PackageManagerService.java revision d9d438ac4e851275abb4ddc6671f74701e07b4fc
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.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
55import static android.content.pm.PackageManager.INSTALL_INTERNAL;
56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
62import static android.content.pm.PackageManager.MATCH_ALL;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
75import static android.content.pm.PackageManager.PERMISSION_DENIED;
76import static android.content.pm.PackageManager.PERMISSION_GRANTED;
77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
78import static android.content.pm.PackageParser.isApkFile;
79import static android.os.Process.FIRST_APPLICATION_UID;
80import static android.os.Process.PACKAGE_INFO_GID;
81import static android.os.Process.SYSTEM_UID;
82import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
83import static android.system.OsConstants.O_CREAT;
84import static android.system.OsConstants.O_RDWR;
85
86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
87import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
88import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
89import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
90import static com.android.internal.util.ArrayUtils.appendInt;
91import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
92import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
94import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
95import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
96import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
98import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
102
103import android.Manifest;
104import android.annotation.NonNull;
105import android.annotation.Nullable;
106import android.app.ActivityManager;
107import android.app.ActivityManagerNative;
108import android.app.IActivityManager;
109import android.app.admin.DevicePolicyManagerInternal;
110import android.app.admin.IDevicePolicyManager;
111import android.app.admin.SecurityLog;
112import android.app.backup.IBackupManager;
113import android.content.BroadcastReceiver;
114import android.content.ComponentName;
115import android.content.Context;
116import android.content.IIntentReceiver;
117import android.content.Intent;
118import android.content.IntentFilter;
119import android.content.IntentFilter.AuthorityEntry;
120import android.content.IntentSender;
121import android.content.IntentSender.SendIntentException;
122import android.content.ServiceConnection;
123import android.content.pm.ActivityInfo;
124import android.content.pm.ApplicationInfo;
125import android.content.pm.AppsQueryHelper;
126import android.content.pm.ComponentInfo;
127import android.content.pm.EphemeralApplicationInfo;
128import android.content.pm.EphemeralResolveInfo;
129import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
130import android.content.pm.FeatureInfo;
131import android.content.pm.IOnPermissionsChangeListener;
132import android.content.pm.IPackageDataObserver;
133import android.content.pm.IPackageDeleteObserver;
134import android.content.pm.IPackageDeleteObserver2;
135import android.content.pm.IPackageInstallObserver2;
136import android.content.pm.IPackageInstaller;
137import android.content.pm.IPackageManager;
138import android.content.pm.IPackageMoveObserver;
139import android.content.pm.IPackageStatsObserver;
140import android.content.pm.InstrumentationInfo;
141import android.content.pm.IntentFilterVerificationInfo;
142import android.content.pm.KeySet;
143import android.content.pm.PackageCleanItem;
144import android.content.pm.PackageInfo;
145import android.content.pm.PackageInfoLite;
146import android.content.pm.PackageInstaller;
147import android.content.pm.PackageManager;
148import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
149import android.content.pm.PackageManagerInternal;
150import android.content.pm.PackageParser;
151import android.content.pm.PackageParser.ActivityIntentInfo;
152import android.content.pm.PackageParser.IntentInfo;
153import android.content.pm.PackageParser.PackageLite;
154import android.content.pm.PackageParser.PackageParserException;
155import android.content.pm.PackageStats;
156import android.content.pm.PackageUserState;
157import android.content.pm.ParceledListSlice;
158import android.content.pm.PermissionGroupInfo;
159import android.content.pm.PermissionInfo;
160import android.content.pm.ProviderInfo;
161import android.content.pm.ResolveInfo;
162import android.content.pm.ServiceInfo;
163import android.content.pm.Signature;
164import android.content.pm.UserInfo;
165import android.content.pm.VerifierDeviceIdentity;
166import android.content.pm.VerifierInfo;
167import android.content.res.Resources;
168import android.graphics.Bitmap;
169import android.hardware.display.DisplayManager;
170import android.net.Uri;
171import android.os.Binder;
172import android.os.Build;
173import android.os.Bundle;
174import android.os.Debug;
175import android.os.Environment;
176import android.os.Environment.UserEnvironment;
177import android.os.FileUtils;
178import android.os.Handler;
179import android.os.IBinder;
180import android.os.Looper;
181import android.os.Message;
182import android.os.Parcel;
183import android.os.ParcelFileDescriptor;
184import android.os.Process;
185import android.os.RemoteCallbackList;
186import android.os.RemoteException;
187import android.os.ResultReceiver;
188import android.os.SELinux;
189import android.os.ServiceManager;
190import android.os.SystemClock;
191import android.os.SystemProperties;
192import android.os.Trace;
193import android.os.UserHandle;
194import android.os.UserManager;
195import android.os.storage.IMountService;
196import android.os.storage.MountServiceInternal;
197import android.os.storage.StorageEventListener;
198import android.os.storage.StorageManager;
199import android.os.storage.VolumeInfo;
200import android.os.storage.VolumeRecord;
201import android.security.KeyStore;
202import android.security.SystemKeyStore;
203import android.system.ErrnoException;
204import android.system.Os;
205import android.text.TextUtils;
206import android.text.format.DateUtils;
207import android.util.ArrayMap;
208import android.util.ArraySet;
209import android.util.AtomicFile;
210import android.util.DisplayMetrics;
211import android.util.EventLog;
212import android.util.ExceptionUtils;
213import android.util.Log;
214import android.util.LogPrinter;
215import android.util.MathUtils;
216import android.util.PrintStreamPrinter;
217import android.util.Slog;
218import android.util.SparseArray;
219import android.util.SparseBooleanArray;
220import android.util.SparseIntArray;
221import android.util.Xml;
222import android.view.Display;
223
224import com.android.internal.R;
225import com.android.internal.annotations.GuardedBy;
226import com.android.internal.app.IMediaContainerService;
227import com.android.internal.app.ResolverActivity;
228import com.android.internal.content.NativeLibraryHelper;
229import com.android.internal.content.PackageHelper;
230import com.android.internal.os.IParcelFileDescriptorFactory;
231import com.android.internal.os.InstallerConnection.InstallerException;
232import com.android.internal.os.SomeArgs;
233import com.android.internal.os.Zygote;
234import com.android.internal.util.ArrayUtils;
235import com.android.internal.util.FastPrintWriter;
236import com.android.internal.util.FastXmlSerializer;
237import com.android.internal.util.IndentingPrintWriter;
238import com.android.internal.util.Preconditions;
239import com.android.internal.util.XmlUtils;
240import com.android.server.EventLogTags;
241import com.android.server.FgThread;
242import com.android.server.IntentResolver;
243import com.android.server.LocalServices;
244import com.android.server.ServiceThread;
245import com.android.server.SystemConfig;
246import com.android.server.Watchdog;
247import com.android.server.pm.PermissionsState.PermissionState;
248import com.android.server.pm.Settings.DatabaseVersion;
249import com.android.server.pm.Settings.VersionInfo;
250import com.android.server.storage.DeviceStorageMonitorInternal;
251
252import dalvik.system.DexFile;
253import dalvik.system.VMRuntime;
254
255import libcore.io.IoUtils;
256import libcore.util.EmptyArray;
257
258import org.xmlpull.v1.XmlPullParser;
259import org.xmlpull.v1.XmlPullParserException;
260import org.xmlpull.v1.XmlSerializer;
261
262import java.io.BufferedInputStream;
263import java.io.BufferedOutputStream;
264import java.io.BufferedReader;
265import java.io.ByteArrayInputStream;
266import java.io.ByteArrayOutputStream;
267import java.io.File;
268import java.io.FileDescriptor;
269import java.io.FileNotFoundException;
270import java.io.FileOutputStream;
271import java.io.FileReader;
272import java.io.FilenameFilter;
273import java.io.IOException;
274import java.io.InputStream;
275import java.io.PrintWriter;
276import java.nio.charset.StandardCharsets;
277import java.security.MessageDigest;
278import java.security.NoSuchAlgorithmException;
279import java.security.PublicKey;
280import java.security.cert.Certificate;
281import java.security.cert.CertificateEncodingException;
282import java.security.cert.CertificateException;
283import java.text.SimpleDateFormat;
284import java.util.ArrayList;
285import java.util.Arrays;
286import java.util.Collection;
287import java.util.Collections;
288import java.util.Comparator;
289import java.util.Date;
290import java.util.HashSet;
291import java.util.Iterator;
292import java.util.List;
293import java.util.Map;
294import java.util.Objects;
295import java.util.Set;
296import java.util.concurrent.CountDownLatch;
297import java.util.concurrent.TimeUnit;
298import java.util.concurrent.atomic.AtomicBoolean;
299import java.util.concurrent.atomic.AtomicInteger;
300import java.util.concurrent.atomic.AtomicLong;
301
302/**
303 * Keep track of all those .apks everywhere.
304 *
305 * This is very central to the platform's security; please run the unit
306 * tests whenever making modifications here:
307 *
308runtest -c android.content.pm.PackageManagerTests frameworks-core
309 *
310 * {@hide}
311 */
312public class PackageManagerService extends IPackageManager.Stub {
313    static final String TAG = "PackageManager";
314    static final boolean DEBUG_SETTINGS = false;
315    static final boolean DEBUG_PREFERRED = false;
316    static final boolean DEBUG_UPGRADE = false;
317    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
318    private static final boolean DEBUG_BACKUP = false;
319    private static final boolean DEBUG_INSTALL = false;
320    private static final boolean DEBUG_REMOVE = false;
321    private static final boolean DEBUG_BROADCASTS = false;
322    private static final boolean DEBUG_SHOW_INFO = false;
323    private static final boolean DEBUG_PACKAGE_INFO = false;
324    private static final boolean DEBUG_INTENT_MATCHING = false;
325    private static final boolean DEBUG_PACKAGE_SCANNING = false;
326    private static final boolean DEBUG_VERIFY = false;
327    private static final boolean DEBUG_FILTERS = false;
328
329    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
330    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
331    // user, but by default initialize to this.
332    static final boolean DEBUG_DEXOPT = false;
333
334    private static final boolean DEBUG_ABI_SELECTION = false;
335    private static final boolean DEBUG_EPHEMERAL = false;
336    private static final boolean DEBUG_TRIAGED_MISSING = false;
337    private static final boolean DEBUG_APP_DATA = false;
338
339    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
340
341    private static final boolean DISABLE_EPHEMERAL_APPS = true;
342
343    private static final int RADIO_UID = Process.PHONE_UID;
344    private static final int LOG_UID = Process.LOG_UID;
345    private static final int NFC_UID = Process.NFC_UID;
346    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
347    private static final int SHELL_UID = Process.SHELL_UID;
348
349    // Cap the size of permission trees that 3rd party apps can define
350    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
351
352    // Suffix used during package installation when copying/moving
353    // package apks to install directory.
354    private static final String INSTALL_PACKAGE_SUFFIX = "-";
355
356    static final int SCAN_NO_DEX = 1<<1;
357    static final int SCAN_FORCE_DEX = 1<<2;
358    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
359    static final int SCAN_NEW_INSTALL = 1<<4;
360    static final int SCAN_NO_PATHS = 1<<5;
361    static final int SCAN_UPDATE_TIME = 1<<6;
362    static final int SCAN_DEFER_DEX = 1<<7;
363    static final int SCAN_BOOTING = 1<<8;
364    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
365    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
366    static final int SCAN_REPLACING = 1<<11;
367    static final int SCAN_REQUIRE_KNOWN = 1<<12;
368    static final int SCAN_MOVE = 1<<13;
369    static final int SCAN_INITIAL = 1<<14;
370    static final int SCAN_CHECK_ONLY = 1<<15;
371    static final int SCAN_DONT_KILL_APP = 1<<17;
372
373    static final int REMOVE_CHATTY = 1<<16;
374
375    private static final int[] EMPTY_INT_ARRAY = new int[0];
376
377    /**
378     * Timeout (in milliseconds) after which the watchdog should declare that
379     * our handler thread is wedged.  The usual default for such things is one
380     * minute but we sometimes do very lengthy I/O operations on this thread,
381     * such as installing multi-gigabyte applications, so ours needs to be longer.
382     */
383    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
384
385    /**
386     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
387     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
388     * settings entry if available, otherwise we use the hardcoded default.  If it's been
389     * more than this long since the last fstrim, we force one during the boot sequence.
390     *
391     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
392     * one gets run at the next available charging+idle time.  This final mandatory
393     * no-fstrim check kicks in only of the other scheduling criteria is never met.
394     */
395    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
396
397    /**
398     * Whether verification is enabled by default.
399     */
400    private static final boolean DEFAULT_VERIFY_ENABLE = true;
401
402    /**
403     * The default maximum time to wait for the verification agent to return in
404     * milliseconds.
405     */
406    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
407
408    /**
409     * The default response for package verification timeout.
410     *
411     * This can be either PackageManager.VERIFICATION_ALLOW or
412     * PackageManager.VERIFICATION_REJECT.
413     */
414    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
415
416    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
417
418    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
419            DEFAULT_CONTAINER_PACKAGE,
420            "com.android.defcontainer.DefaultContainerService");
421
422    private static final String KILL_APP_REASON_GIDS_CHANGED =
423            "permission grant or revoke changed gids";
424
425    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
426            "permissions revoked";
427
428    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
429
430    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
431
432    /** Permission grant: not grant the permission. */
433    private static final int GRANT_DENIED = 1;
434
435    /** Permission grant: grant the permission as an install permission. */
436    private static final int GRANT_INSTALL = 2;
437
438    /** Permission grant: grant the permission as a runtime one. */
439    private static final int GRANT_RUNTIME = 3;
440
441    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
442    private static final int GRANT_UPGRADE = 4;
443
444    /** Canonical intent used to identify what counts as a "web browser" app */
445    private static final Intent sBrowserIntent;
446    static {
447        sBrowserIntent = new Intent();
448        sBrowserIntent.setAction(Intent.ACTION_VIEW);
449        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
450        sBrowserIntent.setData(Uri.parse("http:"));
451    }
452
453    /**
454     * The set of all protected actions [i.e. those actions for which a high priority
455     * intent filter is disallowed].
456     */
457    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
458    static {
459        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
460        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
461        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
462        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
463    }
464
465    // Compilation reasons.
466    public static final int REASON_FIRST_BOOT = 0;
467    public static final int REASON_BOOT = 1;
468    public static final int REASON_INSTALL = 2;
469    public static final int REASON_BACKGROUND_DEXOPT = 3;
470    public static final int REASON_AB_OTA = 4;
471    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
472    public static final int REASON_SHARED_APK = 6;
473    public static final int REASON_FORCED_DEXOPT = 7;
474
475    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
476
477    final ServiceThread mHandlerThread;
478
479    final PackageHandler mHandler;
480
481    private final ProcessLoggingHandler mProcessLoggingHandler;
482
483    /**
484     * Messages for {@link #mHandler} that need to wait for system ready before
485     * being dispatched.
486     */
487    private ArrayList<Message> mPostSystemReadyMessages;
488
489    final int mSdkVersion = Build.VERSION.SDK_INT;
490
491    final Context mContext;
492    final boolean mFactoryTest;
493    final boolean mOnlyCore;
494    final DisplayMetrics mMetrics;
495    final int mDefParseFlags;
496    final String[] mSeparateProcesses;
497    final boolean mIsUpgrade;
498    final boolean mIsPreNUpgrade;
499
500    /** The location for ASEC container files on internal storage. */
501    final String mAsecInternalPath;
502
503    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
504    // LOCK HELD.  Can be called with mInstallLock held.
505    @GuardedBy("mInstallLock")
506    final Installer mInstaller;
507
508    /** Directory where installed third-party apps stored */
509    final File mAppInstallDir;
510    final File mEphemeralInstallDir;
511
512    /**
513     * Directory to which applications installed internally have their
514     * 32 bit native libraries copied.
515     */
516    private File mAppLib32InstallDir;
517
518    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
519    // apps.
520    final File mDrmAppPrivateInstallDir;
521
522    // ----------------------------------------------------------------
523
524    // Lock for state used when installing and doing other long running
525    // operations.  Methods that must be called with this lock held have
526    // the suffix "LI".
527    final Object mInstallLock = new Object();
528
529    // ----------------------------------------------------------------
530
531    // Keys are String (package name), values are Package.  This also serves
532    // as the lock for the global state.  Methods that must be called with
533    // this lock held have the prefix "LP".
534    @GuardedBy("mPackages")
535    final ArrayMap<String, PackageParser.Package> mPackages =
536            new ArrayMap<String, PackageParser.Package>();
537
538    final ArrayMap<String, Set<String>> mKnownCodebase =
539            new ArrayMap<String, Set<String>>();
540
541    // Tracks available target package names -> overlay package paths.
542    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
543        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
544
545    /**
546     * Tracks new system packages [received in an OTA] that we expect to
547     * find updated user-installed versions. Keys are package name, values
548     * are package location.
549     */
550    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
551    /**
552     * Tracks high priority intent filters for protected actions. During boot, certain
553     * filter actions are protected and should never be allowed to have a high priority
554     * intent filter for them. However, there is one, and only one exception -- the
555     * setup wizard. It must be able to define a high priority intent filter for these
556     * actions to ensure there are no escapes from the wizard. We need to delay processing
557     * of these during boot as we need to look at all of the system packages in order
558     * to know which component is the setup wizard.
559     */
560    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
561    /**
562     * Whether or not processing protected filters should be deferred.
563     */
564    private boolean mDeferProtectedFilters = true;
565
566    /**
567     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
568     */
569    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
570    /**
571     * Whether or not system app permissions should be promoted from install to runtime.
572     */
573    boolean mPromoteSystemApps;
574
575    final Settings mSettings;
576    boolean mRestoredSettings;
577
578    // System configuration read by SystemConfig.
579    final int[] mGlobalGids;
580    final SparseArray<ArraySet<String>> mSystemPermissions;
581    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
582
583    // If mac_permissions.xml was found for seinfo labeling.
584    boolean mFoundPolicyFile;
585
586    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
587
588    public static final class SharedLibraryEntry {
589        public final String path;
590        public final String apk;
591
592        SharedLibraryEntry(String _path, String _apk) {
593            path = _path;
594            apk = _apk;
595        }
596    }
597
598    // Currently known shared libraries.
599    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
600            new ArrayMap<String, SharedLibraryEntry>();
601
602    // All available activities, for your resolving pleasure.
603    final ActivityIntentResolver mActivities =
604            new ActivityIntentResolver();
605
606    // All available receivers, for your resolving pleasure.
607    final ActivityIntentResolver mReceivers =
608            new ActivityIntentResolver();
609
610    // All available services, for your resolving pleasure.
611    final ServiceIntentResolver mServices = new ServiceIntentResolver();
612
613    // All available providers, for your resolving pleasure.
614    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
615
616    // Mapping from provider base names (first directory in content URI codePath)
617    // to the provider information.
618    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
619            new ArrayMap<String, PackageParser.Provider>();
620
621    // Mapping from instrumentation class names to info about them.
622    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
623            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
624
625    // Mapping from permission names to info about them.
626    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
627            new ArrayMap<String, PackageParser.PermissionGroup>();
628
629    // Packages whose data we have transfered into another package, thus
630    // should no longer exist.
631    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
632
633    // Broadcast actions that are only available to the system.
634    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
635
636    /** List of packages waiting for verification. */
637    final SparseArray<PackageVerificationState> mPendingVerification
638            = new SparseArray<PackageVerificationState>();
639
640    /** Set of packages associated with each app op permission. */
641    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
642
643    final PackageInstallerService mInstallerService;
644
645    private final PackageDexOptimizer mPackageDexOptimizer;
646
647    private AtomicInteger mNextMoveId = new AtomicInteger();
648    private final MoveCallbacks mMoveCallbacks;
649
650    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
651
652    // Cache of users who need badging.
653    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
654
655    /** Token for keys in mPendingVerification. */
656    private int mPendingVerificationToken = 0;
657
658    volatile boolean mSystemReady;
659    volatile boolean mSafeMode;
660    volatile boolean mHasSystemUidErrors;
661
662    ApplicationInfo mAndroidApplication;
663    final ActivityInfo mResolveActivity = new ActivityInfo();
664    final ResolveInfo mResolveInfo = new ResolveInfo();
665    ComponentName mResolveComponentName;
666    PackageParser.Package mPlatformPackage;
667    ComponentName mCustomResolverComponentName;
668
669    boolean mResolverReplaced = false;
670
671    private final @Nullable ComponentName mIntentFilterVerifierComponent;
672    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
673
674    private int mIntentFilterVerificationToken = 0;
675
676    /** Component that knows whether or not an ephemeral application exists */
677    final ComponentName mEphemeralResolverComponent;
678    /** The service connection to the ephemeral resolver */
679    final EphemeralResolverConnection mEphemeralResolverConnection;
680
681    /** Component used to install ephemeral applications */
682    final ComponentName mEphemeralInstallerComponent;
683    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
684    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
685
686    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
687            = new SparseArray<IntentFilterVerificationState>();
688
689    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
690            new DefaultPermissionGrantPolicy(this);
691
692    // List of packages names to keep cached, even if they are uninstalled for all users
693    private List<String> mKeepUninstalledPackages;
694
695    private static class IFVerificationParams {
696        PackageParser.Package pkg;
697        boolean replacing;
698        int userId;
699        int verifierUid;
700
701        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
702                int _userId, int _verifierUid) {
703            pkg = _pkg;
704            replacing = _replacing;
705            userId = _userId;
706            replacing = _replacing;
707            verifierUid = _verifierUid;
708        }
709    }
710
711    private interface IntentFilterVerifier<T extends IntentFilter> {
712        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
713                                               T filter, String packageName);
714        void startVerifications(int userId);
715        void receiveVerificationResponse(int verificationId);
716    }
717
718    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
719        private Context mContext;
720        private ComponentName mIntentFilterVerifierComponent;
721        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
722
723        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
724            mContext = context;
725            mIntentFilterVerifierComponent = verifierComponent;
726        }
727
728        private String getDefaultScheme() {
729            return IntentFilter.SCHEME_HTTPS;
730        }
731
732        @Override
733        public void startVerifications(int userId) {
734            // Launch verifications requests
735            int count = mCurrentIntentFilterVerifications.size();
736            for (int n=0; n<count; n++) {
737                int verificationId = mCurrentIntentFilterVerifications.get(n);
738                final IntentFilterVerificationState ivs =
739                        mIntentFilterVerificationStates.get(verificationId);
740
741                String packageName = ivs.getPackageName();
742
743                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
744                final int filterCount = filters.size();
745                ArraySet<String> domainsSet = new ArraySet<>();
746                for (int m=0; m<filterCount; m++) {
747                    PackageParser.ActivityIntentInfo filter = filters.get(m);
748                    domainsSet.addAll(filter.getHostsList());
749                }
750                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
751                synchronized (mPackages) {
752                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
753                            packageName, domainsList) != null) {
754                        scheduleWriteSettingsLocked();
755                    }
756                }
757                sendVerificationRequest(userId, verificationId, ivs);
758            }
759            mCurrentIntentFilterVerifications.clear();
760        }
761
762        private void sendVerificationRequest(int userId, int verificationId,
763                IntentFilterVerificationState ivs) {
764
765            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
766            verificationIntent.putExtra(
767                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
768                    verificationId);
769            verificationIntent.putExtra(
770                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
771                    getDefaultScheme());
772            verificationIntent.putExtra(
773                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
774                    ivs.getHostsString());
775            verificationIntent.putExtra(
776                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
777                    ivs.getPackageName());
778            verificationIntent.setComponent(mIntentFilterVerifierComponent);
779            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
780
781            UserHandle user = new UserHandle(userId);
782            mContext.sendBroadcastAsUser(verificationIntent, user);
783            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
784                    "Sending IntentFilter verification broadcast");
785        }
786
787        public void receiveVerificationResponse(int verificationId) {
788            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
789
790            final boolean verified = ivs.isVerified();
791
792            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
793            final int count = filters.size();
794            if (DEBUG_DOMAIN_VERIFICATION) {
795                Slog.i(TAG, "Received verification response " + verificationId
796                        + " for " + count + " filters, verified=" + verified);
797            }
798            for (int n=0; n<count; n++) {
799                PackageParser.ActivityIntentInfo filter = filters.get(n);
800                filter.setVerified(verified);
801
802                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
803                        + " verified with result:" + verified + " and hosts:"
804                        + ivs.getHostsString());
805            }
806
807            mIntentFilterVerificationStates.remove(verificationId);
808
809            final String packageName = ivs.getPackageName();
810            IntentFilterVerificationInfo ivi = null;
811
812            synchronized (mPackages) {
813                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
814            }
815            if (ivi == null) {
816                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
817                        + verificationId + " packageName:" + packageName);
818                return;
819            }
820            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
821                    "Updating IntentFilterVerificationInfo for package " + packageName
822                            +" verificationId:" + verificationId);
823
824            synchronized (mPackages) {
825                if (verified) {
826                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
827                } else {
828                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
829                }
830                scheduleWriteSettingsLocked();
831
832                final int userId = ivs.getUserId();
833                if (userId != UserHandle.USER_ALL) {
834                    final int userStatus =
835                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
836
837                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
838                    boolean needUpdate = false;
839
840                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
841                    // already been set by the User thru the Disambiguation dialog
842                    switch (userStatus) {
843                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
844                            if (verified) {
845                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
846                            } else {
847                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
848                            }
849                            needUpdate = true;
850                            break;
851
852                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
853                            if (verified) {
854                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
855                                needUpdate = true;
856                            }
857                            break;
858
859                        default:
860                            // Nothing to do
861                    }
862
863                    if (needUpdate) {
864                        mSettings.updateIntentFilterVerificationStatusLPw(
865                                packageName, updatedStatus, userId);
866                        scheduleWritePackageRestrictionsLocked(userId);
867                    }
868                }
869            }
870        }
871
872        @Override
873        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
874                    ActivityIntentInfo filter, String packageName) {
875            if (!hasValidDomains(filter)) {
876                return false;
877            }
878            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
879            if (ivs == null) {
880                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
881                        packageName);
882            }
883            if (DEBUG_DOMAIN_VERIFICATION) {
884                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
885            }
886            ivs.addFilter(filter);
887            return true;
888        }
889
890        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
891                int userId, int verificationId, String packageName) {
892            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
893                    verifierUid, userId, packageName);
894            ivs.setPendingState();
895            synchronized (mPackages) {
896                mIntentFilterVerificationStates.append(verificationId, ivs);
897                mCurrentIntentFilterVerifications.add(verificationId);
898            }
899            return ivs;
900        }
901    }
902
903    private static boolean hasValidDomains(ActivityIntentInfo filter) {
904        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
905                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
906                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
907    }
908
909    // Set of pending broadcasts for aggregating enable/disable of components.
910    static class PendingPackageBroadcasts {
911        // for each user id, a map of <package name -> components within that package>
912        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
913
914        public PendingPackageBroadcasts() {
915            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
916        }
917
918        public ArrayList<String> get(int userId, String packageName) {
919            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
920            return packages.get(packageName);
921        }
922
923        public void put(int userId, String packageName, ArrayList<String> components) {
924            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
925            packages.put(packageName, components);
926        }
927
928        public void remove(int userId, String packageName) {
929            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
930            if (packages != null) {
931                packages.remove(packageName);
932            }
933        }
934
935        public void remove(int userId) {
936            mUidMap.remove(userId);
937        }
938
939        public int userIdCount() {
940            return mUidMap.size();
941        }
942
943        public int userIdAt(int n) {
944            return mUidMap.keyAt(n);
945        }
946
947        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
948            return mUidMap.get(userId);
949        }
950
951        public int size() {
952            // total number of pending broadcast entries across all userIds
953            int num = 0;
954            for (int i = 0; i< mUidMap.size(); i++) {
955                num += mUidMap.valueAt(i).size();
956            }
957            return num;
958        }
959
960        public void clear() {
961            mUidMap.clear();
962        }
963
964        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
965            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
966            if (map == null) {
967                map = new ArrayMap<String, ArrayList<String>>();
968                mUidMap.put(userId, map);
969            }
970            return map;
971        }
972    }
973    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
974
975    // Service Connection to remote media container service to copy
976    // package uri's from external media onto secure containers
977    // or internal storage.
978    private IMediaContainerService mContainerService = null;
979
980    static final int SEND_PENDING_BROADCAST = 1;
981    static final int MCS_BOUND = 3;
982    static final int END_COPY = 4;
983    static final int INIT_COPY = 5;
984    static final int MCS_UNBIND = 6;
985    static final int START_CLEANING_PACKAGE = 7;
986    static final int FIND_INSTALL_LOC = 8;
987    static final int POST_INSTALL = 9;
988    static final int MCS_RECONNECT = 10;
989    static final int MCS_GIVE_UP = 11;
990    static final int UPDATED_MEDIA_STATUS = 12;
991    static final int WRITE_SETTINGS = 13;
992    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
993    static final int PACKAGE_VERIFIED = 15;
994    static final int CHECK_PENDING_VERIFICATION = 16;
995    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
996    static final int INTENT_FILTER_VERIFIED = 18;
997
998    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
999
1000    // Delay time in millisecs
1001    static final int BROADCAST_DELAY = 10 * 1000;
1002
1003    static UserManagerService sUserManager;
1004
1005    // Stores a list of users whose package restrictions file needs to be updated
1006    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1007
1008    final private DefaultContainerConnection mDefContainerConn =
1009            new DefaultContainerConnection();
1010    class DefaultContainerConnection implements ServiceConnection {
1011        public void onServiceConnected(ComponentName name, IBinder service) {
1012            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1013            IMediaContainerService imcs =
1014                IMediaContainerService.Stub.asInterface(service);
1015            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1016        }
1017
1018        public void onServiceDisconnected(ComponentName name) {
1019            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1020        }
1021    }
1022
1023    // Recordkeeping of restore-after-install operations that are currently in flight
1024    // between the Package Manager and the Backup Manager
1025    static class PostInstallData {
1026        public InstallArgs args;
1027        public PackageInstalledInfo res;
1028
1029        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1030            args = _a;
1031            res = _r;
1032        }
1033    }
1034
1035    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1036    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1037
1038    // XML tags for backup/restore of various bits of state
1039    private static final String TAG_PREFERRED_BACKUP = "pa";
1040    private static final String TAG_DEFAULT_APPS = "da";
1041    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1042
1043    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1044    private static final String TAG_ALL_GRANTS = "rt-grants";
1045    private static final String TAG_GRANT = "grant";
1046    private static final String ATTR_PACKAGE_NAME = "pkg";
1047
1048    private static final String TAG_PERMISSION = "perm";
1049    private static final String ATTR_PERMISSION_NAME = "name";
1050    private static final String ATTR_IS_GRANTED = "g";
1051    private static final String ATTR_USER_SET = "set";
1052    private static final String ATTR_USER_FIXED = "fixed";
1053    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1054
1055    // System/policy permission grants are not backed up
1056    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1057            FLAG_PERMISSION_POLICY_FIXED
1058            | FLAG_PERMISSION_SYSTEM_FIXED
1059            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1060
1061    // And we back up these user-adjusted states
1062    private static final int USER_RUNTIME_GRANT_MASK =
1063            FLAG_PERMISSION_USER_SET
1064            | FLAG_PERMISSION_USER_FIXED
1065            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1066
1067    final @Nullable String mRequiredVerifierPackage;
1068    final @Nullable String mRequiredInstallerPackage;
1069    final @Nullable String mSetupWizardPackage;
1070
1071    private final PackageUsage mPackageUsage = new PackageUsage();
1072
1073    private class PackageUsage {
1074        private static final int WRITE_INTERVAL
1075            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1076
1077        private final Object mFileLock = new Object();
1078        private final AtomicLong mLastWritten = new AtomicLong(0);
1079        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1080
1081        private boolean mIsHistoricalPackageUsageAvailable = true;
1082
1083        boolean isHistoricalPackageUsageAvailable() {
1084            return mIsHistoricalPackageUsageAvailable;
1085        }
1086
1087        void write(boolean force) {
1088            if (force) {
1089                writeInternal();
1090                return;
1091            }
1092            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1093                && !DEBUG_DEXOPT) {
1094                return;
1095            }
1096            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1097                new Thread("PackageUsage_DiskWriter") {
1098                    @Override
1099                    public void run() {
1100                        try {
1101                            writeInternal();
1102                        } finally {
1103                            mBackgroundWriteRunning.set(false);
1104                        }
1105                    }
1106                }.start();
1107            }
1108        }
1109
1110        private void writeInternal() {
1111            synchronized (mPackages) {
1112                synchronized (mFileLock) {
1113                    AtomicFile file = getFile();
1114                    FileOutputStream f = null;
1115                    try {
1116                        f = file.startWrite();
1117                        BufferedOutputStream out = new BufferedOutputStream(f);
1118                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1119                        StringBuilder sb = new StringBuilder();
1120                        for (PackageParser.Package pkg : mPackages.values()) {
1121                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1122                                continue;
1123                            }
1124                            sb.setLength(0);
1125                            sb.append(pkg.packageName);
1126                            sb.append(' ');
1127                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1128                            sb.append('\n');
1129                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1130                        }
1131                        out.flush();
1132                        file.finishWrite(f);
1133                    } catch (IOException e) {
1134                        if (f != null) {
1135                            file.failWrite(f);
1136                        }
1137                        Log.e(TAG, "Failed to write package usage times", e);
1138                    }
1139                }
1140            }
1141            mLastWritten.set(SystemClock.elapsedRealtime());
1142        }
1143
1144        void readLP() {
1145            synchronized (mFileLock) {
1146                AtomicFile file = getFile();
1147                BufferedInputStream in = null;
1148                try {
1149                    in = new BufferedInputStream(file.openRead());
1150                    StringBuffer sb = new StringBuffer();
1151                    while (true) {
1152                        String packageName = readToken(in, sb, ' ');
1153                        if (packageName == null) {
1154                            break;
1155                        }
1156                        String timeInMillisString = readToken(in, sb, '\n');
1157                        if (timeInMillisString == null) {
1158                            throw new IOException("Failed to find last usage time for package "
1159                                                  + packageName);
1160                        }
1161                        PackageParser.Package pkg = mPackages.get(packageName);
1162                        if (pkg == null) {
1163                            continue;
1164                        }
1165                        long timeInMillis;
1166                        try {
1167                            timeInMillis = Long.parseLong(timeInMillisString);
1168                        } catch (NumberFormatException e) {
1169                            throw new IOException("Failed to parse " + timeInMillisString
1170                                                  + " as a long.", e);
1171                        }
1172                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1173                    }
1174                } catch (FileNotFoundException expected) {
1175                    mIsHistoricalPackageUsageAvailable = false;
1176                } catch (IOException e) {
1177                    Log.w(TAG, "Failed to read package usage times", e);
1178                } finally {
1179                    IoUtils.closeQuietly(in);
1180                }
1181            }
1182            mLastWritten.set(SystemClock.elapsedRealtime());
1183        }
1184
1185        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1186                throws IOException {
1187            sb.setLength(0);
1188            while (true) {
1189                int ch = in.read();
1190                if (ch == -1) {
1191                    if (sb.length() == 0) {
1192                        return null;
1193                    }
1194                    throw new IOException("Unexpected EOF");
1195                }
1196                if (ch == endOfToken) {
1197                    return sb.toString();
1198                }
1199                sb.append((char)ch);
1200            }
1201        }
1202
1203        private AtomicFile getFile() {
1204            File dataDir = Environment.getDataDirectory();
1205            File systemDir = new File(dataDir, "system");
1206            File fname = new File(systemDir, "package-usage.list");
1207            return new AtomicFile(fname);
1208        }
1209    }
1210
1211    class PackageHandler extends Handler {
1212        private boolean mBound = false;
1213        final ArrayList<HandlerParams> mPendingInstalls =
1214            new ArrayList<HandlerParams>();
1215
1216        private boolean connectToService() {
1217            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1218                    " DefaultContainerService");
1219            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1220            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1221            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1222                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1223                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1224                mBound = true;
1225                return true;
1226            }
1227            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1228            return false;
1229        }
1230
1231        private void disconnectService() {
1232            mContainerService = null;
1233            mBound = false;
1234            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1235            mContext.unbindService(mDefContainerConn);
1236            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1237        }
1238
1239        PackageHandler(Looper looper) {
1240            super(looper);
1241        }
1242
1243        public void handleMessage(Message msg) {
1244            try {
1245                doHandleMessage(msg);
1246            } finally {
1247                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1248            }
1249        }
1250
1251        void doHandleMessage(Message msg) {
1252            switch (msg.what) {
1253                case INIT_COPY: {
1254                    HandlerParams params = (HandlerParams) msg.obj;
1255                    int idx = mPendingInstalls.size();
1256                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1257                    // If a bind was already initiated we dont really
1258                    // need to do anything. The pending install
1259                    // will be processed later on.
1260                    if (!mBound) {
1261                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1262                                System.identityHashCode(mHandler));
1263                        // If this is the only one pending we might
1264                        // have to bind to the service again.
1265                        if (!connectToService()) {
1266                            Slog.e(TAG, "Failed to bind to media container service");
1267                            params.serviceError();
1268                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1269                                    System.identityHashCode(mHandler));
1270                            if (params.traceMethod != null) {
1271                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1272                                        params.traceCookie);
1273                            }
1274                            return;
1275                        } else {
1276                            // Once we bind to the service, the first
1277                            // pending request will be processed.
1278                            mPendingInstalls.add(idx, params);
1279                        }
1280                    } else {
1281                        mPendingInstalls.add(idx, params);
1282                        // Already bound to the service. Just make
1283                        // sure we trigger off processing the first request.
1284                        if (idx == 0) {
1285                            mHandler.sendEmptyMessage(MCS_BOUND);
1286                        }
1287                    }
1288                    break;
1289                }
1290                case MCS_BOUND: {
1291                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1292                    if (msg.obj != null) {
1293                        mContainerService = (IMediaContainerService) msg.obj;
1294                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1295                                System.identityHashCode(mHandler));
1296                    }
1297                    if (mContainerService == null) {
1298                        if (!mBound) {
1299                            // Something seriously wrong since we are not bound and we are not
1300                            // waiting for connection. Bail out.
1301                            Slog.e(TAG, "Cannot bind to media container service");
1302                            for (HandlerParams params : mPendingInstalls) {
1303                                // Indicate service bind error
1304                                params.serviceError();
1305                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1306                                        System.identityHashCode(params));
1307                                if (params.traceMethod != null) {
1308                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1309                                            params.traceMethod, params.traceCookie);
1310                                }
1311                                return;
1312                            }
1313                            mPendingInstalls.clear();
1314                        } else {
1315                            Slog.w(TAG, "Waiting to connect to media container service");
1316                        }
1317                    } else if (mPendingInstalls.size() > 0) {
1318                        HandlerParams params = mPendingInstalls.get(0);
1319                        if (params != null) {
1320                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1321                                    System.identityHashCode(params));
1322                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1323                            if (params.startCopy()) {
1324                                // We are done...  look for more work or to
1325                                // go idle.
1326                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1327                                        "Checking for more work or unbind...");
1328                                // Delete pending install
1329                                if (mPendingInstalls.size() > 0) {
1330                                    mPendingInstalls.remove(0);
1331                                }
1332                                if (mPendingInstalls.size() == 0) {
1333                                    if (mBound) {
1334                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1335                                                "Posting delayed MCS_UNBIND");
1336                                        removeMessages(MCS_UNBIND);
1337                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1338                                        // Unbind after a little delay, to avoid
1339                                        // continual thrashing.
1340                                        sendMessageDelayed(ubmsg, 10000);
1341                                    }
1342                                } else {
1343                                    // There are more pending requests in queue.
1344                                    // Just post MCS_BOUND message to trigger processing
1345                                    // of next pending install.
1346                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1347                                            "Posting MCS_BOUND for next work");
1348                                    mHandler.sendEmptyMessage(MCS_BOUND);
1349                                }
1350                            }
1351                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1352                        }
1353                    } else {
1354                        // Should never happen ideally.
1355                        Slog.w(TAG, "Empty queue");
1356                    }
1357                    break;
1358                }
1359                case MCS_RECONNECT: {
1360                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1361                    if (mPendingInstalls.size() > 0) {
1362                        if (mBound) {
1363                            disconnectService();
1364                        }
1365                        if (!connectToService()) {
1366                            Slog.e(TAG, "Failed to bind to media container service");
1367                            for (HandlerParams params : mPendingInstalls) {
1368                                // Indicate service bind error
1369                                params.serviceError();
1370                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1371                                        System.identityHashCode(params));
1372                            }
1373                            mPendingInstalls.clear();
1374                        }
1375                    }
1376                    break;
1377                }
1378                case MCS_UNBIND: {
1379                    // If there is no actual work left, then time to unbind.
1380                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1381
1382                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1383                        if (mBound) {
1384                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1385
1386                            disconnectService();
1387                        }
1388                    } else if (mPendingInstalls.size() > 0) {
1389                        // There are more pending requests in queue.
1390                        // Just post MCS_BOUND message to trigger processing
1391                        // of next pending install.
1392                        mHandler.sendEmptyMessage(MCS_BOUND);
1393                    }
1394
1395                    break;
1396                }
1397                case MCS_GIVE_UP: {
1398                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1399                    HandlerParams params = mPendingInstalls.remove(0);
1400                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1401                            System.identityHashCode(params));
1402                    break;
1403                }
1404                case SEND_PENDING_BROADCAST: {
1405                    String packages[];
1406                    ArrayList<String> components[];
1407                    int size = 0;
1408                    int uids[];
1409                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1410                    synchronized (mPackages) {
1411                        if (mPendingBroadcasts == null) {
1412                            return;
1413                        }
1414                        size = mPendingBroadcasts.size();
1415                        if (size <= 0) {
1416                            // Nothing to be done. Just return
1417                            return;
1418                        }
1419                        packages = new String[size];
1420                        components = new ArrayList[size];
1421                        uids = new int[size];
1422                        int i = 0;  // filling out the above arrays
1423
1424                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1425                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1426                            Iterator<Map.Entry<String, ArrayList<String>>> it
1427                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1428                                            .entrySet().iterator();
1429                            while (it.hasNext() && i < size) {
1430                                Map.Entry<String, ArrayList<String>> ent = it.next();
1431                                packages[i] = ent.getKey();
1432                                components[i] = ent.getValue();
1433                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1434                                uids[i] = (ps != null)
1435                                        ? UserHandle.getUid(packageUserId, ps.appId)
1436                                        : -1;
1437                                i++;
1438                            }
1439                        }
1440                        size = i;
1441                        mPendingBroadcasts.clear();
1442                    }
1443                    // Send broadcasts
1444                    for (int i = 0; i < size; i++) {
1445                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1446                    }
1447                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1448                    break;
1449                }
1450                case START_CLEANING_PACKAGE: {
1451                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1452                    final String packageName = (String)msg.obj;
1453                    final int userId = msg.arg1;
1454                    final boolean andCode = msg.arg2 != 0;
1455                    synchronized (mPackages) {
1456                        if (userId == UserHandle.USER_ALL) {
1457                            int[] users = sUserManager.getUserIds();
1458                            for (int user : users) {
1459                                mSettings.addPackageToCleanLPw(
1460                                        new PackageCleanItem(user, packageName, andCode));
1461                            }
1462                        } else {
1463                            mSettings.addPackageToCleanLPw(
1464                                    new PackageCleanItem(userId, packageName, andCode));
1465                        }
1466                    }
1467                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1468                    startCleaningPackages();
1469                } break;
1470                case POST_INSTALL: {
1471                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1472
1473                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1474                    mRunningInstalls.delete(msg.arg1);
1475
1476                    if (data != null) {
1477                        InstallArgs args = data.args;
1478                        PackageInstalledInfo parentRes = data.res;
1479
1480                        final boolean grantPermissions = (args.installFlags
1481                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1482                        final boolean killApp = (args.installFlags
1483                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1484                        final String[] grantedPermissions = args.installGrantPermissions;
1485
1486                        // Handle the parent package
1487                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1488                                grantedPermissions, args.observer);
1489
1490                        // Handle the child packages
1491                        final int childCount = (parentRes.addedChildPackages != null)
1492                                ? parentRes.addedChildPackages.size() : 0;
1493                        for (int i = 0; i < childCount; i++) {
1494                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1495                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1496                                    grantedPermissions, args.observer);
1497                        }
1498
1499                        // Log tracing if needed
1500                        if (args.traceMethod != null) {
1501                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1502                                    args.traceCookie);
1503                        }
1504                    } else {
1505                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1506                    }
1507
1508                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1509                } break;
1510                case UPDATED_MEDIA_STATUS: {
1511                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1512                    boolean reportStatus = msg.arg1 == 1;
1513                    boolean doGc = msg.arg2 == 1;
1514                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1515                    if (doGc) {
1516                        // Force a gc to clear up stale containers.
1517                        Runtime.getRuntime().gc();
1518                    }
1519                    if (msg.obj != null) {
1520                        @SuppressWarnings("unchecked")
1521                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1522                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1523                        // Unload containers
1524                        unloadAllContainers(args);
1525                    }
1526                    if (reportStatus) {
1527                        try {
1528                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1529                            PackageHelper.getMountService().finishMediaUpdate();
1530                        } catch (RemoteException e) {
1531                            Log.e(TAG, "MountService not running?");
1532                        }
1533                    }
1534                } break;
1535                case WRITE_SETTINGS: {
1536                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1537                    synchronized (mPackages) {
1538                        removeMessages(WRITE_SETTINGS);
1539                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1540                        mSettings.writeLPr();
1541                        mDirtyUsers.clear();
1542                    }
1543                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1544                } break;
1545                case WRITE_PACKAGE_RESTRICTIONS: {
1546                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1547                    synchronized (mPackages) {
1548                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1549                        for (int userId : mDirtyUsers) {
1550                            mSettings.writePackageRestrictionsLPr(userId);
1551                        }
1552                        mDirtyUsers.clear();
1553                    }
1554                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1555                } break;
1556                case CHECK_PENDING_VERIFICATION: {
1557                    final int verificationId = msg.arg1;
1558                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1559
1560                    if ((state != null) && !state.timeoutExtended()) {
1561                        final InstallArgs args = state.getInstallArgs();
1562                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1563
1564                        Slog.i(TAG, "Verification timed out for " + originUri);
1565                        mPendingVerification.remove(verificationId);
1566
1567                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1568
1569                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1570                            Slog.i(TAG, "Continuing with installation of " + originUri);
1571                            state.setVerifierResponse(Binder.getCallingUid(),
1572                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1573                            broadcastPackageVerified(verificationId, originUri,
1574                                    PackageManager.VERIFICATION_ALLOW,
1575                                    state.getInstallArgs().getUser());
1576                            try {
1577                                ret = args.copyApk(mContainerService, true);
1578                            } catch (RemoteException e) {
1579                                Slog.e(TAG, "Could not contact the ContainerService");
1580                            }
1581                        } else {
1582                            broadcastPackageVerified(verificationId, originUri,
1583                                    PackageManager.VERIFICATION_REJECT,
1584                                    state.getInstallArgs().getUser());
1585                        }
1586
1587                        Trace.asyncTraceEnd(
1588                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1589
1590                        processPendingInstall(args, ret);
1591                        mHandler.sendEmptyMessage(MCS_UNBIND);
1592                    }
1593                    break;
1594                }
1595                case PACKAGE_VERIFIED: {
1596                    final int verificationId = msg.arg1;
1597
1598                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1599                    if (state == null) {
1600                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1601                        break;
1602                    }
1603
1604                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1605
1606                    state.setVerifierResponse(response.callerUid, response.code);
1607
1608                    if (state.isVerificationComplete()) {
1609                        mPendingVerification.remove(verificationId);
1610
1611                        final InstallArgs args = state.getInstallArgs();
1612                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1613
1614                        int ret;
1615                        if (state.isInstallAllowed()) {
1616                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1617                            broadcastPackageVerified(verificationId, originUri,
1618                                    response.code, state.getInstallArgs().getUser());
1619                            try {
1620                                ret = args.copyApk(mContainerService, true);
1621                            } catch (RemoteException e) {
1622                                Slog.e(TAG, "Could not contact the ContainerService");
1623                            }
1624                        } else {
1625                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1626                        }
1627
1628                        Trace.asyncTraceEnd(
1629                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1630
1631                        processPendingInstall(args, ret);
1632                        mHandler.sendEmptyMessage(MCS_UNBIND);
1633                    }
1634
1635                    break;
1636                }
1637                case START_INTENT_FILTER_VERIFICATIONS: {
1638                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1639                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1640                            params.replacing, params.pkg);
1641                    break;
1642                }
1643                case INTENT_FILTER_VERIFIED: {
1644                    final int verificationId = msg.arg1;
1645
1646                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1647                            verificationId);
1648                    if (state == null) {
1649                        Slog.w(TAG, "Invalid IntentFilter verification token "
1650                                + verificationId + " received");
1651                        break;
1652                    }
1653
1654                    final int userId = state.getUserId();
1655
1656                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1657                            "Processing IntentFilter verification with token:"
1658                            + verificationId + " and userId:" + userId);
1659
1660                    final IntentFilterVerificationResponse response =
1661                            (IntentFilterVerificationResponse) msg.obj;
1662
1663                    state.setVerifierResponse(response.callerUid, response.code);
1664
1665                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1666                            "IntentFilter verification with token:" + verificationId
1667                            + " and userId:" + userId
1668                            + " is settings verifier response with response code:"
1669                            + response.code);
1670
1671                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1672                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1673                                + response.getFailedDomainsString());
1674                    }
1675
1676                    if (state.isVerificationComplete()) {
1677                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1678                    } else {
1679                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1680                                "IntentFilter verification with token:" + verificationId
1681                                + " was not said to be complete");
1682                    }
1683
1684                    break;
1685                }
1686            }
1687        }
1688    }
1689
1690    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1691            boolean killApp, String[] grantedPermissions,
1692            IPackageInstallObserver2 installObserver) {
1693        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1694            // Send the removed broadcasts
1695            if (res.removedInfo != null) {
1696                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1697            }
1698
1699            // Now that we successfully installed the package, grant runtime
1700            // permissions if requested before broadcasting the install.
1701            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1702                    >= Build.VERSION_CODES.M) {
1703                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1704            }
1705
1706            final boolean update = res.removedInfo != null
1707                    && res.removedInfo.removedPackage != null;
1708
1709            // If this is the first time we have child packages for a disabled privileged
1710            // app that had no children, we grant requested runtime permissions to the new
1711            // children if the parent on the system image had them already granted.
1712            if (res.pkg.parentPackage != null) {
1713                synchronized (mPackages) {
1714                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1715                }
1716            }
1717
1718            synchronized (mPackages) {
1719                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1720            }
1721
1722            final String packageName = res.pkg.applicationInfo.packageName;
1723            Bundle extras = new Bundle(1);
1724            extras.putInt(Intent.EXTRA_UID, res.uid);
1725
1726            // Determine the set of users who are adding this package for
1727            // the first time vs. those who are seeing an update.
1728            int[] firstUsers = EMPTY_INT_ARRAY;
1729            int[] updateUsers = EMPTY_INT_ARRAY;
1730            if (res.origUsers == null || res.origUsers.length == 0) {
1731                firstUsers = res.newUsers;
1732            } else {
1733                for (int newUser : res.newUsers) {
1734                    boolean isNew = true;
1735                    for (int origUser : res.origUsers) {
1736                        if (origUser == newUser) {
1737                            isNew = false;
1738                            break;
1739                        }
1740                    }
1741                    if (isNew) {
1742                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1743                    } else {
1744                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1745                    }
1746                }
1747            }
1748
1749            // Send installed broadcasts if the install/update is not ephemeral
1750            if (!isEphemeral(res.pkg)) {
1751                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1752
1753                // Send added for users that see the package for the first time
1754                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1755                        extras, 0 /*flags*/, null /*targetPackage*/,
1756                        null /*finishedReceiver*/, firstUsers);
1757
1758                // Send added for users that don't see the package for the first time
1759                if (update) {
1760                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1761                }
1762                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1763                        extras, 0 /*flags*/, null /*targetPackage*/,
1764                        null /*finishedReceiver*/, updateUsers);
1765
1766                // Send replaced for users that don't see the package for the first time
1767                if (update) {
1768                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1769                            packageName, extras, 0 /*flags*/,
1770                            null /*targetPackage*/, null /*finishedReceiver*/,
1771                            updateUsers);
1772                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1773                            null /*package*/, null /*extras*/, 0 /*flags*/,
1774                            packageName /*targetPackage*/,
1775                            null /*finishedReceiver*/, updateUsers);
1776                }
1777
1778                // Send broadcast package appeared if forward locked/external for all users
1779                // treat asec-hosted packages like removable media on upgrade
1780                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1781                    if (DEBUG_INSTALL) {
1782                        Slog.i(TAG, "upgrading pkg " + res.pkg
1783                                + " is ASEC-hosted -> AVAILABLE");
1784                    }
1785                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1786                    ArrayList<String> pkgList = new ArrayList<>(1);
1787                    pkgList.add(packageName);
1788                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1789                }
1790            }
1791
1792            // Work that needs to happen on first install within each user
1793            if (firstUsers != null && firstUsers.length > 0) {
1794                synchronized (mPackages) {
1795                    for (int userId : firstUsers) {
1796                        // If this app is a browser and it's newly-installed for some
1797                        // users, clear any default-browser state in those users. The
1798                        // app's nature doesn't depend on the user, so we can just check
1799                        // its browser nature in any user and generalize.
1800                        if (packageIsBrowser(packageName, userId)) {
1801                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1802                        }
1803
1804                        // We may also need to apply pending (restored) runtime
1805                        // permission grants within these users.
1806                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1807                    }
1808                }
1809            }
1810
1811            // Log current value of "unknown sources" setting
1812            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1813                    getUnknownSourcesSettings());
1814
1815            // Force a gc to clear up things
1816            Runtime.getRuntime().gc();
1817
1818            // Remove the replaced package's older resources safely now
1819            // We delete after a gc for applications  on sdcard.
1820            if (res.removedInfo != null && res.removedInfo.args != null) {
1821                synchronized (mInstallLock) {
1822                    res.removedInfo.args.doPostDeleteLI(true);
1823                }
1824            }
1825        }
1826
1827        // If someone is watching installs - notify them
1828        if (installObserver != null) {
1829            try {
1830                Bundle extras = extrasForInstallResult(res);
1831                installObserver.onPackageInstalled(res.name, res.returnCode,
1832                        res.returnMsg, extras);
1833            } catch (RemoteException e) {
1834                Slog.i(TAG, "Observer no longer exists.");
1835            }
1836        }
1837    }
1838
1839    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1840            PackageParser.Package pkg) {
1841        if (pkg.parentPackage == null) {
1842            return;
1843        }
1844        if (pkg.requestedPermissions == null) {
1845            return;
1846        }
1847        final PackageSetting disabledSysParentPs = mSettings
1848                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1849        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1850                || !disabledSysParentPs.isPrivileged()
1851                || (disabledSysParentPs.childPackageNames != null
1852                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1853            return;
1854        }
1855        final int[] allUserIds = sUserManager.getUserIds();
1856        final int permCount = pkg.requestedPermissions.size();
1857        for (int i = 0; i < permCount; i++) {
1858            String permission = pkg.requestedPermissions.get(i);
1859            BasePermission bp = mSettings.mPermissions.get(permission);
1860            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1861                continue;
1862            }
1863            for (int userId : allUserIds) {
1864                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1865                        permission, userId)) {
1866                    grantRuntimePermission(pkg.packageName, permission, userId);
1867                }
1868            }
1869        }
1870    }
1871
1872    private StorageEventListener mStorageListener = new StorageEventListener() {
1873        @Override
1874        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1875            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1876                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1877                    final String volumeUuid = vol.getFsUuid();
1878
1879                    // Clean up any users or apps that were removed or recreated
1880                    // while this volume was missing
1881                    reconcileUsers(volumeUuid);
1882                    reconcileApps(volumeUuid);
1883
1884                    // Clean up any install sessions that expired or were
1885                    // cancelled while this volume was missing
1886                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1887
1888                    loadPrivatePackages(vol);
1889
1890                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1891                    unloadPrivatePackages(vol);
1892                }
1893            }
1894
1895            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1896                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1897                    updateExternalMediaStatus(true, false);
1898                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1899                    updateExternalMediaStatus(false, false);
1900                }
1901            }
1902        }
1903
1904        @Override
1905        public void onVolumeForgotten(String fsUuid) {
1906            if (TextUtils.isEmpty(fsUuid)) {
1907                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1908                return;
1909            }
1910
1911            // Remove any apps installed on the forgotten volume
1912            synchronized (mPackages) {
1913                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1914                for (PackageSetting ps : packages) {
1915                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1916                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1917                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1918                }
1919
1920                mSettings.onVolumeForgotten(fsUuid);
1921                mSettings.writeLPr();
1922            }
1923        }
1924    };
1925
1926    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1927            String[] grantedPermissions) {
1928        for (int userId : userIds) {
1929            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1930        }
1931
1932        // We could have touched GID membership, so flush out packages.list
1933        synchronized (mPackages) {
1934            mSettings.writePackageListLPr();
1935        }
1936    }
1937
1938    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1939            String[] grantedPermissions) {
1940        SettingBase sb = (SettingBase) pkg.mExtras;
1941        if (sb == null) {
1942            return;
1943        }
1944
1945        PermissionsState permissionsState = sb.getPermissionsState();
1946
1947        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1948                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1949
1950        synchronized (mPackages) {
1951            for (String permission : pkg.requestedPermissions) {
1952                BasePermission bp = mSettings.mPermissions.get(permission);
1953                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1954                        && (grantedPermissions == null
1955                               || ArrayUtils.contains(grantedPermissions, permission))) {
1956                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1957                    // Installer cannot change immutable permissions.
1958                    if ((flags & immutableFlags) == 0) {
1959                        grantRuntimePermission(pkg.packageName, permission, userId);
1960                    }
1961                }
1962            }
1963        }
1964    }
1965
1966    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1967        Bundle extras = null;
1968        switch (res.returnCode) {
1969            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1970                extras = new Bundle();
1971                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1972                        res.origPermission);
1973                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1974                        res.origPackage);
1975                break;
1976            }
1977            case PackageManager.INSTALL_SUCCEEDED: {
1978                extras = new Bundle();
1979                extras.putBoolean(Intent.EXTRA_REPLACING,
1980                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1981                break;
1982            }
1983        }
1984        return extras;
1985    }
1986
1987    void scheduleWriteSettingsLocked() {
1988        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1989            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1990        }
1991    }
1992
1993    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1994        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1995        scheduleWritePackageRestrictionsLocked(userId);
1996    }
1997
1998    void scheduleWritePackageRestrictionsLocked(int userId) {
1999        final int[] userIds = (userId == UserHandle.USER_ALL)
2000                ? sUserManager.getUserIds() : new int[]{userId};
2001        for (int nextUserId : userIds) {
2002            if (!sUserManager.exists(nextUserId)) return;
2003            mDirtyUsers.add(nextUserId);
2004            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2005                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2006            }
2007        }
2008    }
2009
2010    public static PackageManagerService main(Context context, Installer installer,
2011            boolean factoryTest, boolean onlyCore) {
2012        // Self-check for initial settings.
2013        PackageManagerServiceCompilerMapping.checkProperties();
2014
2015        PackageManagerService m = new PackageManagerService(context, installer,
2016                factoryTest, onlyCore);
2017        m.enableSystemUserPackages();
2018        ServiceManager.addService("package", m);
2019        return m;
2020    }
2021
2022    private void enableSystemUserPackages() {
2023        if (!UserManager.isSplitSystemUser()) {
2024            return;
2025        }
2026        // For system user, enable apps based on the following conditions:
2027        // - app is whitelisted or belong to one of these groups:
2028        //   -- system app which has no launcher icons
2029        //   -- system app which has INTERACT_ACROSS_USERS permission
2030        //   -- system IME app
2031        // - app is not in the blacklist
2032        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2033        Set<String> enableApps = new ArraySet<>();
2034        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2035                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2036                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2037        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2038        enableApps.addAll(wlApps);
2039        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2040                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2041        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2042        enableApps.removeAll(blApps);
2043        Log.i(TAG, "Applications installed for system user: " + enableApps);
2044        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2045                UserHandle.SYSTEM);
2046        final int allAppsSize = allAps.size();
2047        synchronized (mPackages) {
2048            for (int i = 0; i < allAppsSize; i++) {
2049                String pName = allAps.get(i);
2050                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2051                // Should not happen, but we shouldn't be failing if it does
2052                if (pkgSetting == null) {
2053                    continue;
2054                }
2055                boolean install = enableApps.contains(pName);
2056                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2057                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2058                            + " for system user");
2059                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2060                }
2061            }
2062        }
2063    }
2064
2065    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2066        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2067                Context.DISPLAY_SERVICE);
2068        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2069    }
2070
2071    public PackageManagerService(Context context, Installer installer,
2072            boolean factoryTest, boolean onlyCore) {
2073        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2074                SystemClock.uptimeMillis());
2075
2076        if (mSdkVersion <= 0) {
2077            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2078        }
2079
2080        mContext = context;
2081        mFactoryTest = factoryTest;
2082        mOnlyCore = onlyCore;
2083        mMetrics = new DisplayMetrics();
2084        mSettings = new Settings(mPackages);
2085        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2086                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2087        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2088                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2089        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2090                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2091        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2092                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2093        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2094                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2095        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2096                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2097
2098        String separateProcesses = SystemProperties.get("debug.separate_processes");
2099        if (separateProcesses != null && separateProcesses.length() > 0) {
2100            if ("*".equals(separateProcesses)) {
2101                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2102                mSeparateProcesses = null;
2103                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2104            } else {
2105                mDefParseFlags = 0;
2106                mSeparateProcesses = separateProcesses.split(",");
2107                Slog.w(TAG, "Running with debug.separate_processes: "
2108                        + separateProcesses);
2109            }
2110        } else {
2111            mDefParseFlags = 0;
2112            mSeparateProcesses = null;
2113        }
2114
2115        mInstaller = installer;
2116        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2117                "*dexopt*");
2118        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2119
2120        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2121                FgThread.get().getLooper());
2122
2123        getDefaultDisplayMetrics(context, mMetrics);
2124
2125        SystemConfig systemConfig = SystemConfig.getInstance();
2126        mGlobalGids = systemConfig.getGlobalGids();
2127        mSystemPermissions = systemConfig.getSystemPermissions();
2128        mAvailableFeatures = systemConfig.getAvailableFeatures();
2129
2130        synchronized (mInstallLock) {
2131        // writer
2132        synchronized (mPackages) {
2133            mHandlerThread = new ServiceThread(TAG,
2134                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2135            mHandlerThread.start();
2136            mHandler = new PackageHandler(mHandlerThread.getLooper());
2137            mProcessLoggingHandler = new ProcessLoggingHandler();
2138            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2139
2140            File dataDir = Environment.getDataDirectory();
2141            mAppInstallDir = new File(dataDir, "app");
2142            mAppLib32InstallDir = new File(dataDir, "app-lib");
2143            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2144            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2145            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2146
2147            sUserManager = new UserManagerService(context, this, mPackages);
2148
2149            // Propagate permission configuration in to package manager.
2150            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2151                    = systemConfig.getPermissions();
2152            for (int i=0; i<permConfig.size(); i++) {
2153                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2154                BasePermission bp = mSettings.mPermissions.get(perm.name);
2155                if (bp == null) {
2156                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2157                    mSettings.mPermissions.put(perm.name, bp);
2158                }
2159                if (perm.gids != null) {
2160                    bp.setGids(perm.gids, perm.perUser);
2161                }
2162            }
2163
2164            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2165            for (int i=0; i<libConfig.size(); i++) {
2166                mSharedLibraries.put(libConfig.keyAt(i),
2167                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2168            }
2169
2170            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2171
2172            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2173
2174            String customResolverActivity = Resources.getSystem().getString(
2175                    R.string.config_customResolverActivity);
2176            if (TextUtils.isEmpty(customResolverActivity)) {
2177                customResolverActivity = null;
2178            } else {
2179                mCustomResolverComponentName = ComponentName.unflattenFromString(
2180                        customResolverActivity);
2181            }
2182
2183            long startTime = SystemClock.uptimeMillis();
2184
2185            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2186                    startTime);
2187
2188            // Set flag to monitor and not change apk file paths when
2189            // scanning install directories.
2190            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2191
2192            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2193            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2194
2195            if (bootClassPath == null) {
2196                Slog.w(TAG, "No BOOTCLASSPATH found!");
2197            }
2198
2199            if (systemServerClassPath == null) {
2200                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2201            }
2202
2203            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2204            final String[] dexCodeInstructionSets =
2205                    getDexCodeInstructionSets(
2206                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2207
2208            /**
2209             * Ensure all external libraries have had dexopt run on them.
2210             */
2211            if (mSharedLibraries.size() > 0) {
2212                // NOTE: For now, we're compiling these system "shared libraries"
2213                // (and framework jars) into all available architectures. It's possible
2214                // to compile them only when we come across an app that uses them (there's
2215                // already logic for that in scanPackageLI) but that adds some complexity.
2216                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2217                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2218                        final String lib = libEntry.path;
2219                        if (lib == null) {
2220                            continue;
2221                        }
2222
2223                        try {
2224                            // Shared libraries do not have profiles so we perform a full
2225                            // AOT compilation (if needed).
2226                            int dexoptNeeded = DexFile.getDexOptNeeded(
2227                                    lib, dexCodeInstructionSet,
2228                                    getCompilerFilterForReason(REASON_SHARED_APK),
2229                                    false /* newProfile */);
2230                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2231                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2232                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2233                                        getCompilerFilterForReason(REASON_SHARED_APK),
2234                                        StorageManager.UUID_PRIVATE_INTERNAL);
2235                            }
2236                        } catch (FileNotFoundException e) {
2237                            Slog.w(TAG, "Library not found: " + lib);
2238                        } catch (IOException | InstallerException e) {
2239                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2240                                    + e.getMessage());
2241                        }
2242                    }
2243                }
2244            }
2245
2246            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2247
2248            final VersionInfo ver = mSettings.getInternalVersion();
2249            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2250
2251            // when upgrading from pre-M, promote system app permissions from install to runtime
2252            mPromoteSystemApps =
2253                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2254
2255            // save off the names of pre-existing system packages prior to scanning; we don't
2256            // want to automatically grant runtime permissions for new system apps
2257            if (mPromoteSystemApps) {
2258                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2259                while (pkgSettingIter.hasNext()) {
2260                    PackageSetting ps = pkgSettingIter.next();
2261                    if (isSystemApp(ps)) {
2262                        mExistingSystemPackages.add(ps.name);
2263                    }
2264                }
2265            }
2266
2267            // When upgrading from pre-N, we need to handle package extraction like first boot,
2268            // as there is no profiling data available.
2269            mIsPreNUpgrade = !mSettings.isNWorkDone();
2270            mSettings.setNWorkDone();
2271
2272            // Collect vendor overlay packages.
2273            // (Do this before scanning any apps.)
2274            // For security and version matching reason, only consider
2275            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2276            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2277            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2278                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2279
2280            // Find base frameworks (resource packages without code).
2281            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2282                    | PackageParser.PARSE_IS_SYSTEM_DIR
2283                    | PackageParser.PARSE_IS_PRIVILEGED,
2284                    scanFlags | SCAN_NO_DEX, 0);
2285
2286            // Collected privileged system packages.
2287            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2288            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2289                    | PackageParser.PARSE_IS_SYSTEM_DIR
2290                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2291
2292            // Collect ordinary system packages.
2293            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2294            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2295                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2296
2297            // Collect all vendor packages.
2298            File vendorAppDir = new File("/vendor/app");
2299            try {
2300                vendorAppDir = vendorAppDir.getCanonicalFile();
2301            } catch (IOException e) {
2302                // failed to look up canonical path, continue with original one
2303            }
2304            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2305                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2306
2307            // Collect all OEM packages.
2308            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2309            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2310                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2311
2312            // Prune any system packages that no longer exist.
2313            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2314            if (!mOnlyCore) {
2315                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2316                while (psit.hasNext()) {
2317                    PackageSetting ps = psit.next();
2318
2319                    /*
2320                     * If this is not a system app, it can't be a
2321                     * disable system app.
2322                     */
2323                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2324                        continue;
2325                    }
2326
2327                    /*
2328                     * If the package is scanned, it's not erased.
2329                     */
2330                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2331                    if (scannedPkg != null) {
2332                        /*
2333                         * If the system app is both scanned and in the
2334                         * disabled packages list, then it must have been
2335                         * added via OTA. Remove it from the currently
2336                         * scanned package so the previously user-installed
2337                         * application can be scanned.
2338                         */
2339                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2340                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2341                                    + ps.name + "; removing system app.  Last known codePath="
2342                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2343                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2344                                    + scannedPkg.mVersionCode);
2345                            removePackageLI(scannedPkg, true);
2346                            mExpectingBetter.put(ps.name, ps.codePath);
2347                        }
2348
2349                        continue;
2350                    }
2351
2352                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2353                        psit.remove();
2354                        logCriticalInfo(Log.WARN, "System package " + ps.name
2355                                + " no longer exists; wiping its data");
2356                        removeDataDirsLI(null, ps.name);
2357                    } else {
2358                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2359                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2360                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2361                        }
2362                    }
2363                }
2364            }
2365
2366            //look for any incomplete package installations
2367            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2368            //clean up list
2369            for(int i = 0; i < deletePkgsList.size(); i++) {
2370                //clean up here
2371                cleanupInstallFailedPackage(deletePkgsList.get(i));
2372            }
2373            //delete tmp files
2374            deleteTempPackageFiles();
2375
2376            // Remove any shared userIDs that have no associated packages
2377            mSettings.pruneSharedUsersLPw();
2378
2379            if (!mOnlyCore) {
2380                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2381                        SystemClock.uptimeMillis());
2382                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2383
2384                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2385                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2386
2387                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2388                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2389
2390                /**
2391                 * Remove disable package settings for any updated system
2392                 * apps that were removed via an OTA. If they're not a
2393                 * previously-updated app, remove them completely.
2394                 * Otherwise, just revoke their system-level permissions.
2395                 */
2396                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2397                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2398                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2399
2400                    String msg;
2401                    if (deletedPkg == null) {
2402                        msg = "Updated system package " + deletedAppName
2403                                + " no longer exists; wiping its data";
2404                        removeDataDirsLI(null, deletedAppName);
2405                    } else {
2406                        msg = "Updated system app + " + deletedAppName
2407                                + " no longer present; removing system privileges for "
2408                                + deletedAppName;
2409
2410                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2411
2412                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2413                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2414                    }
2415                    logCriticalInfo(Log.WARN, msg);
2416                }
2417
2418                /**
2419                 * Make sure all system apps that we expected to appear on
2420                 * the userdata partition actually showed up. If they never
2421                 * appeared, crawl back and revive the system version.
2422                 */
2423                for (int i = 0; i < mExpectingBetter.size(); i++) {
2424                    final String packageName = mExpectingBetter.keyAt(i);
2425                    if (!mPackages.containsKey(packageName)) {
2426                        final File scanFile = mExpectingBetter.valueAt(i);
2427
2428                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2429                                + " but never showed up; reverting to system");
2430
2431                        final int reparseFlags;
2432                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2433                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2434                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2435                                    | PackageParser.PARSE_IS_PRIVILEGED;
2436                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2437                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2438                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2439                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2440                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2441                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2442                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2443                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2444                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2445                        } else {
2446                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2447                            continue;
2448                        }
2449
2450                        mSettings.enableSystemPackageLPw(packageName);
2451
2452                        try {
2453                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2454                        } catch (PackageManagerException e) {
2455                            Slog.e(TAG, "Failed to parse original system package: "
2456                                    + e.getMessage());
2457                        }
2458                    }
2459                }
2460            }
2461            mExpectingBetter.clear();
2462
2463            // Resolve protected action filters. Only the setup wizard is allowed to
2464            // have a high priority filter for these actions.
2465            mSetupWizardPackage = getSetupWizardPackageName();
2466            if (mProtectedFilters.size() > 0) {
2467                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2468                    Slog.i(TAG, "No setup wizard;"
2469                        + " All protected intents capped to priority 0");
2470                }
2471                for (ActivityIntentInfo filter : mProtectedFilters) {
2472                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2473                        if (DEBUG_FILTERS) {
2474                            Slog.i(TAG, "Found setup wizard;"
2475                                + " allow priority " + filter.getPriority() + ";"
2476                                + " package: " + filter.activity.info.packageName
2477                                + " activity: " + filter.activity.className
2478                                + " priority: " + filter.getPriority());
2479                        }
2480                        // skip setup wizard; allow it to keep the high priority filter
2481                        continue;
2482                    }
2483                    Slog.w(TAG, "Protected action; cap priority to 0;"
2484                            + " package: " + filter.activity.info.packageName
2485                            + " activity: " + filter.activity.className
2486                            + " origPrio: " + filter.getPriority());
2487                    filter.setPriority(0);
2488                }
2489            }
2490            mDeferProtectedFilters = false;
2491            mProtectedFilters.clear();
2492
2493            // Now that we know all of the shared libraries, update all clients to have
2494            // the correct library paths.
2495            updateAllSharedLibrariesLPw();
2496
2497            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2498                // NOTE: We ignore potential failures here during a system scan (like
2499                // the rest of the commands above) because there's precious little we
2500                // can do about it. A settings error is reported, though.
2501                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2502                        false /* boot complete */);
2503            }
2504
2505            // Now that we know all the packages we are keeping,
2506            // read and update their last usage times.
2507            mPackageUsage.readLP();
2508
2509            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2510                    SystemClock.uptimeMillis());
2511            Slog.i(TAG, "Time to scan packages: "
2512                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2513                    + " seconds");
2514
2515            // If the platform SDK has changed since the last time we booted,
2516            // we need to re-grant app permission to catch any new ones that
2517            // appear.  This is really a hack, and means that apps can in some
2518            // cases get permissions that the user didn't initially explicitly
2519            // allow...  it would be nice to have some better way to handle
2520            // this situation.
2521            int updateFlags = UPDATE_PERMISSIONS_ALL;
2522            if (ver.sdkVersion != mSdkVersion) {
2523                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2524                        + mSdkVersion + "; regranting permissions for internal storage");
2525                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2526            }
2527            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2528            ver.sdkVersion = mSdkVersion;
2529
2530            // If this is the first boot or an update from pre-M, and it is a normal
2531            // boot, then we need to initialize the default preferred apps across
2532            // all defined users.
2533            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2534                for (UserInfo user : sUserManager.getUsers(true)) {
2535                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2536                    applyFactoryDefaultBrowserLPw(user.id);
2537                    primeDomainVerificationsLPw(user.id);
2538                }
2539            }
2540
2541            // Prepare storage for system user really early during boot,
2542            // since core system apps like SettingsProvider and SystemUI
2543            // can't wait for user to start
2544            final int storageFlags;
2545            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2546                storageFlags = StorageManager.FLAG_STORAGE_DE;
2547            } else {
2548                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2549            }
2550            reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2551                    storageFlags);
2552
2553            // If this is first boot after an OTA, and a normal boot, then
2554            // we need to clear code cache directories.
2555            if (mIsUpgrade && !onlyCore) {
2556                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2557                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2558                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2559                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2560                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2561                    }
2562                }
2563                ver.fingerprint = Build.FINGERPRINT;
2564            }
2565
2566            checkDefaultBrowser();
2567
2568            // clear only after permissions and other defaults have been updated
2569            mExistingSystemPackages.clear();
2570            mPromoteSystemApps = false;
2571
2572            // All the changes are done during package scanning.
2573            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2574
2575            // can downgrade to reader
2576            mSettings.writeLPr();
2577
2578            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2579                    SystemClock.uptimeMillis());
2580
2581            if (!mOnlyCore) {
2582                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2583                mRequiredInstallerPackage = getRequiredInstallerLPr();
2584                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2585                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2586                        mIntentFilterVerifierComponent);
2587            } else {
2588                mRequiredVerifierPackage = null;
2589                mRequiredInstallerPackage = null;
2590                mIntentFilterVerifierComponent = null;
2591                mIntentFilterVerifier = null;
2592            }
2593
2594            mInstallerService = new PackageInstallerService(context, this);
2595
2596            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2597            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2598            // both the installer and resolver must be present to enable ephemeral
2599            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2600                if (DEBUG_EPHEMERAL) {
2601                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2602                            + " installer:" + ephemeralInstallerComponent);
2603                }
2604                mEphemeralResolverComponent = ephemeralResolverComponent;
2605                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2606                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2607                mEphemeralResolverConnection =
2608                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2609            } else {
2610                if (DEBUG_EPHEMERAL) {
2611                    final String missingComponent =
2612                            (ephemeralResolverComponent == null)
2613                            ? (ephemeralInstallerComponent == null)
2614                                    ? "resolver and installer"
2615                                    : "resolver"
2616                            : "installer";
2617                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2618                }
2619                mEphemeralResolverComponent = null;
2620                mEphemeralInstallerComponent = null;
2621                mEphemeralResolverConnection = null;
2622            }
2623
2624            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2625        } // synchronized (mPackages)
2626        } // synchronized (mInstallLock)
2627
2628        // Now after opening every single application zip, make sure they
2629        // are all flushed.  Not really needed, but keeps things nice and
2630        // tidy.
2631        Runtime.getRuntime().gc();
2632
2633        // The initial scanning above does many calls into installd while
2634        // holding the mPackages lock, but we're mostly interested in yelling
2635        // once we have a booted system.
2636        mInstaller.setWarnIfHeld(mPackages);
2637
2638        // Expose private service for system components to use.
2639        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2640    }
2641
2642    @Override
2643    public boolean isFirstBoot() {
2644        return !mRestoredSettings;
2645    }
2646
2647    @Override
2648    public boolean isOnlyCoreApps() {
2649        return mOnlyCore;
2650    }
2651
2652    @Override
2653    public boolean isUpgrade() {
2654        return mIsUpgrade;
2655    }
2656
2657    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2658        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2659
2660        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2661                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2662                UserHandle.USER_SYSTEM);
2663        if (matches.size() == 1) {
2664            return matches.get(0).getComponentInfo().packageName;
2665        } else {
2666            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2667            return null;
2668        }
2669    }
2670
2671    private @NonNull String getRequiredInstallerLPr() {
2672        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2673        intent.addCategory(Intent.CATEGORY_DEFAULT);
2674        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2675
2676        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2677                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2678                UserHandle.USER_SYSTEM);
2679        if (matches.size() == 1) {
2680            return matches.get(0).getComponentInfo().packageName;
2681        } else {
2682            throw new RuntimeException("There must be exactly one installer; found " + matches);
2683        }
2684    }
2685
2686    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2687        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2688
2689        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2690                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2691                UserHandle.USER_SYSTEM);
2692        ResolveInfo best = null;
2693        final int N = matches.size();
2694        for (int i = 0; i < N; i++) {
2695            final ResolveInfo cur = matches.get(i);
2696            final String packageName = cur.getComponentInfo().packageName;
2697            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2698                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2699                continue;
2700            }
2701
2702            if (best == null || cur.priority > best.priority) {
2703                best = cur;
2704            }
2705        }
2706
2707        if (best != null) {
2708            return best.getComponentInfo().getComponentName();
2709        } else {
2710            throw new RuntimeException("There must be at least one intent filter verifier");
2711        }
2712    }
2713
2714    private @Nullable ComponentName getEphemeralResolverLPr() {
2715        final String[] packageArray =
2716                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2717        if (packageArray.length == 0) {
2718            if (DEBUG_EPHEMERAL) {
2719                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2720            }
2721            return null;
2722        }
2723
2724        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2725        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2726                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2727                UserHandle.USER_SYSTEM);
2728
2729        final int N = resolvers.size();
2730        if (N == 0) {
2731            if (DEBUG_EPHEMERAL) {
2732                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2733            }
2734            return null;
2735        }
2736
2737        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2738        for (int i = 0; i < N; i++) {
2739            final ResolveInfo info = resolvers.get(i);
2740
2741            if (info.serviceInfo == null) {
2742                continue;
2743            }
2744
2745            final String packageName = info.serviceInfo.packageName;
2746            if (!possiblePackages.contains(packageName)) {
2747                if (DEBUG_EPHEMERAL) {
2748                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2749                            + " pkg: " + packageName + ", info:" + info);
2750                }
2751                continue;
2752            }
2753
2754            if (DEBUG_EPHEMERAL) {
2755                Slog.v(TAG, "Ephemeral resolver found;"
2756                        + " pkg: " + packageName + ", info:" + info);
2757            }
2758            return new ComponentName(packageName, info.serviceInfo.name);
2759        }
2760        if (DEBUG_EPHEMERAL) {
2761            Slog.v(TAG, "Ephemeral resolver NOT found");
2762        }
2763        return null;
2764    }
2765
2766    private @Nullable ComponentName getEphemeralInstallerLPr() {
2767        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2768        intent.addCategory(Intent.CATEGORY_DEFAULT);
2769        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2770
2771        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2772                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2773                UserHandle.USER_SYSTEM);
2774        if (matches.size() == 0) {
2775            return null;
2776        } else if (matches.size() == 1) {
2777            return matches.get(0).getComponentInfo().getComponentName();
2778        } else {
2779            throw new RuntimeException(
2780                    "There must be at most one ephemeral installer; found " + matches);
2781        }
2782    }
2783
2784    private void primeDomainVerificationsLPw(int userId) {
2785        if (DEBUG_DOMAIN_VERIFICATION) {
2786            Slog.d(TAG, "Priming domain verifications in user " + userId);
2787        }
2788
2789        SystemConfig systemConfig = SystemConfig.getInstance();
2790        ArraySet<String> packages = systemConfig.getLinkedApps();
2791        ArraySet<String> domains = new ArraySet<String>();
2792
2793        for (String packageName : packages) {
2794            PackageParser.Package pkg = mPackages.get(packageName);
2795            if (pkg != null) {
2796                if (!pkg.isSystemApp()) {
2797                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2798                    continue;
2799                }
2800
2801                domains.clear();
2802                for (PackageParser.Activity a : pkg.activities) {
2803                    for (ActivityIntentInfo filter : a.intents) {
2804                        if (hasValidDomains(filter)) {
2805                            domains.addAll(filter.getHostsList());
2806                        }
2807                    }
2808                }
2809
2810                if (domains.size() > 0) {
2811                    if (DEBUG_DOMAIN_VERIFICATION) {
2812                        Slog.v(TAG, "      + " + packageName);
2813                    }
2814                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2815                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2816                    // and then 'always' in the per-user state actually used for intent resolution.
2817                    final IntentFilterVerificationInfo ivi;
2818                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2819                            new ArrayList<String>(domains));
2820                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2821                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2822                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2823                } else {
2824                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2825                            + "' does not handle web links");
2826                }
2827            } else {
2828                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2829            }
2830        }
2831
2832        scheduleWritePackageRestrictionsLocked(userId);
2833        scheduleWriteSettingsLocked();
2834    }
2835
2836    private void applyFactoryDefaultBrowserLPw(int userId) {
2837        // The default browser app's package name is stored in a string resource,
2838        // with a product-specific overlay used for vendor customization.
2839        String browserPkg = mContext.getResources().getString(
2840                com.android.internal.R.string.default_browser);
2841        if (!TextUtils.isEmpty(browserPkg)) {
2842            // non-empty string => required to be a known package
2843            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2844            if (ps == null) {
2845                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2846                browserPkg = null;
2847            } else {
2848                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2849            }
2850        }
2851
2852        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2853        // default.  If there's more than one, just leave everything alone.
2854        if (browserPkg == null) {
2855            calculateDefaultBrowserLPw(userId);
2856        }
2857    }
2858
2859    private void calculateDefaultBrowserLPw(int userId) {
2860        List<String> allBrowsers = resolveAllBrowserApps(userId);
2861        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2862        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2863    }
2864
2865    private List<String> resolveAllBrowserApps(int userId) {
2866        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2867        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2868                PackageManager.MATCH_ALL, userId);
2869
2870        final int count = list.size();
2871        List<String> result = new ArrayList<String>(count);
2872        for (int i=0; i<count; i++) {
2873            ResolveInfo info = list.get(i);
2874            if (info.activityInfo == null
2875                    || !info.handleAllWebDataURI
2876                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2877                    || result.contains(info.activityInfo.packageName)) {
2878                continue;
2879            }
2880            result.add(info.activityInfo.packageName);
2881        }
2882
2883        return result;
2884    }
2885
2886    private boolean packageIsBrowser(String packageName, int userId) {
2887        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2888                PackageManager.MATCH_ALL, userId);
2889        final int N = list.size();
2890        for (int i = 0; i < N; i++) {
2891            ResolveInfo info = list.get(i);
2892            if (packageName.equals(info.activityInfo.packageName)) {
2893                return true;
2894            }
2895        }
2896        return false;
2897    }
2898
2899    private void checkDefaultBrowser() {
2900        final int myUserId = UserHandle.myUserId();
2901        final String packageName = getDefaultBrowserPackageName(myUserId);
2902        if (packageName != null) {
2903            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2904            if (info == null) {
2905                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2906                synchronized (mPackages) {
2907                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2908                }
2909            }
2910        }
2911    }
2912
2913    @Override
2914    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2915            throws RemoteException {
2916        try {
2917            return super.onTransact(code, data, reply, flags);
2918        } catch (RuntimeException e) {
2919            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2920                Slog.wtf(TAG, "Package Manager Crash", e);
2921            }
2922            throw e;
2923        }
2924    }
2925
2926    void cleanupInstallFailedPackage(PackageSetting ps) {
2927        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2928
2929        removeDataDirsLI(ps.volumeUuid, ps.name);
2930        if (ps.codePath != null) {
2931            removeCodePathLI(ps.codePath);
2932        }
2933        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2934            if (ps.resourcePath.isDirectory()) {
2935                FileUtils.deleteContents(ps.resourcePath);
2936            }
2937            ps.resourcePath.delete();
2938        }
2939        mSettings.removePackageLPw(ps.name);
2940    }
2941
2942    static int[] appendInts(int[] cur, int[] add) {
2943        if (add == null) return cur;
2944        if (cur == null) return add;
2945        final int N = add.length;
2946        for (int i=0; i<N; i++) {
2947            cur = appendInt(cur, add[i]);
2948        }
2949        return cur;
2950    }
2951
2952    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
2953        if (!sUserManager.exists(userId)) return null;
2954        if (ps == null) {
2955            return null;
2956        }
2957        final PackageParser.Package p = ps.pkg;
2958        if (p == null) {
2959            return null;
2960        }
2961
2962        final PermissionsState permissionsState = ps.getPermissionsState();
2963
2964        final int[] gids = permissionsState.computeGids(userId);
2965        final Set<String> permissions = permissionsState.getPermissions(userId);
2966        final PackageUserState state = ps.readUserState(userId);
2967
2968        return PackageParser.generatePackageInfo(p, gids, flags,
2969                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2970    }
2971
2972    @Override
2973    public void checkPackageStartable(String packageName, int userId) {
2974        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2975
2976        synchronized (mPackages) {
2977            final PackageSetting ps = mSettings.mPackages.get(packageName);
2978            if (ps == null) {
2979                throw new SecurityException("Package " + packageName + " was not found!");
2980            }
2981
2982            if (!ps.getInstalled(userId)) {
2983                throw new SecurityException(
2984                        "Package " + packageName + " was not installed for user " + userId + "!");
2985            }
2986
2987            if (mSafeMode && !ps.isSystem()) {
2988                throw new SecurityException("Package " + packageName + " not a system app!");
2989            }
2990
2991            if (ps.frozen) {
2992                throw new SecurityException("Package " + packageName + " is currently frozen!");
2993            }
2994
2995            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
2996                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
2997                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2998            }
2999        }
3000    }
3001
3002    @Override
3003    public boolean isPackageAvailable(String packageName, int userId) {
3004        if (!sUserManager.exists(userId)) return false;
3005        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3006                false /* requireFullPermission */, false /* checkShell */, "is package available");
3007        synchronized (mPackages) {
3008            PackageParser.Package p = mPackages.get(packageName);
3009            if (p != null) {
3010                final PackageSetting ps = (PackageSetting) p.mExtras;
3011                if (ps != null) {
3012                    final PackageUserState state = ps.readUserState(userId);
3013                    if (state != null) {
3014                        return PackageParser.isAvailable(state);
3015                    }
3016                }
3017            }
3018        }
3019        return false;
3020    }
3021
3022    @Override
3023    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3024        if (!sUserManager.exists(userId)) return null;
3025        flags = updateFlagsForPackage(flags, userId, packageName);
3026        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3027                false /* requireFullPermission */, false /* checkShell */, "get package info");
3028        // reader
3029        synchronized (mPackages) {
3030            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3031            PackageParser.Package p = null;
3032            if (matchFactoryOnly) {
3033                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3034                if (ps != null) {
3035                    return generatePackageInfo(ps, flags, userId);
3036                }
3037            }
3038            if (p == null) {
3039                p = mPackages.get(packageName);
3040                if (matchFactoryOnly && !isSystemApp(p)) {
3041                    return null;
3042                }
3043            }
3044            if (DEBUG_PACKAGE_INFO)
3045                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3046            if (p != null) {
3047                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3048            }
3049            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3050                final PackageSetting ps = mSettings.mPackages.get(packageName);
3051                return generatePackageInfo(ps, flags, userId);
3052            }
3053        }
3054        return null;
3055    }
3056
3057    @Override
3058    public String[] currentToCanonicalPackageNames(String[] names) {
3059        String[] out = new String[names.length];
3060        // reader
3061        synchronized (mPackages) {
3062            for (int i=names.length-1; i>=0; i--) {
3063                PackageSetting ps = mSettings.mPackages.get(names[i]);
3064                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3065            }
3066        }
3067        return out;
3068    }
3069
3070    @Override
3071    public String[] canonicalToCurrentPackageNames(String[] names) {
3072        String[] out = new String[names.length];
3073        // reader
3074        synchronized (mPackages) {
3075            for (int i=names.length-1; i>=0; i--) {
3076                String cur = mSettings.mRenamedPackages.get(names[i]);
3077                out[i] = cur != null ? cur : names[i];
3078            }
3079        }
3080        return out;
3081    }
3082
3083    @Override
3084    public int getPackageUid(String packageName, int flags, int userId) {
3085        if (!sUserManager.exists(userId)) return -1;
3086        flags = updateFlagsForPackage(flags, userId, packageName);
3087        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3088                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3089
3090        // reader
3091        synchronized (mPackages) {
3092            final PackageParser.Package p = mPackages.get(packageName);
3093            if (p != null && p.isMatch(flags)) {
3094                return UserHandle.getUid(userId, p.applicationInfo.uid);
3095            }
3096            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3097                final PackageSetting ps = mSettings.mPackages.get(packageName);
3098                if (ps != null && ps.isMatch(flags)) {
3099                    return UserHandle.getUid(userId, ps.appId);
3100                }
3101            }
3102        }
3103
3104        return -1;
3105    }
3106
3107    @Override
3108    public int[] getPackageGids(String packageName, int flags, int userId) {
3109        if (!sUserManager.exists(userId)) return null;
3110        flags = updateFlagsForPackage(flags, userId, packageName);
3111        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3112                false /* requireFullPermission */, false /* checkShell */,
3113                "getPackageGids");
3114
3115        // reader
3116        synchronized (mPackages) {
3117            final PackageParser.Package p = mPackages.get(packageName);
3118            if (p != null && p.isMatch(flags)) {
3119                PackageSetting ps = (PackageSetting) p.mExtras;
3120                return ps.getPermissionsState().computeGids(userId);
3121            }
3122            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3123                final PackageSetting ps = mSettings.mPackages.get(packageName);
3124                if (ps != null && ps.isMatch(flags)) {
3125                    return ps.getPermissionsState().computeGids(userId);
3126                }
3127            }
3128        }
3129
3130        return null;
3131    }
3132
3133    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3134        if (bp.perm != null) {
3135            return PackageParser.generatePermissionInfo(bp.perm, flags);
3136        }
3137        PermissionInfo pi = new PermissionInfo();
3138        pi.name = bp.name;
3139        pi.packageName = bp.sourcePackage;
3140        pi.nonLocalizedLabel = bp.name;
3141        pi.protectionLevel = bp.protectionLevel;
3142        return pi;
3143    }
3144
3145    @Override
3146    public PermissionInfo getPermissionInfo(String name, int flags) {
3147        // reader
3148        synchronized (mPackages) {
3149            final BasePermission p = mSettings.mPermissions.get(name);
3150            if (p != null) {
3151                return generatePermissionInfo(p, flags);
3152            }
3153            return null;
3154        }
3155    }
3156
3157    @Override
3158    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3159            int flags) {
3160        // reader
3161        synchronized (mPackages) {
3162            if (group != null && !mPermissionGroups.containsKey(group)) {
3163                // This is thrown as NameNotFoundException
3164                return null;
3165            }
3166
3167            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3168            for (BasePermission p : mSettings.mPermissions.values()) {
3169                if (group == null) {
3170                    if (p.perm == null || p.perm.info.group == null) {
3171                        out.add(generatePermissionInfo(p, flags));
3172                    }
3173                } else {
3174                    if (p.perm != null && group.equals(p.perm.info.group)) {
3175                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3176                    }
3177                }
3178            }
3179            return new ParceledListSlice<>(out);
3180        }
3181    }
3182
3183    @Override
3184    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3185        // reader
3186        synchronized (mPackages) {
3187            return PackageParser.generatePermissionGroupInfo(
3188                    mPermissionGroups.get(name), flags);
3189        }
3190    }
3191
3192    @Override
3193    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3194        // reader
3195        synchronized (mPackages) {
3196            final int N = mPermissionGroups.size();
3197            ArrayList<PermissionGroupInfo> out
3198                    = new ArrayList<PermissionGroupInfo>(N);
3199            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3200                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3201            }
3202            return new ParceledListSlice<>(out);
3203        }
3204    }
3205
3206    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3207            int userId) {
3208        if (!sUserManager.exists(userId)) return null;
3209        PackageSetting ps = mSettings.mPackages.get(packageName);
3210        if (ps != null) {
3211            if (ps.pkg == null) {
3212                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3213                if (pInfo != null) {
3214                    return pInfo.applicationInfo;
3215                }
3216                return null;
3217            }
3218            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3219                    ps.readUserState(userId), userId);
3220        }
3221        return null;
3222    }
3223
3224    @Override
3225    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3226        if (!sUserManager.exists(userId)) return null;
3227        flags = updateFlagsForApplication(flags, userId, packageName);
3228        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3229                false /* requireFullPermission */, false /* checkShell */, "get application info");
3230        // writer
3231        synchronized (mPackages) {
3232            PackageParser.Package p = mPackages.get(packageName);
3233            if (DEBUG_PACKAGE_INFO) Log.v(
3234                    TAG, "getApplicationInfo " + packageName
3235                    + ": " + p);
3236            if (p != null) {
3237                PackageSetting ps = mSettings.mPackages.get(packageName);
3238                if (ps == null) return null;
3239                // Note: isEnabledLP() does not apply here - always return info
3240                return PackageParser.generateApplicationInfo(
3241                        p, flags, ps.readUserState(userId), userId);
3242            }
3243            if ("android".equals(packageName)||"system".equals(packageName)) {
3244                return mAndroidApplication;
3245            }
3246            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3247                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3248            }
3249        }
3250        return null;
3251    }
3252
3253    @Override
3254    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3255            final IPackageDataObserver observer) {
3256        mContext.enforceCallingOrSelfPermission(
3257                android.Manifest.permission.CLEAR_APP_CACHE, null);
3258        // Queue up an async operation since clearing cache may take a little while.
3259        mHandler.post(new Runnable() {
3260            public void run() {
3261                mHandler.removeCallbacks(this);
3262                boolean success = true;
3263                synchronized (mInstallLock) {
3264                    try {
3265                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3266                    } catch (InstallerException e) {
3267                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3268                        success = false;
3269                    }
3270                }
3271                if (observer != null) {
3272                    try {
3273                        observer.onRemoveCompleted(null, success);
3274                    } catch (RemoteException e) {
3275                        Slog.w(TAG, "RemoveException when invoking call back");
3276                    }
3277                }
3278            }
3279        });
3280    }
3281
3282    @Override
3283    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3284            final IntentSender pi) {
3285        mContext.enforceCallingOrSelfPermission(
3286                android.Manifest.permission.CLEAR_APP_CACHE, null);
3287        // Queue up an async operation since clearing cache may take a little while.
3288        mHandler.post(new Runnable() {
3289            public void run() {
3290                mHandler.removeCallbacks(this);
3291                boolean success = true;
3292                synchronized (mInstallLock) {
3293                    try {
3294                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3295                    } catch (InstallerException e) {
3296                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3297                        success = false;
3298                    }
3299                }
3300                if(pi != null) {
3301                    try {
3302                        // Callback via pending intent
3303                        int code = success ? 1 : 0;
3304                        pi.sendIntent(null, code, null,
3305                                null, null);
3306                    } catch (SendIntentException e1) {
3307                        Slog.i(TAG, "Failed to send pending intent");
3308                    }
3309                }
3310            }
3311        });
3312    }
3313
3314    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3315        synchronized (mInstallLock) {
3316            try {
3317                mInstaller.freeCache(volumeUuid, freeStorageSize);
3318            } catch (InstallerException e) {
3319                throw new IOException("Failed to free enough space", e);
3320            }
3321        }
3322    }
3323
3324    /**
3325     * Return if the user key is currently unlocked.
3326     */
3327    private boolean isUserKeyUnlocked(int userId) {
3328        if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3329            final IMountService mount = IMountService.Stub
3330                    .asInterface(ServiceManager.getService("mount"));
3331            if (mount == null) {
3332                Slog.w(TAG, "Early during boot, assuming locked");
3333                return false;
3334            }
3335            final long token = Binder.clearCallingIdentity();
3336            try {
3337                return mount.isUserKeyUnlocked(userId);
3338            } catch (RemoteException e) {
3339                throw e.rethrowAsRuntimeException();
3340            } finally {
3341                Binder.restoreCallingIdentity(token);
3342            }
3343        } else {
3344            return true;
3345        }
3346    }
3347
3348    /**
3349     * Update given flags based on encryption status of current user.
3350     */
3351    private int updateFlags(int flags, int userId) {
3352        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3353                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3354            // Caller expressed an explicit opinion about what encryption
3355            // aware/unaware components they want to see, so fall through and
3356            // give them what they want
3357        } else {
3358            // Caller expressed no opinion, so match based on user state
3359            if (isUserKeyUnlocked(userId)) {
3360                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3361            } else {
3362                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3363            }
3364        }
3365        return flags;
3366    }
3367
3368    /**
3369     * Update given flags when being used to request {@link PackageInfo}.
3370     */
3371    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3372        boolean triaged = true;
3373        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3374                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3375            // Caller is asking for component details, so they'd better be
3376            // asking for specific encryption matching behavior, or be triaged
3377            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3378                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3379                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3380                triaged = false;
3381            }
3382        }
3383        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3384                | PackageManager.MATCH_SYSTEM_ONLY
3385                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3386            triaged = false;
3387        }
3388        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3389            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3390                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3391        }
3392        return updateFlags(flags, userId);
3393    }
3394
3395    /**
3396     * Update given flags when being used to request {@link ApplicationInfo}.
3397     */
3398    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3399        return updateFlagsForPackage(flags, userId, cookie);
3400    }
3401
3402    /**
3403     * Update given flags when being used to request {@link ComponentInfo}.
3404     */
3405    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3406        if (cookie instanceof Intent) {
3407            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3408                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3409            }
3410        }
3411
3412        boolean triaged = true;
3413        // Caller is asking for component details, so they'd better be
3414        // asking for specific encryption matching behavior, or be triaged
3415        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3416                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3417                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3418            triaged = false;
3419        }
3420        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3421            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3422                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3423        }
3424
3425        return updateFlags(flags, userId);
3426    }
3427
3428    /**
3429     * Update given flags when being used to request {@link ResolveInfo}.
3430     */
3431    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3432        // Safe mode means we shouldn't match any third-party components
3433        if (mSafeMode) {
3434            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3435        }
3436
3437        return updateFlagsForComponent(flags, userId, cookie);
3438    }
3439
3440    @Override
3441    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3442        if (!sUserManager.exists(userId)) return null;
3443        flags = updateFlagsForComponent(flags, userId, component);
3444        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3445                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3446        synchronized (mPackages) {
3447            PackageParser.Activity a = mActivities.mActivities.get(component);
3448
3449            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3450            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3451                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3452                if (ps == null) return null;
3453                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3454                        userId);
3455            }
3456            if (mResolveComponentName.equals(component)) {
3457                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3458                        new PackageUserState(), userId);
3459            }
3460        }
3461        return null;
3462    }
3463
3464    @Override
3465    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3466            String resolvedType) {
3467        synchronized (mPackages) {
3468            if (component.equals(mResolveComponentName)) {
3469                // The resolver supports EVERYTHING!
3470                return true;
3471            }
3472            PackageParser.Activity a = mActivities.mActivities.get(component);
3473            if (a == null) {
3474                return false;
3475            }
3476            for (int i=0; i<a.intents.size(); i++) {
3477                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3478                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3479                    return true;
3480                }
3481            }
3482            return false;
3483        }
3484    }
3485
3486    @Override
3487    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3488        if (!sUserManager.exists(userId)) return null;
3489        flags = updateFlagsForComponent(flags, userId, component);
3490        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3491                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3492        synchronized (mPackages) {
3493            PackageParser.Activity a = mReceivers.mActivities.get(component);
3494            if (DEBUG_PACKAGE_INFO) Log.v(
3495                TAG, "getReceiverInfo " + component + ": " + a);
3496            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3497                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3498                if (ps == null) return null;
3499                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3500                        userId);
3501            }
3502        }
3503        return null;
3504    }
3505
3506    @Override
3507    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3508        if (!sUserManager.exists(userId)) return null;
3509        flags = updateFlagsForComponent(flags, userId, component);
3510        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3511                false /* requireFullPermission */, false /* checkShell */, "get service info");
3512        synchronized (mPackages) {
3513            PackageParser.Service s = mServices.mServices.get(component);
3514            if (DEBUG_PACKAGE_INFO) Log.v(
3515                TAG, "getServiceInfo " + component + ": " + s);
3516            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3517                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3518                if (ps == null) return null;
3519                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3520                        userId);
3521            }
3522        }
3523        return null;
3524    }
3525
3526    @Override
3527    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3528        if (!sUserManager.exists(userId)) return null;
3529        flags = updateFlagsForComponent(flags, userId, component);
3530        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3531                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3532        synchronized (mPackages) {
3533            PackageParser.Provider p = mProviders.mProviders.get(component);
3534            if (DEBUG_PACKAGE_INFO) Log.v(
3535                TAG, "getProviderInfo " + component + ": " + p);
3536            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3537                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3538                if (ps == null) return null;
3539                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3540                        userId);
3541            }
3542        }
3543        return null;
3544    }
3545
3546    @Override
3547    public String[] getSystemSharedLibraryNames() {
3548        Set<String> libSet;
3549        synchronized (mPackages) {
3550            libSet = mSharedLibraries.keySet();
3551            int size = libSet.size();
3552            if (size > 0) {
3553                String[] libs = new String[size];
3554                libSet.toArray(libs);
3555                return libs;
3556            }
3557        }
3558        return null;
3559    }
3560
3561    @Override
3562    public @Nullable String getServicesSystemSharedLibraryPackageName() {
3563        synchronized (mPackages) {
3564            SharedLibraryEntry libraryEntry = mSharedLibraries.get(
3565                    PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
3566            if (libraryEntry != null) {
3567                return libraryEntry.apk;
3568            }
3569        }
3570        return null;
3571    }
3572
3573    @Override
3574    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3575        synchronized (mPackages) {
3576            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3577
3578            final FeatureInfo fi = new FeatureInfo();
3579            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3580                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3581            res.add(fi);
3582
3583            return new ParceledListSlice<>(res);
3584        }
3585    }
3586
3587    @Override
3588    public boolean hasSystemFeature(String name, int version) {
3589        synchronized (mPackages) {
3590            final FeatureInfo feat = mAvailableFeatures.get(name);
3591            if (feat == null) {
3592                return false;
3593            } else {
3594                return feat.version >= version;
3595            }
3596        }
3597    }
3598
3599    @Override
3600    public int checkPermission(String permName, String pkgName, int userId) {
3601        if (!sUserManager.exists(userId)) {
3602            return PackageManager.PERMISSION_DENIED;
3603        }
3604
3605        synchronized (mPackages) {
3606            final PackageParser.Package p = mPackages.get(pkgName);
3607            if (p != null && p.mExtras != null) {
3608                final PackageSetting ps = (PackageSetting) p.mExtras;
3609                final PermissionsState permissionsState = ps.getPermissionsState();
3610                if (permissionsState.hasPermission(permName, userId)) {
3611                    return PackageManager.PERMISSION_GRANTED;
3612                }
3613                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3614                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3615                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3616                    return PackageManager.PERMISSION_GRANTED;
3617                }
3618            }
3619        }
3620
3621        return PackageManager.PERMISSION_DENIED;
3622    }
3623
3624    @Override
3625    public int checkUidPermission(String permName, int uid) {
3626        final int userId = UserHandle.getUserId(uid);
3627
3628        if (!sUserManager.exists(userId)) {
3629            return PackageManager.PERMISSION_DENIED;
3630        }
3631
3632        synchronized (mPackages) {
3633            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3634            if (obj != null) {
3635                final SettingBase ps = (SettingBase) obj;
3636                final PermissionsState permissionsState = ps.getPermissionsState();
3637                if (permissionsState.hasPermission(permName, userId)) {
3638                    return PackageManager.PERMISSION_GRANTED;
3639                }
3640                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3641                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3642                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3643                    return PackageManager.PERMISSION_GRANTED;
3644                }
3645            } else {
3646                ArraySet<String> perms = mSystemPermissions.get(uid);
3647                if (perms != null) {
3648                    if (perms.contains(permName)) {
3649                        return PackageManager.PERMISSION_GRANTED;
3650                    }
3651                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3652                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3653                        return PackageManager.PERMISSION_GRANTED;
3654                    }
3655                }
3656            }
3657        }
3658
3659        return PackageManager.PERMISSION_DENIED;
3660    }
3661
3662    @Override
3663    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3664        if (UserHandle.getCallingUserId() != userId) {
3665            mContext.enforceCallingPermission(
3666                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3667                    "isPermissionRevokedByPolicy for user " + userId);
3668        }
3669
3670        if (checkPermission(permission, packageName, userId)
3671                == PackageManager.PERMISSION_GRANTED) {
3672            return false;
3673        }
3674
3675        final long identity = Binder.clearCallingIdentity();
3676        try {
3677            final int flags = getPermissionFlags(permission, packageName, userId);
3678            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3679        } finally {
3680            Binder.restoreCallingIdentity(identity);
3681        }
3682    }
3683
3684    @Override
3685    public String getPermissionControllerPackageName() {
3686        synchronized (mPackages) {
3687            return mRequiredInstallerPackage;
3688        }
3689    }
3690
3691    /**
3692     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3693     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3694     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3695     * @param message the message to log on security exception
3696     */
3697    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3698            boolean checkShell, String message) {
3699        if (userId < 0) {
3700            throw new IllegalArgumentException("Invalid userId " + userId);
3701        }
3702        if (checkShell) {
3703            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3704        }
3705        if (userId == UserHandle.getUserId(callingUid)) return;
3706        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3707            if (requireFullPermission) {
3708                mContext.enforceCallingOrSelfPermission(
3709                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3710            } else {
3711                try {
3712                    mContext.enforceCallingOrSelfPermission(
3713                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3714                } catch (SecurityException se) {
3715                    mContext.enforceCallingOrSelfPermission(
3716                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3717                }
3718            }
3719        }
3720    }
3721
3722    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3723        if (callingUid == Process.SHELL_UID) {
3724            if (userHandle >= 0
3725                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3726                throw new SecurityException("Shell does not have permission to access user "
3727                        + userHandle);
3728            } else if (userHandle < 0) {
3729                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3730                        + Debug.getCallers(3));
3731            }
3732        }
3733    }
3734
3735    private BasePermission findPermissionTreeLP(String permName) {
3736        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3737            if (permName.startsWith(bp.name) &&
3738                    permName.length() > bp.name.length() &&
3739                    permName.charAt(bp.name.length()) == '.') {
3740                return bp;
3741            }
3742        }
3743        return null;
3744    }
3745
3746    private BasePermission checkPermissionTreeLP(String permName) {
3747        if (permName != null) {
3748            BasePermission bp = findPermissionTreeLP(permName);
3749            if (bp != null) {
3750                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3751                    return bp;
3752                }
3753                throw new SecurityException("Calling uid "
3754                        + Binder.getCallingUid()
3755                        + " is not allowed to add to permission tree "
3756                        + bp.name + " owned by uid " + bp.uid);
3757            }
3758        }
3759        throw new SecurityException("No permission tree found for " + permName);
3760    }
3761
3762    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3763        if (s1 == null) {
3764            return s2 == null;
3765        }
3766        if (s2 == null) {
3767            return false;
3768        }
3769        if (s1.getClass() != s2.getClass()) {
3770            return false;
3771        }
3772        return s1.equals(s2);
3773    }
3774
3775    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3776        if (pi1.icon != pi2.icon) return false;
3777        if (pi1.logo != pi2.logo) return false;
3778        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3779        if (!compareStrings(pi1.name, pi2.name)) return false;
3780        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3781        // We'll take care of setting this one.
3782        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3783        // These are not currently stored in settings.
3784        //if (!compareStrings(pi1.group, pi2.group)) return false;
3785        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3786        //if (pi1.labelRes != pi2.labelRes) return false;
3787        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3788        return true;
3789    }
3790
3791    int permissionInfoFootprint(PermissionInfo info) {
3792        int size = info.name.length();
3793        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3794        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3795        return size;
3796    }
3797
3798    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3799        int size = 0;
3800        for (BasePermission perm : mSettings.mPermissions.values()) {
3801            if (perm.uid == tree.uid) {
3802                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3803            }
3804        }
3805        return size;
3806    }
3807
3808    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3809        // We calculate the max size of permissions defined by this uid and throw
3810        // if that plus the size of 'info' would exceed our stated maximum.
3811        if (tree.uid != Process.SYSTEM_UID) {
3812            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3813            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3814                throw new SecurityException("Permission tree size cap exceeded");
3815            }
3816        }
3817    }
3818
3819    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3820        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3821            throw new SecurityException("Label must be specified in permission");
3822        }
3823        BasePermission tree = checkPermissionTreeLP(info.name);
3824        BasePermission bp = mSettings.mPermissions.get(info.name);
3825        boolean added = bp == null;
3826        boolean changed = true;
3827        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3828        if (added) {
3829            enforcePermissionCapLocked(info, tree);
3830            bp = new BasePermission(info.name, tree.sourcePackage,
3831                    BasePermission.TYPE_DYNAMIC);
3832        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3833            throw new SecurityException(
3834                    "Not allowed to modify non-dynamic permission "
3835                    + info.name);
3836        } else {
3837            if (bp.protectionLevel == fixedLevel
3838                    && bp.perm.owner.equals(tree.perm.owner)
3839                    && bp.uid == tree.uid
3840                    && comparePermissionInfos(bp.perm.info, info)) {
3841                changed = false;
3842            }
3843        }
3844        bp.protectionLevel = fixedLevel;
3845        info = new PermissionInfo(info);
3846        info.protectionLevel = fixedLevel;
3847        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3848        bp.perm.info.packageName = tree.perm.info.packageName;
3849        bp.uid = tree.uid;
3850        if (added) {
3851            mSettings.mPermissions.put(info.name, bp);
3852        }
3853        if (changed) {
3854            if (!async) {
3855                mSettings.writeLPr();
3856            } else {
3857                scheduleWriteSettingsLocked();
3858            }
3859        }
3860        return added;
3861    }
3862
3863    @Override
3864    public boolean addPermission(PermissionInfo info) {
3865        synchronized (mPackages) {
3866            return addPermissionLocked(info, false);
3867        }
3868    }
3869
3870    @Override
3871    public boolean addPermissionAsync(PermissionInfo info) {
3872        synchronized (mPackages) {
3873            return addPermissionLocked(info, true);
3874        }
3875    }
3876
3877    @Override
3878    public void removePermission(String name) {
3879        synchronized (mPackages) {
3880            checkPermissionTreeLP(name);
3881            BasePermission bp = mSettings.mPermissions.get(name);
3882            if (bp != null) {
3883                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3884                    throw new SecurityException(
3885                            "Not allowed to modify non-dynamic permission "
3886                            + name);
3887                }
3888                mSettings.mPermissions.remove(name);
3889                mSettings.writeLPr();
3890            }
3891        }
3892    }
3893
3894    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3895            BasePermission bp) {
3896        int index = pkg.requestedPermissions.indexOf(bp.name);
3897        if (index == -1) {
3898            throw new SecurityException("Package " + pkg.packageName
3899                    + " has not requested permission " + bp.name);
3900        }
3901        if (!bp.isRuntime() && !bp.isDevelopment()) {
3902            throw new SecurityException("Permission " + bp.name
3903                    + " is not a changeable permission type");
3904        }
3905    }
3906
3907    @Override
3908    public void grantRuntimePermission(String packageName, String name, final int userId) {
3909        if (!sUserManager.exists(userId)) {
3910            Log.e(TAG, "No such user:" + userId);
3911            return;
3912        }
3913
3914        mContext.enforceCallingOrSelfPermission(
3915                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3916                "grantRuntimePermission");
3917
3918        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3919                true /* requireFullPermission */, true /* checkShell */,
3920                "grantRuntimePermission");
3921
3922        final int uid;
3923        final SettingBase sb;
3924
3925        synchronized (mPackages) {
3926            final PackageParser.Package pkg = mPackages.get(packageName);
3927            if (pkg == null) {
3928                throw new IllegalArgumentException("Unknown package: " + packageName);
3929            }
3930
3931            final BasePermission bp = mSettings.mPermissions.get(name);
3932            if (bp == null) {
3933                throw new IllegalArgumentException("Unknown permission: " + name);
3934            }
3935
3936            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3937
3938            // If a permission review is required for legacy apps we represent
3939            // their permissions as always granted runtime ones since we need
3940            // to keep the review required permission flag per user while an
3941            // install permission's state is shared across all users.
3942            if (Build.PERMISSIONS_REVIEW_REQUIRED
3943                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3944                    && bp.isRuntime()) {
3945                return;
3946            }
3947
3948            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3949            sb = (SettingBase) pkg.mExtras;
3950            if (sb == null) {
3951                throw new IllegalArgumentException("Unknown package: " + packageName);
3952            }
3953
3954            final PermissionsState permissionsState = sb.getPermissionsState();
3955
3956            final int flags = permissionsState.getPermissionFlags(name, userId);
3957            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3958                throw new SecurityException("Cannot grant system fixed permission "
3959                        + name + " for package " + packageName);
3960            }
3961
3962            if (bp.isDevelopment()) {
3963                // Development permissions must be handled specially, since they are not
3964                // normal runtime permissions.  For now they apply to all users.
3965                if (permissionsState.grantInstallPermission(bp) !=
3966                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3967                    scheduleWriteSettingsLocked();
3968                }
3969                return;
3970            }
3971
3972            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3973                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3974                return;
3975            }
3976
3977            final int result = permissionsState.grantRuntimePermission(bp, userId);
3978            switch (result) {
3979                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3980                    return;
3981                }
3982
3983                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3984                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3985                    mHandler.post(new Runnable() {
3986                        @Override
3987                        public void run() {
3988                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3989                        }
3990                    });
3991                }
3992                break;
3993            }
3994
3995            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3996
3997            // Not critical if that is lost - app has to request again.
3998            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3999        }
4000
4001        // Only need to do this if user is initialized. Otherwise it's a new user
4002        // and there are no processes running as the user yet and there's no need
4003        // to make an expensive call to remount processes for the changed permissions.
4004        if (READ_EXTERNAL_STORAGE.equals(name)
4005                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4006            final long token = Binder.clearCallingIdentity();
4007            try {
4008                if (sUserManager.isInitialized(userId)) {
4009                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4010                            MountServiceInternal.class);
4011                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4012                }
4013            } finally {
4014                Binder.restoreCallingIdentity(token);
4015            }
4016        }
4017    }
4018
4019    @Override
4020    public void revokeRuntimePermission(String packageName, String name, int userId) {
4021        if (!sUserManager.exists(userId)) {
4022            Log.e(TAG, "No such user:" + userId);
4023            return;
4024        }
4025
4026        mContext.enforceCallingOrSelfPermission(
4027                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4028                "revokeRuntimePermission");
4029
4030        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4031                true /* requireFullPermission */, true /* checkShell */,
4032                "revokeRuntimePermission");
4033
4034        final int appId;
4035
4036        synchronized (mPackages) {
4037            final PackageParser.Package pkg = mPackages.get(packageName);
4038            if (pkg == null) {
4039                throw new IllegalArgumentException("Unknown package: " + packageName);
4040            }
4041
4042            final BasePermission bp = mSettings.mPermissions.get(name);
4043            if (bp == null) {
4044                throw new IllegalArgumentException("Unknown permission: " + name);
4045            }
4046
4047            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4048
4049            // If a permission review is required for legacy apps we represent
4050            // their permissions as always granted runtime ones since we need
4051            // to keep the review required permission flag per user while an
4052            // install permission's state is shared across all users.
4053            if (Build.PERMISSIONS_REVIEW_REQUIRED
4054                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4055                    && bp.isRuntime()) {
4056                return;
4057            }
4058
4059            SettingBase sb = (SettingBase) pkg.mExtras;
4060            if (sb == null) {
4061                throw new IllegalArgumentException("Unknown package: " + packageName);
4062            }
4063
4064            final PermissionsState permissionsState = sb.getPermissionsState();
4065
4066            final int flags = permissionsState.getPermissionFlags(name, userId);
4067            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4068                throw new SecurityException("Cannot revoke system fixed permission "
4069                        + name + " for package " + packageName);
4070            }
4071
4072            if (bp.isDevelopment()) {
4073                // Development permissions must be handled specially, since they are not
4074                // normal runtime permissions.  For now they apply to all users.
4075                if (permissionsState.revokeInstallPermission(bp) !=
4076                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4077                    scheduleWriteSettingsLocked();
4078                }
4079                return;
4080            }
4081
4082            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4083                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4084                return;
4085            }
4086
4087            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4088
4089            // Critical, after this call app should never have the permission.
4090            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4091
4092            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4093        }
4094
4095        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4096    }
4097
4098    @Override
4099    public void resetRuntimePermissions() {
4100        mContext.enforceCallingOrSelfPermission(
4101                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4102                "revokeRuntimePermission");
4103
4104        int callingUid = Binder.getCallingUid();
4105        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4106            mContext.enforceCallingOrSelfPermission(
4107                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4108                    "resetRuntimePermissions");
4109        }
4110
4111        synchronized (mPackages) {
4112            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4113            for (int userId : UserManagerService.getInstance().getUserIds()) {
4114                final int packageCount = mPackages.size();
4115                for (int i = 0; i < packageCount; i++) {
4116                    PackageParser.Package pkg = mPackages.valueAt(i);
4117                    if (!(pkg.mExtras instanceof PackageSetting)) {
4118                        continue;
4119                    }
4120                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4121                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4122                }
4123            }
4124        }
4125    }
4126
4127    @Override
4128    public int getPermissionFlags(String name, String packageName, int userId) {
4129        if (!sUserManager.exists(userId)) {
4130            return 0;
4131        }
4132
4133        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4134
4135        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4136                true /* requireFullPermission */, false /* checkShell */,
4137                "getPermissionFlags");
4138
4139        synchronized (mPackages) {
4140            final PackageParser.Package pkg = mPackages.get(packageName);
4141            if (pkg == null) {
4142                throw new IllegalArgumentException("Unknown package: " + packageName);
4143            }
4144
4145            final BasePermission bp = mSettings.mPermissions.get(name);
4146            if (bp == null) {
4147                throw new IllegalArgumentException("Unknown permission: " + name);
4148            }
4149
4150            SettingBase sb = (SettingBase) pkg.mExtras;
4151            if (sb == null) {
4152                throw new IllegalArgumentException("Unknown package: " + packageName);
4153            }
4154
4155            PermissionsState permissionsState = sb.getPermissionsState();
4156            return permissionsState.getPermissionFlags(name, userId);
4157        }
4158    }
4159
4160    @Override
4161    public void updatePermissionFlags(String name, String packageName, int flagMask,
4162            int flagValues, int userId) {
4163        if (!sUserManager.exists(userId)) {
4164            return;
4165        }
4166
4167        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4168
4169        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4170                true /* requireFullPermission */, true /* checkShell */,
4171                "updatePermissionFlags");
4172
4173        // Only the system can change these flags and nothing else.
4174        if (getCallingUid() != Process.SYSTEM_UID) {
4175            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4176            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4177            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4178            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4179            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4180        }
4181
4182        synchronized (mPackages) {
4183            final PackageParser.Package pkg = mPackages.get(packageName);
4184            if (pkg == null) {
4185                throw new IllegalArgumentException("Unknown package: " + packageName);
4186            }
4187
4188            final BasePermission bp = mSettings.mPermissions.get(name);
4189            if (bp == null) {
4190                throw new IllegalArgumentException("Unknown permission: " + name);
4191            }
4192
4193            SettingBase sb = (SettingBase) pkg.mExtras;
4194            if (sb == null) {
4195                throw new IllegalArgumentException("Unknown package: " + packageName);
4196            }
4197
4198            PermissionsState permissionsState = sb.getPermissionsState();
4199
4200            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4201
4202            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4203                // Install and runtime permissions are stored in different places,
4204                // so figure out what permission changed and persist the change.
4205                if (permissionsState.getInstallPermissionState(name) != null) {
4206                    scheduleWriteSettingsLocked();
4207                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4208                        || hadState) {
4209                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4210                }
4211            }
4212        }
4213    }
4214
4215    /**
4216     * Update the permission flags for all packages and runtime permissions of a user in order
4217     * to allow device or profile owner to remove POLICY_FIXED.
4218     */
4219    @Override
4220    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4221        if (!sUserManager.exists(userId)) {
4222            return;
4223        }
4224
4225        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4226
4227        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4228                true /* requireFullPermission */, true /* checkShell */,
4229                "updatePermissionFlagsForAllApps");
4230
4231        // Only the system can change system fixed flags.
4232        if (getCallingUid() != Process.SYSTEM_UID) {
4233            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4234            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4235        }
4236
4237        synchronized (mPackages) {
4238            boolean changed = false;
4239            final int packageCount = mPackages.size();
4240            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4241                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4242                SettingBase sb = (SettingBase) pkg.mExtras;
4243                if (sb == null) {
4244                    continue;
4245                }
4246                PermissionsState permissionsState = sb.getPermissionsState();
4247                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4248                        userId, flagMask, flagValues);
4249            }
4250            if (changed) {
4251                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4252            }
4253        }
4254    }
4255
4256    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4257        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4258                != PackageManager.PERMISSION_GRANTED
4259            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4260                != PackageManager.PERMISSION_GRANTED) {
4261            throw new SecurityException(message + " requires "
4262                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4263                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4264        }
4265    }
4266
4267    @Override
4268    public boolean shouldShowRequestPermissionRationale(String permissionName,
4269            String packageName, int userId) {
4270        if (UserHandle.getCallingUserId() != userId) {
4271            mContext.enforceCallingPermission(
4272                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4273                    "canShowRequestPermissionRationale for user " + userId);
4274        }
4275
4276        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4277        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4278            return false;
4279        }
4280
4281        if (checkPermission(permissionName, packageName, userId)
4282                == PackageManager.PERMISSION_GRANTED) {
4283            return false;
4284        }
4285
4286        final int flags;
4287
4288        final long identity = Binder.clearCallingIdentity();
4289        try {
4290            flags = getPermissionFlags(permissionName,
4291                    packageName, userId);
4292        } finally {
4293            Binder.restoreCallingIdentity(identity);
4294        }
4295
4296        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4297                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4298                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4299
4300        if ((flags & fixedFlags) != 0) {
4301            return false;
4302        }
4303
4304        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4305    }
4306
4307    @Override
4308    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4309        mContext.enforceCallingOrSelfPermission(
4310                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4311                "addOnPermissionsChangeListener");
4312
4313        synchronized (mPackages) {
4314            mOnPermissionChangeListeners.addListenerLocked(listener);
4315        }
4316    }
4317
4318    @Override
4319    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4320        synchronized (mPackages) {
4321            mOnPermissionChangeListeners.removeListenerLocked(listener);
4322        }
4323    }
4324
4325    @Override
4326    public boolean isProtectedBroadcast(String actionName) {
4327        synchronized (mPackages) {
4328            if (mProtectedBroadcasts.contains(actionName)) {
4329                return true;
4330            } else if (actionName != null) {
4331                // TODO: remove these terrible hacks
4332                if (actionName.startsWith("android.net.netmon.lingerExpired")
4333                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4334                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4335                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4336                    return true;
4337                }
4338            }
4339        }
4340        return false;
4341    }
4342
4343    @Override
4344    public int checkSignatures(String pkg1, String pkg2) {
4345        synchronized (mPackages) {
4346            final PackageParser.Package p1 = mPackages.get(pkg1);
4347            final PackageParser.Package p2 = mPackages.get(pkg2);
4348            if (p1 == null || p1.mExtras == null
4349                    || p2 == null || p2.mExtras == null) {
4350                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4351            }
4352            return compareSignatures(p1.mSignatures, p2.mSignatures);
4353        }
4354    }
4355
4356    @Override
4357    public int checkUidSignatures(int uid1, int uid2) {
4358        // Map to base uids.
4359        uid1 = UserHandle.getAppId(uid1);
4360        uid2 = UserHandle.getAppId(uid2);
4361        // reader
4362        synchronized (mPackages) {
4363            Signature[] s1;
4364            Signature[] s2;
4365            Object obj = mSettings.getUserIdLPr(uid1);
4366            if (obj != null) {
4367                if (obj instanceof SharedUserSetting) {
4368                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4369                } else if (obj instanceof PackageSetting) {
4370                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4371                } else {
4372                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4373                }
4374            } else {
4375                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4376            }
4377            obj = mSettings.getUserIdLPr(uid2);
4378            if (obj != null) {
4379                if (obj instanceof SharedUserSetting) {
4380                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4381                } else if (obj instanceof PackageSetting) {
4382                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4383                } else {
4384                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4385                }
4386            } else {
4387                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4388            }
4389            return compareSignatures(s1, s2);
4390        }
4391    }
4392
4393    private void killUid(int appId, int userId, String reason) {
4394        final long identity = Binder.clearCallingIdentity();
4395        try {
4396            IActivityManager am = ActivityManagerNative.getDefault();
4397            if (am != null) {
4398                try {
4399                    am.killUid(appId, userId, reason);
4400                } catch (RemoteException e) {
4401                    /* ignore - same process */
4402                }
4403            }
4404        } finally {
4405            Binder.restoreCallingIdentity(identity);
4406        }
4407    }
4408
4409    /**
4410     * Compares two sets of signatures. Returns:
4411     * <br />
4412     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4413     * <br />
4414     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4415     * <br />
4416     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4417     * <br />
4418     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4419     * <br />
4420     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4421     */
4422    static int compareSignatures(Signature[] s1, Signature[] s2) {
4423        if (s1 == null) {
4424            return s2 == null
4425                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4426                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4427        }
4428
4429        if (s2 == null) {
4430            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4431        }
4432
4433        if (s1.length != s2.length) {
4434            return PackageManager.SIGNATURE_NO_MATCH;
4435        }
4436
4437        // Since both signature sets are of size 1, we can compare without HashSets.
4438        if (s1.length == 1) {
4439            return s1[0].equals(s2[0]) ?
4440                    PackageManager.SIGNATURE_MATCH :
4441                    PackageManager.SIGNATURE_NO_MATCH;
4442        }
4443
4444        ArraySet<Signature> set1 = new ArraySet<Signature>();
4445        for (Signature sig : s1) {
4446            set1.add(sig);
4447        }
4448        ArraySet<Signature> set2 = new ArraySet<Signature>();
4449        for (Signature sig : s2) {
4450            set2.add(sig);
4451        }
4452        // Make sure s2 contains all signatures in s1.
4453        if (set1.equals(set2)) {
4454            return PackageManager.SIGNATURE_MATCH;
4455        }
4456        return PackageManager.SIGNATURE_NO_MATCH;
4457    }
4458
4459    /**
4460     * If the database version for this type of package (internal storage or
4461     * external storage) is less than the version where package signatures
4462     * were updated, return true.
4463     */
4464    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4465        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4466        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4467    }
4468
4469    /**
4470     * Used for backward compatibility to make sure any packages with
4471     * certificate chains get upgraded to the new style. {@code existingSigs}
4472     * will be in the old format (since they were stored on disk from before the
4473     * system upgrade) and {@code scannedSigs} will be in the newer format.
4474     */
4475    private int compareSignaturesCompat(PackageSignatures existingSigs,
4476            PackageParser.Package scannedPkg) {
4477        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4478            return PackageManager.SIGNATURE_NO_MATCH;
4479        }
4480
4481        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4482        for (Signature sig : existingSigs.mSignatures) {
4483            existingSet.add(sig);
4484        }
4485        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4486        for (Signature sig : scannedPkg.mSignatures) {
4487            try {
4488                Signature[] chainSignatures = sig.getChainSignatures();
4489                for (Signature chainSig : chainSignatures) {
4490                    scannedCompatSet.add(chainSig);
4491                }
4492            } catch (CertificateEncodingException e) {
4493                scannedCompatSet.add(sig);
4494            }
4495        }
4496        /*
4497         * Make sure the expanded scanned set contains all signatures in the
4498         * existing one.
4499         */
4500        if (scannedCompatSet.equals(existingSet)) {
4501            // Migrate the old signatures to the new scheme.
4502            existingSigs.assignSignatures(scannedPkg.mSignatures);
4503            // The new KeySets will be re-added later in the scanning process.
4504            synchronized (mPackages) {
4505                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4506            }
4507            return PackageManager.SIGNATURE_MATCH;
4508        }
4509        return PackageManager.SIGNATURE_NO_MATCH;
4510    }
4511
4512    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4513        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4514        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4515    }
4516
4517    private int compareSignaturesRecover(PackageSignatures existingSigs,
4518            PackageParser.Package scannedPkg) {
4519        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4520            return PackageManager.SIGNATURE_NO_MATCH;
4521        }
4522
4523        String msg = null;
4524        try {
4525            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4526                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4527                        + scannedPkg.packageName);
4528                return PackageManager.SIGNATURE_MATCH;
4529            }
4530        } catch (CertificateException e) {
4531            msg = e.getMessage();
4532        }
4533
4534        logCriticalInfo(Log.INFO,
4535                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4536        return PackageManager.SIGNATURE_NO_MATCH;
4537    }
4538
4539    @Override
4540    public List<String> getAllPackages() {
4541        synchronized (mPackages) {
4542            return new ArrayList<String>(mPackages.keySet());
4543        }
4544    }
4545
4546    @Override
4547    public String[] getPackagesForUid(int uid) {
4548        uid = UserHandle.getAppId(uid);
4549        // reader
4550        synchronized (mPackages) {
4551            Object obj = mSettings.getUserIdLPr(uid);
4552            if (obj instanceof SharedUserSetting) {
4553                final SharedUserSetting sus = (SharedUserSetting) obj;
4554                final int N = sus.packages.size();
4555                final String[] res = new String[N];
4556                final Iterator<PackageSetting> it = sus.packages.iterator();
4557                int i = 0;
4558                while (it.hasNext()) {
4559                    res[i++] = it.next().name;
4560                }
4561                return res;
4562            } else if (obj instanceof PackageSetting) {
4563                final PackageSetting ps = (PackageSetting) obj;
4564                return new String[] { ps.name };
4565            }
4566        }
4567        return null;
4568    }
4569
4570    @Override
4571    public String getNameForUid(int uid) {
4572        // reader
4573        synchronized (mPackages) {
4574            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4575            if (obj instanceof SharedUserSetting) {
4576                final SharedUserSetting sus = (SharedUserSetting) obj;
4577                return sus.name + ":" + sus.userId;
4578            } else if (obj instanceof PackageSetting) {
4579                final PackageSetting ps = (PackageSetting) obj;
4580                return ps.name;
4581            }
4582        }
4583        return null;
4584    }
4585
4586    @Override
4587    public int getUidForSharedUser(String sharedUserName) {
4588        if(sharedUserName == null) {
4589            return -1;
4590        }
4591        // reader
4592        synchronized (mPackages) {
4593            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4594            if (suid == null) {
4595                return -1;
4596            }
4597            return suid.userId;
4598        }
4599    }
4600
4601    @Override
4602    public int getFlagsForUid(int uid) {
4603        synchronized (mPackages) {
4604            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4605            if (obj instanceof SharedUserSetting) {
4606                final SharedUserSetting sus = (SharedUserSetting) obj;
4607                return sus.pkgFlags;
4608            } else if (obj instanceof PackageSetting) {
4609                final PackageSetting ps = (PackageSetting) obj;
4610                return ps.pkgFlags;
4611            }
4612        }
4613        return 0;
4614    }
4615
4616    @Override
4617    public int getPrivateFlagsForUid(int uid) {
4618        synchronized (mPackages) {
4619            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4620            if (obj instanceof SharedUserSetting) {
4621                final SharedUserSetting sus = (SharedUserSetting) obj;
4622                return sus.pkgPrivateFlags;
4623            } else if (obj instanceof PackageSetting) {
4624                final PackageSetting ps = (PackageSetting) obj;
4625                return ps.pkgPrivateFlags;
4626            }
4627        }
4628        return 0;
4629    }
4630
4631    @Override
4632    public boolean isUidPrivileged(int uid) {
4633        uid = UserHandle.getAppId(uid);
4634        // reader
4635        synchronized (mPackages) {
4636            Object obj = mSettings.getUserIdLPr(uid);
4637            if (obj instanceof SharedUserSetting) {
4638                final SharedUserSetting sus = (SharedUserSetting) obj;
4639                final Iterator<PackageSetting> it = sus.packages.iterator();
4640                while (it.hasNext()) {
4641                    if (it.next().isPrivileged()) {
4642                        return true;
4643                    }
4644                }
4645            } else if (obj instanceof PackageSetting) {
4646                final PackageSetting ps = (PackageSetting) obj;
4647                return ps.isPrivileged();
4648            }
4649        }
4650        return false;
4651    }
4652
4653    @Override
4654    public String[] getAppOpPermissionPackages(String permissionName) {
4655        synchronized (mPackages) {
4656            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4657            if (pkgs == null) {
4658                return null;
4659            }
4660            return pkgs.toArray(new String[pkgs.size()]);
4661        }
4662    }
4663
4664    @Override
4665    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4666            int flags, int userId) {
4667        if (!sUserManager.exists(userId)) return null;
4668        flags = updateFlagsForResolve(flags, userId, intent);
4669        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4670                false /* requireFullPermission */, false /* checkShell */, "resolve intent");
4671        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4672                userId);
4673        final ResolveInfo bestChoice =
4674                chooseBestActivity(intent, resolvedType, flags, query, userId);
4675
4676        if (isEphemeralAllowed(intent, query, userId)) {
4677            final EphemeralResolveInfo ai =
4678                    getEphemeralResolveInfo(intent, resolvedType, userId);
4679            if (ai != null) {
4680                if (DEBUG_EPHEMERAL) {
4681                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4682                }
4683                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4684                bestChoice.ephemeralResolveInfo = ai;
4685            }
4686        }
4687        return bestChoice;
4688    }
4689
4690    @Override
4691    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4692            IntentFilter filter, int match, ComponentName activity) {
4693        final int userId = UserHandle.getCallingUserId();
4694        if (DEBUG_PREFERRED) {
4695            Log.v(TAG, "setLastChosenActivity intent=" + intent
4696                + " resolvedType=" + resolvedType
4697                + " flags=" + flags
4698                + " filter=" + filter
4699                + " match=" + match
4700                + " activity=" + activity);
4701            filter.dump(new PrintStreamPrinter(System.out), "    ");
4702        }
4703        intent.setComponent(null);
4704        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4705                userId);
4706        // Find any earlier preferred or last chosen entries and nuke them
4707        findPreferredActivity(intent, resolvedType,
4708                flags, query, 0, false, true, false, userId);
4709        // Add the new activity as the last chosen for this filter
4710        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4711                "Setting last chosen");
4712    }
4713
4714    @Override
4715    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4716        final int userId = UserHandle.getCallingUserId();
4717        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4718        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4719                userId);
4720        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4721                false, false, false, userId);
4722    }
4723
4724
4725    private boolean isEphemeralAllowed(
4726            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4727        // Short circuit and return early if possible.
4728        if (DISABLE_EPHEMERAL_APPS) {
4729            return false;
4730        }
4731        final int callingUser = UserHandle.getCallingUserId();
4732        if (callingUser != UserHandle.USER_SYSTEM) {
4733            return false;
4734        }
4735        if (mEphemeralResolverConnection == null) {
4736            return false;
4737        }
4738        if (intent.getComponent() != null) {
4739            return false;
4740        }
4741        if (intent.getPackage() != null) {
4742            return false;
4743        }
4744        final boolean isWebUri = hasWebURI(intent);
4745        if (!isWebUri) {
4746            return false;
4747        }
4748        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4749        synchronized (mPackages) {
4750            final int count = resolvedActivites.size();
4751            for (int n = 0; n < count; n++) {
4752                ResolveInfo info = resolvedActivites.get(n);
4753                String packageName = info.activityInfo.packageName;
4754                PackageSetting ps = mSettings.mPackages.get(packageName);
4755                if (ps != null) {
4756                    // Try to get the status from User settings first
4757                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4758                    int status = (int) (packedStatus >> 32);
4759                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4760                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4761                        if (DEBUG_EPHEMERAL) {
4762                            Slog.v(TAG, "DENY ephemeral apps;"
4763                                + " pkg: " + packageName + ", status: " + status);
4764                        }
4765                        return false;
4766                    }
4767                }
4768            }
4769        }
4770        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4771        return true;
4772    }
4773
4774    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4775            int userId) {
4776        MessageDigest digest = null;
4777        try {
4778            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4779        } catch (NoSuchAlgorithmException e) {
4780            // If we can't create a digest, ignore ephemeral apps.
4781            return null;
4782        }
4783
4784        final byte[] hostBytes = intent.getData().getHost().getBytes();
4785        final byte[] digestBytes = digest.digest(hostBytes);
4786        int shaPrefix =
4787                digestBytes[0] << 24
4788                | digestBytes[1] << 16
4789                | digestBytes[2] << 8
4790                | digestBytes[3] << 0;
4791        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4792                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4793        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4794            // No hash prefix match; there are no ephemeral apps for this domain.
4795            return null;
4796        }
4797        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4798            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4799            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4800                continue;
4801            }
4802            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4803            // No filters; this should never happen.
4804            if (filters.isEmpty()) {
4805                continue;
4806            }
4807            // We have a domain match; resolve the filters to see if anything matches.
4808            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4809            for (int j = filters.size() - 1; j >= 0; --j) {
4810                final EphemeralResolveIntentInfo intentInfo =
4811                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4812                ephemeralResolver.addFilter(intentInfo);
4813            }
4814            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4815                    intent, resolvedType, false /*defaultOnly*/, userId);
4816            if (!matchedResolveInfoList.isEmpty()) {
4817                return matchedResolveInfoList.get(0);
4818            }
4819        }
4820        // Hash or filter mis-match; no ephemeral apps for this domain.
4821        return null;
4822    }
4823
4824    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4825            int flags, List<ResolveInfo> query, int userId) {
4826        if (query != null) {
4827            final int N = query.size();
4828            if (N == 1) {
4829                return query.get(0);
4830            } else if (N > 1) {
4831                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4832                // If there is more than one activity with the same priority,
4833                // then let the user decide between them.
4834                ResolveInfo r0 = query.get(0);
4835                ResolveInfo r1 = query.get(1);
4836                if (DEBUG_INTENT_MATCHING || debug) {
4837                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4838                            + r1.activityInfo.name + "=" + r1.priority);
4839                }
4840                // If the first activity has a higher priority, or a different
4841                // default, then it is always desirable to pick it.
4842                if (r0.priority != r1.priority
4843                        || r0.preferredOrder != r1.preferredOrder
4844                        || r0.isDefault != r1.isDefault) {
4845                    return query.get(0);
4846                }
4847                // If we have saved a preference for a preferred activity for
4848                // this Intent, use that.
4849                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4850                        flags, query, r0.priority, true, false, debug, userId);
4851                if (ri != null) {
4852                    return ri;
4853                }
4854                ri = new ResolveInfo(mResolveInfo);
4855                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4856                ri.activityInfo.applicationInfo = new ApplicationInfo(
4857                        ri.activityInfo.applicationInfo);
4858                if (userId != 0) {
4859                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4860                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4861                }
4862                // Make sure that the resolver is displayable in car mode
4863                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4864                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4865                return ri;
4866            }
4867        }
4868        return null;
4869    }
4870
4871    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4872            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4873        final int N = query.size();
4874        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4875                .get(userId);
4876        // Get the list of persistent preferred activities that handle the intent
4877        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4878        List<PersistentPreferredActivity> pprefs = ppir != null
4879                ? ppir.queryIntent(intent, resolvedType,
4880                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4881                : null;
4882        if (pprefs != null && pprefs.size() > 0) {
4883            final int M = pprefs.size();
4884            for (int i=0; i<M; i++) {
4885                final PersistentPreferredActivity ppa = pprefs.get(i);
4886                if (DEBUG_PREFERRED || debug) {
4887                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4888                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4889                            + "\n  component=" + ppa.mComponent);
4890                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4891                }
4892                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4893                        flags | MATCH_DISABLED_COMPONENTS, userId);
4894                if (DEBUG_PREFERRED || debug) {
4895                    Slog.v(TAG, "Found persistent preferred activity:");
4896                    if (ai != null) {
4897                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4898                    } else {
4899                        Slog.v(TAG, "  null");
4900                    }
4901                }
4902                if (ai == null) {
4903                    // This previously registered persistent preferred activity
4904                    // component is no longer known. Ignore it and do NOT remove it.
4905                    continue;
4906                }
4907                for (int j=0; j<N; j++) {
4908                    final ResolveInfo ri = query.get(j);
4909                    if (!ri.activityInfo.applicationInfo.packageName
4910                            .equals(ai.applicationInfo.packageName)) {
4911                        continue;
4912                    }
4913                    if (!ri.activityInfo.name.equals(ai.name)) {
4914                        continue;
4915                    }
4916                    //  Found a persistent preference that can handle the intent.
4917                    if (DEBUG_PREFERRED || debug) {
4918                        Slog.v(TAG, "Returning persistent preferred activity: " +
4919                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4920                    }
4921                    return ri;
4922                }
4923            }
4924        }
4925        return null;
4926    }
4927
4928    // TODO: handle preferred activities missing while user has amnesia
4929    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4930            List<ResolveInfo> query, int priority, boolean always,
4931            boolean removeMatches, boolean debug, int userId) {
4932        if (!sUserManager.exists(userId)) return null;
4933        flags = updateFlagsForResolve(flags, userId, intent);
4934        // writer
4935        synchronized (mPackages) {
4936            if (intent.getSelector() != null) {
4937                intent = intent.getSelector();
4938            }
4939            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4940
4941            // Try to find a matching persistent preferred activity.
4942            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4943                    debug, userId);
4944
4945            // If a persistent preferred activity matched, use it.
4946            if (pri != null) {
4947                return pri;
4948            }
4949
4950            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4951            // Get the list of preferred activities that handle the intent
4952            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4953            List<PreferredActivity> prefs = pir != null
4954                    ? pir.queryIntent(intent, resolvedType,
4955                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4956                    : null;
4957            if (prefs != null && prefs.size() > 0) {
4958                boolean changed = false;
4959                try {
4960                    // First figure out how good the original match set is.
4961                    // We will only allow preferred activities that came
4962                    // from the same match quality.
4963                    int match = 0;
4964
4965                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4966
4967                    final int N = query.size();
4968                    for (int j=0; j<N; j++) {
4969                        final ResolveInfo ri = query.get(j);
4970                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4971                                + ": 0x" + Integer.toHexString(match));
4972                        if (ri.match > match) {
4973                            match = ri.match;
4974                        }
4975                    }
4976
4977                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4978                            + Integer.toHexString(match));
4979
4980                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4981                    final int M = prefs.size();
4982                    for (int i=0; i<M; i++) {
4983                        final PreferredActivity pa = prefs.get(i);
4984                        if (DEBUG_PREFERRED || debug) {
4985                            Slog.v(TAG, "Checking PreferredActivity ds="
4986                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4987                                    + "\n  component=" + pa.mPref.mComponent);
4988                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4989                        }
4990                        if (pa.mPref.mMatch != match) {
4991                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4992                                    + Integer.toHexString(pa.mPref.mMatch));
4993                            continue;
4994                        }
4995                        // If it's not an "always" type preferred activity and that's what we're
4996                        // looking for, skip it.
4997                        if (always && !pa.mPref.mAlways) {
4998                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4999                            continue;
5000                        }
5001                        final ActivityInfo ai = getActivityInfo(
5002                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5003                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5004                                userId);
5005                        if (DEBUG_PREFERRED || debug) {
5006                            Slog.v(TAG, "Found preferred activity:");
5007                            if (ai != null) {
5008                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5009                            } else {
5010                                Slog.v(TAG, "  null");
5011                            }
5012                        }
5013                        if (ai == null) {
5014                            // This previously registered preferred activity
5015                            // component is no longer known.  Most likely an update
5016                            // to the app was installed and in the new version this
5017                            // component no longer exists.  Clean it up by removing
5018                            // it from the preferred activities list, and skip it.
5019                            Slog.w(TAG, "Removing dangling preferred activity: "
5020                                    + pa.mPref.mComponent);
5021                            pir.removeFilter(pa);
5022                            changed = true;
5023                            continue;
5024                        }
5025                        for (int j=0; j<N; j++) {
5026                            final ResolveInfo ri = query.get(j);
5027                            if (!ri.activityInfo.applicationInfo.packageName
5028                                    .equals(ai.applicationInfo.packageName)) {
5029                                continue;
5030                            }
5031                            if (!ri.activityInfo.name.equals(ai.name)) {
5032                                continue;
5033                            }
5034
5035                            if (removeMatches) {
5036                                pir.removeFilter(pa);
5037                                changed = true;
5038                                if (DEBUG_PREFERRED) {
5039                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5040                                }
5041                                break;
5042                            }
5043
5044                            // Okay we found a previously set preferred or last chosen app.
5045                            // If the result set is different from when this
5046                            // was created, we need to clear it and re-ask the
5047                            // user their preference, if we're looking for an "always" type entry.
5048                            if (always && !pa.mPref.sameSet(query)) {
5049                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5050                                        + intent + " type " + resolvedType);
5051                                if (DEBUG_PREFERRED) {
5052                                    Slog.v(TAG, "Removing preferred activity since set changed "
5053                                            + pa.mPref.mComponent);
5054                                }
5055                                pir.removeFilter(pa);
5056                                // Re-add the filter as a "last chosen" entry (!always)
5057                                PreferredActivity lastChosen = new PreferredActivity(
5058                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5059                                pir.addFilter(lastChosen);
5060                                changed = true;
5061                                return null;
5062                            }
5063
5064                            // Yay! Either the set matched or we're looking for the last chosen
5065                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5066                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5067                            return ri;
5068                        }
5069                    }
5070                } finally {
5071                    if (changed) {
5072                        if (DEBUG_PREFERRED) {
5073                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5074                        }
5075                        scheduleWritePackageRestrictionsLocked(userId);
5076                    }
5077                }
5078            }
5079        }
5080        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5081        return null;
5082    }
5083
5084    /*
5085     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5086     */
5087    @Override
5088    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5089            int targetUserId) {
5090        mContext.enforceCallingOrSelfPermission(
5091                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5092        List<CrossProfileIntentFilter> matches =
5093                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5094        if (matches != null) {
5095            int size = matches.size();
5096            for (int i = 0; i < size; i++) {
5097                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5098            }
5099        }
5100        if (hasWebURI(intent)) {
5101            // cross-profile app linking works only towards the parent.
5102            final UserInfo parent = getProfileParent(sourceUserId);
5103            synchronized(mPackages) {
5104                int flags = updateFlagsForResolve(0, parent.id, intent);
5105                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5106                        intent, resolvedType, flags, sourceUserId, parent.id);
5107                return xpDomainInfo != null;
5108            }
5109        }
5110        return false;
5111    }
5112
5113    private UserInfo getProfileParent(int userId) {
5114        final long identity = Binder.clearCallingIdentity();
5115        try {
5116            return sUserManager.getProfileParent(userId);
5117        } finally {
5118            Binder.restoreCallingIdentity(identity);
5119        }
5120    }
5121
5122    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5123            String resolvedType, int userId) {
5124        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5125        if (resolver != null) {
5126            return resolver.queryIntent(intent, resolvedType, false, userId);
5127        }
5128        return null;
5129    }
5130
5131    @Override
5132    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5133            String resolvedType, int flags, int userId) {
5134        return new ParceledListSlice<>(
5135                queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5136    }
5137
5138    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5139            String resolvedType, int flags, int userId) {
5140        if (!sUserManager.exists(userId)) return Collections.emptyList();
5141        flags = updateFlagsForResolve(flags, userId, intent);
5142        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5143                false /* requireFullPermission */, false /* checkShell */,
5144                "query intent activities");
5145        ComponentName comp = intent.getComponent();
5146        if (comp == null) {
5147            if (intent.getSelector() != null) {
5148                intent = intent.getSelector();
5149                comp = intent.getComponent();
5150            }
5151        }
5152
5153        if (comp != null) {
5154            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5155            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5156            if (ai != null) {
5157                final ResolveInfo ri = new ResolveInfo();
5158                ri.activityInfo = ai;
5159                list.add(ri);
5160            }
5161            return list;
5162        }
5163
5164        // reader
5165        synchronized (mPackages) {
5166            final String pkgName = intent.getPackage();
5167            if (pkgName == null) {
5168                List<CrossProfileIntentFilter> matchingFilters =
5169                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5170                // Check for results that need to skip the current profile.
5171                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5172                        resolvedType, flags, userId);
5173                if (xpResolveInfo != null) {
5174                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5175                    result.add(xpResolveInfo);
5176                    return filterIfNotSystemUser(result, userId);
5177                }
5178
5179                // Check for results in the current profile.
5180                List<ResolveInfo> result = mActivities.queryIntent(
5181                        intent, resolvedType, flags, userId);
5182                result = filterIfNotSystemUser(result, userId);
5183
5184                // Check for cross profile results.
5185                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5186                xpResolveInfo = queryCrossProfileIntents(
5187                        matchingFilters, intent, resolvedType, flags, userId,
5188                        hasNonNegativePriorityResult);
5189                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5190                    boolean isVisibleToUser = filterIfNotSystemUser(
5191                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5192                    if (isVisibleToUser) {
5193                        result.add(xpResolveInfo);
5194                        Collections.sort(result, mResolvePrioritySorter);
5195                    }
5196                }
5197                if (hasWebURI(intent)) {
5198                    CrossProfileDomainInfo xpDomainInfo = null;
5199                    final UserInfo parent = getProfileParent(userId);
5200                    if (parent != null) {
5201                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5202                                flags, userId, parent.id);
5203                    }
5204                    if (xpDomainInfo != null) {
5205                        if (xpResolveInfo != null) {
5206                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5207                            // in the result.
5208                            result.remove(xpResolveInfo);
5209                        }
5210                        if (result.size() == 0) {
5211                            result.add(xpDomainInfo.resolveInfo);
5212                            return result;
5213                        }
5214                    } else if (result.size() <= 1) {
5215                        return result;
5216                    }
5217                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5218                            xpDomainInfo, userId);
5219                    Collections.sort(result, mResolvePrioritySorter);
5220                }
5221                return result;
5222            }
5223            final PackageParser.Package pkg = mPackages.get(pkgName);
5224            if (pkg != null) {
5225                return filterIfNotSystemUser(
5226                        mActivities.queryIntentForPackage(
5227                                intent, resolvedType, flags, pkg.activities, userId),
5228                        userId);
5229            }
5230            return new ArrayList<ResolveInfo>();
5231        }
5232    }
5233
5234    private static class CrossProfileDomainInfo {
5235        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5236        ResolveInfo resolveInfo;
5237        /* Best domain verification status of the activities found in the other profile */
5238        int bestDomainVerificationStatus;
5239    }
5240
5241    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5242            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5243        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5244                sourceUserId)) {
5245            return null;
5246        }
5247        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5248                resolvedType, flags, parentUserId);
5249
5250        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5251            return null;
5252        }
5253        CrossProfileDomainInfo result = null;
5254        int size = resultTargetUser.size();
5255        for (int i = 0; i < size; i++) {
5256            ResolveInfo riTargetUser = resultTargetUser.get(i);
5257            // Intent filter verification is only for filters that specify a host. So don't return
5258            // those that handle all web uris.
5259            if (riTargetUser.handleAllWebDataURI) {
5260                continue;
5261            }
5262            String packageName = riTargetUser.activityInfo.packageName;
5263            PackageSetting ps = mSettings.mPackages.get(packageName);
5264            if (ps == null) {
5265                continue;
5266            }
5267            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5268            int status = (int)(verificationState >> 32);
5269            if (result == null) {
5270                result = new CrossProfileDomainInfo();
5271                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5272                        sourceUserId, parentUserId);
5273                result.bestDomainVerificationStatus = status;
5274            } else {
5275                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5276                        result.bestDomainVerificationStatus);
5277            }
5278        }
5279        // Don't consider matches with status NEVER across profiles.
5280        if (result != null && result.bestDomainVerificationStatus
5281                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5282            return null;
5283        }
5284        return result;
5285    }
5286
5287    /**
5288     * Verification statuses are ordered from the worse to the best, except for
5289     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5290     */
5291    private int bestDomainVerificationStatus(int status1, int status2) {
5292        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5293            return status2;
5294        }
5295        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5296            return status1;
5297        }
5298        return (int) MathUtils.max(status1, status2);
5299    }
5300
5301    private boolean isUserEnabled(int userId) {
5302        long callingId = Binder.clearCallingIdentity();
5303        try {
5304            UserInfo userInfo = sUserManager.getUserInfo(userId);
5305            return userInfo != null && userInfo.isEnabled();
5306        } finally {
5307            Binder.restoreCallingIdentity(callingId);
5308        }
5309    }
5310
5311    /**
5312     * Filter out activities with systemUserOnly flag set, when current user is not System.
5313     *
5314     * @return filtered list
5315     */
5316    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5317        if (userId == UserHandle.USER_SYSTEM) {
5318            return resolveInfos;
5319        }
5320        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5321            ResolveInfo info = resolveInfos.get(i);
5322            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5323                resolveInfos.remove(i);
5324            }
5325        }
5326        return resolveInfos;
5327    }
5328
5329    /**
5330     * @param resolveInfos list of resolve infos in descending priority order
5331     * @return if the list contains a resolve info with non-negative priority
5332     */
5333    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5334        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5335    }
5336
5337    private static boolean hasWebURI(Intent intent) {
5338        if (intent.getData() == null) {
5339            return false;
5340        }
5341        final String scheme = intent.getScheme();
5342        if (TextUtils.isEmpty(scheme)) {
5343            return false;
5344        }
5345        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5346    }
5347
5348    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5349            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5350            int userId) {
5351        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5352
5353        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5354            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5355                    candidates.size());
5356        }
5357
5358        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5359        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5360        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5361        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5362        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5363        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5364
5365        synchronized (mPackages) {
5366            final int count = candidates.size();
5367            // First, try to use linked apps. Partition the candidates into four lists:
5368            // one for the final results, one for the "do not use ever", one for "undefined status"
5369            // and finally one for "browser app type".
5370            for (int n=0; n<count; n++) {
5371                ResolveInfo info = candidates.get(n);
5372                String packageName = info.activityInfo.packageName;
5373                PackageSetting ps = mSettings.mPackages.get(packageName);
5374                if (ps != null) {
5375                    // Add to the special match all list (Browser use case)
5376                    if (info.handleAllWebDataURI) {
5377                        matchAllList.add(info);
5378                        continue;
5379                    }
5380                    // Try to get the status from User settings first
5381                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5382                    int status = (int)(packedStatus >> 32);
5383                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5384                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5385                        if (DEBUG_DOMAIN_VERIFICATION) {
5386                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5387                                    + " : linkgen=" + linkGeneration);
5388                        }
5389                        // Use link-enabled generation as preferredOrder, i.e.
5390                        // prefer newly-enabled over earlier-enabled.
5391                        info.preferredOrder = linkGeneration;
5392                        alwaysList.add(info);
5393                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5394                        if (DEBUG_DOMAIN_VERIFICATION) {
5395                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5396                        }
5397                        neverList.add(info);
5398                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5399                        if (DEBUG_DOMAIN_VERIFICATION) {
5400                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5401                        }
5402                        alwaysAskList.add(info);
5403                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5404                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5405                        if (DEBUG_DOMAIN_VERIFICATION) {
5406                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5407                        }
5408                        undefinedList.add(info);
5409                    }
5410                }
5411            }
5412
5413            // We'll want to include browser possibilities in a few cases
5414            boolean includeBrowser = false;
5415
5416            // First try to add the "always" resolution(s) for the current user, if any
5417            if (alwaysList.size() > 0) {
5418                result.addAll(alwaysList);
5419            } else {
5420                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5421                result.addAll(undefinedList);
5422                // Maybe add one for the other profile.
5423                if (xpDomainInfo != null && (
5424                        xpDomainInfo.bestDomainVerificationStatus
5425                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5426                    result.add(xpDomainInfo.resolveInfo);
5427                }
5428                includeBrowser = true;
5429            }
5430
5431            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5432            // If there were 'always' entries their preferred order has been set, so we also
5433            // back that off to make the alternatives equivalent
5434            if (alwaysAskList.size() > 0) {
5435                for (ResolveInfo i : result) {
5436                    i.preferredOrder = 0;
5437                }
5438                result.addAll(alwaysAskList);
5439                includeBrowser = true;
5440            }
5441
5442            if (includeBrowser) {
5443                // Also add browsers (all of them or only the default one)
5444                if (DEBUG_DOMAIN_VERIFICATION) {
5445                    Slog.v(TAG, "   ...including browsers in candidate set");
5446                }
5447                if ((matchFlags & MATCH_ALL) != 0) {
5448                    result.addAll(matchAllList);
5449                } else {
5450                    // Browser/generic handling case.  If there's a default browser, go straight
5451                    // to that (but only if there is no other higher-priority match).
5452                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5453                    int maxMatchPrio = 0;
5454                    ResolveInfo defaultBrowserMatch = null;
5455                    final int numCandidates = matchAllList.size();
5456                    for (int n = 0; n < numCandidates; n++) {
5457                        ResolveInfo info = matchAllList.get(n);
5458                        // track the highest overall match priority...
5459                        if (info.priority > maxMatchPrio) {
5460                            maxMatchPrio = info.priority;
5461                        }
5462                        // ...and the highest-priority default browser match
5463                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5464                            if (defaultBrowserMatch == null
5465                                    || (defaultBrowserMatch.priority < info.priority)) {
5466                                if (debug) {
5467                                    Slog.v(TAG, "Considering default browser match " + info);
5468                                }
5469                                defaultBrowserMatch = info;
5470                            }
5471                        }
5472                    }
5473                    if (defaultBrowserMatch != null
5474                            && defaultBrowserMatch.priority >= maxMatchPrio
5475                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5476                    {
5477                        if (debug) {
5478                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5479                        }
5480                        result.add(defaultBrowserMatch);
5481                    } else {
5482                        result.addAll(matchAllList);
5483                    }
5484                }
5485
5486                // If there is nothing selected, add all candidates and remove the ones that the user
5487                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5488                if (result.size() == 0) {
5489                    result.addAll(candidates);
5490                    result.removeAll(neverList);
5491                }
5492            }
5493        }
5494        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5495            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5496                    result.size());
5497            for (ResolveInfo info : result) {
5498                Slog.v(TAG, "  + " + info.activityInfo);
5499            }
5500        }
5501        return result;
5502    }
5503
5504    // Returns a packed value as a long:
5505    //
5506    // high 'int'-sized word: link status: undefined/ask/never/always.
5507    // low 'int'-sized word: relative priority among 'always' results.
5508    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5509        long result = ps.getDomainVerificationStatusForUser(userId);
5510        // if none available, get the master status
5511        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5512            if (ps.getIntentFilterVerificationInfo() != null) {
5513                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5514            }
5515        }
5516        return result;
5517    }
5518
5519    private ResolveInfo querySkipCurrentProfileIntents(
5520            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5521            int flags, int sourceUserId) {
5522        if (matchingFilters != null) {
5523            int size = matchingFilters.size();
5524            for (int i = 0; i < size; i ++) {
5525                CrossProfileIntentFilter filter = matchingFilters.get(i);
5526                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5527                    // Checking if there are activities in the target user that can handle the
5528                    // intent.
5529                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5530                            resolvedType, flags, sourceUserId);
5531                    if (resolveInfo != null) {
5532                        return resolveInfo;
5533                    }
5534                }
5535            }
5536        }
5537        return null;
5538    }
5539
5540    // Return matching ResolveInfo in target user if any.
5541    private ResolveInfo queryCrossProfileIntents(
5542            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5543            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5544        if (matchingFilters != null) {
5545            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5546            // match the same intent. For performance reasons, it is better not to
5547            // run queryIntent twice for the same userId
5548            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5549            int size = matchingFilters.size();
5550            for (int i = 0; i < size; i++) {
5551                CrossProfileIntentFilter filter = matchingFilters.get(i);
5552                int targetUserId = filter.getTargetUserId();
5553                boolean skipCurrentProfile =
5554                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5555                boolean skipCurrentProfileIfNoMatchFound =
5556                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5557                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5558                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5559                    // Checking if there are activities in the target user that can handle the
5560                    // intent.
5561                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5562                            resolvedType, flags, sourceUserId);
5563                    if (resolveInfo != null) return resolveInfo;
5564                    alreadyTriedUserIds.put(targetUserId, true);
5565                }
5566            }
5567        }
5568        return null;
5569    }
5570
5571    /**
5572     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5573     * will forward the intent to the filter's target user.
5574     * Otherwise, returns null.
5575     */
5576    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5577            String resolvedType, int flags, int sourceUserId) {
5578        int targetUserId = filter.getTargetUserId();
5579        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5580                resolvedType, flags, targetUserId);
5581        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5582            // If all the matches in the target profile are suspended, return null.
5583            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5584                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5585                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5586                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5587                            targetUserId);
5588                }
5589            }
5590        }
5591        return null;
5592    }
5593
5594    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5595            int sourceUserId, int targetUserId) {
5596        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5597        long ident = Binder.clearCallingIdentity();
5598        boolean targetIsProfile;
5599        try {
5600            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5601        } finally {
5602            Binder.restoreCallingIdentity(ident);
5603        }
5604        String className;
5605        if (targetIsProfile) {
5606            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5607        } else {
5608            className = FORWARD_INTENT_TO_PARENT;
5609        }
5610        ComponentName forwardingActivityComponentName = new ComponentName(
5611                mAndroidApplication.packageName, className);
5612        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5613                sourceUserId);
5614        if (!targetIsProfile) {
5615            forwardingActivityInfo.showUserIcon = targetUserId;
5616            forwardingResolveInfo.noResourceId = true;
5617        }
5618        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5619        forwardingResolveInfo.priority = 0;
5620        forwardingResolveInfo.preferredOrder = 0;
5621        forwardingResolveInfo.match = 0;
5622        forwardingResolveInfo.isDefault = true;
5623        forwardingResolveInfo.filter = filter;
5624        forwardingResolveInfo.targetUserId = targetUserId;
5625        return forwardingResolveInfo;
5626    }
5627
5628    @Override
5629    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5630            Intent[] specifics, String[] specificTypes, Intent intent,
5631            String resolvedType, int flags, int userId) {
5632        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5633                specificTypes, intent, resolvedType, flags, userId));
5634    }
5635
5636    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5637            Intent[] specifics, String[] specificTypes, Intent intent,
5638            String resolvedType, int flags, int userId) {
5639        if (!sUserManager.exists(userId)) return Collections.emptyList();
5640        flags = updateFlagsForResolve(flags, userId, intent);
5641        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5642                false /* requireFullPermission */, false /* checkShell */,
5643                "query intent activity options");
5644        final String resultsAction = intent.getAction();
5645
5646        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5647                | PackageManager.GET_RESOLVED_FILTER, userId);
5648
5649        if (DEBUG_INTENT_MATCHING) {
5650            Log.v(TAG, "Query " + intent + ": " + results);
5651        }
5652
5653        int specificsPos = 0;
5654        int N;
5655
5656        // todo: note that the algorithm used here is O(N^2).  This
5657        // isn't a problem in our current environment, but if we start running
5658        // into situations where we have more than 5 or 10 matches then this
5659        // should probably be changed to something smarter...
5660
5661        // First we go through and resolve each of the specific items
5662        // that were supplied, taking care of removing any corresponding
5663        // duplicate items in the generic resolve list.
5664        if (specifics != null) {
5665            for (int i=0; i<specifics.length; i++) {
5666                final Intent sintent = specifics[i];
5667                if (sintent == null) {
5668                    continue;
5669                }
5670
5671                if (DEBUG_INTENT_MATCHING) {
5672                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5673                }
5674
5675                String action = sintent.getAction();
5676                if (resultsAction != null && resultsAction.equals(action)) {
5677                    // If this action was explicitly requested, then don't
5678                    // remove things that have it.
5679                    action = null;
5680                }
5681
5682                ResolveInfo ri = null;
5683                ActivityInfo ai = null;
5684
5685                ComponentName comp = sintent.getComponent();
5686                if (comp == null) {
5687                    ri = resolveIntent(
5688                        sintent,
5689                        specificTypes != null ? specificTypes[i] : null,
5690                            flags, userId);
5691                    if (ri == null) {
5692                        continue;
5693                    }
5694                    if (ri == mResolveInfo) {
5695                        // ACK!  Must do something better with this.
5696                    }
5697                    ai = ri.activityInfo;
5698                    comp = new ComponentName(ai.applicationInfo.packageName,
5699                            ai.name);
5700                } else {
5701                    ai = getActivityInfo(comp, flags, userId);
5702                    if (ai == null) {
5703                        continue;
5704                    }
5705                }
5706
5707                // Look for any generic query activities that are duplicates
5708                // of this specific one, and remove them from the results.
5709                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5710                N = results.size();
5711                int j;
5712                for (j=specificsPos; j<N; j++) {
5713                    ResolveInfo sri = results.get(j);
5714                    if ((sri.activityInfo.name.equals(comp.getClassName())
5715                            && sri.activityInfo.applicationInfo.packageName.equals(
5716                                    comp.getPackageName()))
5717                        || (action != null && sri.filter.matchAction(action))) {
5718                        results.remove(j);
5719                        if (DEBUG_INTENT_MATCHING) Log.v(
5720                            TAG, "Removing duplicate item from " + j
5721                            + " due to specific " + specificsPos);
5722                        if (ri == null) {
5723                            ri = sri;
5724                        }
5725                        j--;
5726                        N--;
5727                    }
5728                }
5729
5730                // Add this specific item to its proper place.
5731                if (ri == null) {
5732                    ri = new ResolveInfo();
5733                    ri.activityInfo = ai;
5734                }
5735                results.add(specificsPos, ri);
5736                ri.specificIndex = i;
5737                specificsPos++;
5738            }
5739        }
5740
5741        // Now we go through the remaining generic results and remove any
5742        // duplicate actions that are found here.
5743        N = results.size();
5744        for (int i=specificsPos; i<N-1; i++) {
5745            final ResolveInfo rii = results.get(i);
5746            if (rii.filter == null) {
5747                continue;
5748            }
5749
5750            // Iterate over all of the actions of this result's intent
5751            // filter...  typically this should be just one.
5752            final Iterator<String> it = rii.filter.actionsIterator();
5753            if (it == null) {
5754                continue;
5755            }
5756            while (it.hasNext()) {
5757                final String action = it.next();
5758                if (resultsAction != null && resultsAction.equals(action)) {
5759                    // If this action was explicitly requested, then don't
5760                    // remove things that have it.
5761                    continue;
5762                }
5763                for (int j=i+1; j<N; j++) {
5764                    final ResolveInfo rij = results.get(j);
5765                    if (rij.filter != null && rij.filter.hasAction(action)) {
5766                        results.remove(j);
5767                        if (DEBUG_INTENT_MATCHING) Log.v(
5768                            TAG, "Removing duplicate item from " + j
5769                            + " due to action " + action + " at " + i);
5770                        j--;
5771                        N--;
5772                    }
5773                }
5774            }
5775
5776            // If the caller didn't request filter information, drop it now
5777            // so we don't have to marshall/unmarshall it.
5778            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5779                rii.filter = null;
5780            }
5781        }
5782
5783        // Filter out the caller activity if so requested.
5784        if (caller != null) {
5785            N = results.size();
5786            for (int i=0; i<N; i++) {
5787                ActivityInfo ainfo = results.get(i).activityInfo;
5788                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5789                        && caller.getClassName().equals(ainfo.name)) {
5790                    results.remove(i);
5791                    break;
5792                }
5793            }
5794        }
5795
5796        // If the caller didn't request filter information,
5797        // drop them now so we don't have to
5798        // marshall/unmarshall it.
5799        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5800            N = results.size();
5801            for (int i=0; i<N; i++) {
5802                results.get(i).filter = null;
5803            }
5804        }
5805
5806        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5807        return results;
5808    }
5809
5810    @Override
5811    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5812            String resolvedType, int flags, int userId) {
5813        return new ParceledListSlice<>(
5814                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5815    }
5816
5817    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5818            String resolvedType, int flags, int userId) {
5819        if (!sUserManager.exists(userId)) return Collections.emptyList();
5820        flags = updateFlagsForResolve(flags, userId, intent);
5821        ComponentName comp = intent.getComponent();
5822        if (comp == null) {
5823            if (intent.getSelector() != null) {
5824                intent = intent.getSelector();
5825                comp = intent.getComponent();
5826            }
5827        }
5828        if (comp != null) {
5829            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5830            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5831            if (ai != null) {
5832                ResolveInfo ri = new ResolveInfo();
5833                ri.activityInfo = ai;
5834                list.add(ri);
5835            }
5836            return list;
5837        }
5838
5839        // reader
5840        synchronized (mPackages) {
5841            String pkgName = intent.getPackage();
5842            if (pkgName == null) {
5843                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5844            }
5845            final PackageParser.Package pkg = mPackages.get(pkgName);
5846            if (pkg != null) {
5847                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5848                        userId);
5849            }
5850            return Collections.emptyList();
5851        }
5852    }
5853
5854    @Override
5855    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5856        if (!sUserManager.exists(userId)) return null;
5857        flags = updateFlagsForResolve(flags, userId, intent);
5858        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
5859        if (query != null) {
5860            if (query.size() >= 1) {
5861                // If there is more than one service with the same priority,
5862                // just arbitrarily pick the first one.
5863                return query.get(0);
5864            }
5865        }
5866        return null;
5867    }
5868
5869    @Override
5870    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
5871            String resolvedType, int flags, int userId) {
5872        return new ParceledListSlice<>(
5873                queryIntentServicesInternal(intent, resolvedType, flags, userId));
5874    }
5875
5876    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
5877            String resolvedType, int flags, int userId) {
5878        if (!sUserManager.exists(userId)) return Collections.emptyList();
5879        flags = updateFlagsForResolve(flags, userId, intent);
5880        ComponentName comp = intent.getComponent();
5881        if (comp == null) {
5882            if (intent.getSelector() != null) {
5883                intent = intent.getSelector();
5884                comp = intent.getComponent();
5885            }
5886        }
5887        if (comp != null) {
5888            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5889            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5890            if (si != null) {
5891                final ResolveInfo ri = new ResolveInfo();
5892                ri.serviceInfo = si;
5893                list.add(ri);
5894            }
5895            return list;
5896        }
5897
5898        // reader
5899        synchronized (mPackages) {
5900            String pkgName = intent.getPackage();
5901            if (pkgName == null) {
5902                return mServices.queryIntent(intent, resolvedType, flags, userId);
5903            }
5904            final PackageParser.Package pkg = mPackages.get(pkgName);
5905            if (pkg != null) {
5906                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5907                        userId);
5908            }
5909            return Collections.emptyList();
5910        }
5911    }
5912
5913    @Override
5914    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
5915            String resolvedType, int flags, int userId) {
5916        return new ParceledListSlice<>(
5917                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
5918    }
5919
5920    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
5921            Intent intent, String resolvedType, int flags, int userId) {
5922        if (!sUserManager.exists(userId)) return Collections.emptyList();
5923        flags = updateFlagsForResolve(flags, userId, intent);
5924        ComponentName comp = intent.getComponent();
5925        if (comp == null) {
5926            if (intent.getSelector() != null) {
5927                intent = intent.getSelector();
5928                comp = intent.getComponent();
5929            }
5930        }
5931        if (comp != null) {
5932            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5933            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5934            if (pi != null) {
5935                final ResolveInfo ri = new ResolveInfo();
5936                ri.providerInfo = pi;
5937                list.add(ri);
5938            }
5939            return list;
5940        }
5941
5942        // reader
5943        synchronized (mPackages) {
5944            String pkgName = intent.getPackage();
5945            if (pkgName == null) {
5946                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5947            }
5948            final PackageParser.Package pkg = mPackages.get(pkgName);
5949            if (pkg != null) {
5950                return mProviders.queryIntentForPackage(
5951                        intent, resolvedType, flags, pkg.providers, userId);
5952            }
5953            return Collections.emptyList();
5954        }
5955    }
5956
5957    @Override
5958    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5959        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5960        flags = updateFlagsForPackage(flags, userId, null);
5961        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5962        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5963                true /* requireFullPermission */, false /* checkShell */,
5964                "get installed packages");
5965
5966        // writer
5967        synchronized (mPackages) {
5968            ArrayList<PackageInfo> list;
5969            if (listUninstalled) {
5970                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5971                for (PackageSetting ps : mSettings.mPackages.values()) {
5972                    final PackageInfo pi;
5973                    if (ps.pkg != null) {
5974                        pi = generatePackageInfo(ps, flags, userId);
5975                    } else {
5976                        pi = generatePackageInfo(ps, flags, userId);
5977                    }
5978                    if (pi != null) {
5979                        list.add(pi);
5980                    }
5981                }
5982            } else {
5983                list = new ArrayList<PackageInfo>(mPackages.size());
5984                for (PackageParser.Package p : mPackages.values()) {
5985                    final PackageInfo pi =
5986                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
5987                    if (pi != null) {
5988                        list.add(pi);
5989                    }
5990                }
5991            }
5992
5993            return new ParceledListSlice<PackageInfo>(list);
5994        }
5995    }
5996
5997    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5998            String[] permissions, boolean[] tmp, int flags, int userId) {
5999        int numMatch = 0;
6000        final PermissionsState permissionsState = ps.getPermissionsState();
6001        for (int i=0; i<permissions.length; i++) {
6002            final String permission = permissions[i];
6003            if (permissionsState.hasPermission(permission, userId)) {
6004                tmp[i] = true;
6005                numMatch++;
6006            } else {
6007                tmp[i] = false;
6008            }
6009        }
6010        if (numMatch == 0) {
6011            return;
6012        }
6013        final PackageInfo pi;
6014        if (ps.pkg != null) {
6015            pi = generatePackageInfo(ps, flags, userId);
6016        } else {
6017            pi = generatePackageInfo(ps, flags, userId);
6018        }
6019        // The above might return null in cases of uninstalled apps or install-state
6020        // skew across users/profiles.
6021        if (pi != null) {
6022            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6023                if (numMatch == permissions.length) {
6024                    pi.requestedPermissions = permissions;
6025                } else {
6026                    pi.requestedPermissions = new String[numMatch];
6027                    numMatch = 0;
6028                    for (int i=0; i<permissions.length; i++) {
6029                        if (tmp[i]) {
6030                            pi.requestedPermissions[numMatch] = permissions[i];
6031                            numMatch++;
6032                        }
6033                    }
6034                }
6035            }
6036            list.add(pi);
6037        }
6038    }
6039
6040    @Override
6041    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6042            String[] permissions, int flags, int userId) {
6043        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6044        flags = updateFlagsForPackage(flags, userId, permissions);
6045        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6046
6047        // writer
6048        synchronized (mPackages) {
6049            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6050            boolean[] tmpBools = new boolean[permissions.length];
6051            if (listUninstalled) {
6052                for (PackageSetting ps : mSettings.mPackages.values()) {
6053                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6054                }
6055            } else {
6056                for (PackageParser.Package pkg : mPackages.values()) {
6057                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6058                    if (ps != null) {
6059                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6060                                userId);
6061                    }
6062                }
6063            }
6064
6065            return new ParceledListSlice<PackageInfo>(list);
6066        }
6067    }
6068
6069    @Override
6070    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6071        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6072        flags = updateFlagsForApplication(flags, userId, null);
6073        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6074
6075        // writer
6076        synchronized (mPackages) {
6077            ArrayList<ApplicationInfo> list;
6078            if (listUninstalled) {
6079                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6080                for (PackageSetting ps : mSettings.mPackages.values()) {
6081                    ApplicationInfo ai;
6082                    if (ps.pkg != null) {
6083                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6084                                ps.readUserState(userId), userId);
6085                    } else {
6086                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6087                    }
6088                    if (ai != null) {
6089                        list.add(ai);
6090                    }
6091                }
6092            } else {
6093                list = new ArrayList<ApplicationInfo>(mPackages.size());
6094                for (PackageParser.Package p : mPackages.values()) {
6095                    if (p.mExtras != null) {
6096                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6097                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6098                        if (ai != null) {
6099                            list.add(ai);
6100                        }
6101                    }
6102                }
6103            }
6104
6105            return new ParceledListSlice<ApplicationInfo>(list);
6106        }
6107    }
6108
6109    @Override
6110    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6111        if (DISABLE_EPHEMERAL_APPS) {
6112            return null;
6113        }
6114
6115        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6116                "getEphemeralApplications");
6117        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6118                true /* requireFullPermission */, false /* checkShell */,
6119                "getEphemeralApplications");
6120        synchronized (mPackages) {
6121            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6122                    .getEphemeralApplicationsLPw(userId);
6123            if (ephemeralApps != null) {
6124                return new ParceledListSlice<>(ephemeralApps);
6125            }
6126        }
6127        return null;
6128    }
6129
6130    @Override
6131    public boolean isEphemeralApplication(String packageName, int userId) {
6132        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6133                true /* requireFullPermission */, false /* checkShell */,
6134                "isEphemeral");
6135        if (DISABLE_EPHEMERAL_APPS) {
6136            return false;
6137        }
6138
6139        if (!isCallerSameApp(packageName)) {
6140            return false;
6141        }
6142        synchronized (mPackages) {
6143            PackageParser.Package pkg = mPackages.get(packageName);
6144            if (pkg != null) {
6145                return pkg.applicationInfo.isEphemeralApp();
6146            }
6147        }
6148        return false;
6149    }
6150
6151    @Override
6152    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6153        if (DISABLE_EPHEMERAL_APPS) {
6154            return null;
6155        }
6156
6157        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6158                true /* requireFullPermission */, false /* checkShell */,
6159                "getCookie");
6160        if (!isCallerSameApp(packageName)) {
6161            return null;
6162        }
6163        synchronized (mPackages) {
6164            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6165                    packageName, userId);
6166        }
6167    }
6168
6169    @Override
6170    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6171        if (DISABLE_EPHEMERAL_APPS) {
6172            return true;
6173        }
6174
6175        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6176                true /* requireFullPermission */, true /* checkShell */,
6177                "setCookie");
6178        if (!isCallerSameApp(packageName)) {
6179            return false;
6180        }
6181        synchronized (mPackages) {
6182            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6183                    packageName, cookie, userId);
6184        }
6185    }
6186
6187    @Override
6188    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6189        if (DISABLE_EPHEMERAL_APPS) {
6190            return null;
6191        }
6192
6193        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6194                "getEphemeralApplicationIcon");
6195        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6196                true /* requireFullPermission */, false /* checkShell */,
6197                "getEphemeralApplicationIcon");
6198        synchronized (mPackages) {
6199            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6200                    packageName, userId);
6201        }
6202    }
6203
6204    private boolean isCallerSameApp(String packageName) {
6205        PackageParser.Package pkg = mPackages.get(packageName);
6206        return pkg != null
6207                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6208    }
6209
6210    @Override
6211    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6212        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6213    }
6214
6215    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6216        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6217
6218        // reader
6219        synchronized (mPackages) {
6220            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6221            final int userId = UserHandle.getCallingUserId();
6222            while (i.hasNext()) {
6223                final PackageParser.Package p = i.next();
6224                if (p.applicationInfo == null) continue;
6225
6226                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6227                        && !p.applicationInfo.isDirectBootAware();
6228                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6229                        && p.applicationInfo.isDirectBootAware();
6230
6231                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6232                        && (!mSafeMode || isSystemApp(p))
6233                        && (matchesUnaware || matchesAware)) {
6234                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6235                    if (ps != null) {
6236                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6237                                ps.readUserState(userId), userId);
6238                        if (ai != null) {
6239                            finalList.add(ai);
6240                        }
6241                    }
6242                }
6243            }
6244        }
6245
6246        return finalList;
6247    }
6248
6249    @Override
6250    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6251        if (!sUserManager.exists(userId)) return null;
6252        flags = updateFlagsForComponent(flags, userId, name);
6253        // reader
6254        synchronized (mPackages) {
6255            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6256            PackageSetting ps = provider != null
6257                    ? mSettings.mPackages.get(provider.owner.packageName)
6258                    : null;
6259            return ps != null
6260                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6261                    ? PackageParser.generateProviderInfo(provider, flags,
6262                            ps.readUserState(userId), userId)
6263                    : null;
6264        }
6265    }
6266
6267    /**
6268     * @deprecated
6269     */
6270    @Deprecated
6271    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6272        // reader
6273        synchronized (mPackages) {
6274            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6275                    .entrySet().iterator();
6276            final int userId = UserHandle.getCallingUserId();
6277            while (i.hasNext()) {
6278                Map.Entry<String, PackageParser.Provider> entry = i.next();
6279                PackageParser.Provider p = entry.getValue();
6280                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6281
6282                if (ps != null && p.syncable
6283                        && (!mSafeMode || (p.info.applicationInfo.flags
6284                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6285                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6286                            ps.readUserState(userId), userId);
6287                    if (info != null) {
6288                        outNames.add(entry.getKey());
6289                        outInfo.add(info);
6290                    }
6291                }
6292            }
6293        }
6294    }
6295
6296    @Override
6297    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6298            int uid, int flags) {
6299        final int userId = processName != null ? UserHandle.getUserId(uid)
6300                : UserHandle.getCallingUserId();
6301        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6302        flags = updateFlagsForComponent(flags, userId, processName);
6303
6304        ArrayList<ProviderInfo> finalList = null;
6305        // reader
6306        synchronized (mPackages) {
6307            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6308            while (i.hasNext()) {
6309                final PackageParser.Provider p = i.next();
6310                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6311                if (ps != null && p.info.authority != null
6312                        && (processName == null
6313                                || (p.info.processName.equals(processName)
6314                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6315                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6316                    if (finalList == null) {
6317                        finalList = new ArrayList<ProviderInfo>(3);
6318                    }
6319                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6320                            ps.readUserState(userId), userId);
6321                    if (info != null) {
6322                        finalList.add(info);
6323                    }
6324                }
6325            }
6326        }
6327
6328        if (finalList != null) {
6329            Collections.sort(finalList, mProviderInitOrderSorter);
6330            return new ParceledListSlice<ProviderInfo>(finalList);
6331        }
6332
6333        return ParceledListSlice.emptyList();
6334    }
6335
6336    @Override
6337    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6338        // reader
6339        synchronized (mPackages) {
6340            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6341            return PackageParser.generateInstrumentationInfo(i, flags);
6342        }
6343    }
6344
6345    @Override
6346    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6347            String targetPackage, int flags) {
6348        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6349    }
6350
6351    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6352            int flags) {
6353        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6354
6355        // reader
6356        synchronized (mPackages) {
6357            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6358            while (i.hasNext()) {
6359                final PackageParser.Instrumentation p = i.next();
6360                if (targetPackage == null
6361                        || targetPackage.equals(p.info.targetPackage)) {
6362                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6363                            flags);
6364                    if (ii != null) {
6365                        finalList.add(ii);
6366                    }
6367                }
6368            }
6369        }
6370
6371        return finalList;
6372    }
6373
6374    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6375        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6376        if (overlays == null) {
6377            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6378            return;
6379        }
6380        for (PackageParser.Package opkg : overlays.values()) {
6381            // Not much to do if idmap fails: we already logged the error
6382            // and we certainly don't want to abort installation of pkg simply
6383            // because an overlay didn't fit properly. For these reasons,
6384            // ignore the return value of createIdmapForPackagePairLI.
6385            createIdmapForPackagePairLI(pkg, opkg);
6386        }
6387    }
6388
6389    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6390            PackageParser.Package opkg) {
6391        if (!opkg.mTrustedOverlay) {
6392            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6393                    opkg.baseCodePath + ": overlay not trusted");
6394            return false;
6395        }
6396        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6397        if (overlaySet == null) {
6398            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6399                    opkg.baseCodePath + " but target package has no known overlays");
6400            return false;
6401        }
6402        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6403        // TODO: generate idmap for split APKs
6404        try {
6405            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6406        } catch (InstallerException e) {
6407            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6408                    + opkg.baseCodePath);
6409            return false;
6410        }
6411        PackageParser.Package[] overlayArray =
6412            overlaySet.values().toArray(new PackageParser.Package[0]);
6413        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6414            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6415                return p1.mOverlayPriority - p2.mOverlayPriority;
6416            }
6417        };
6418        Arrays.sort(overlayArray, cmp);
6419
6420        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6421        int i = 0;
6422        for (PackageParser.Package p : overlayArray) {
6423            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6424        }
6425        return true;
6426    }
6427
6428    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6429        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6430        try {
6431            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6432        } finally {
6433            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6434        }
6435    }
6436
6437    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6438        final File[] files = dir.listFiles();
6439        if (ArrayUtils.isEmpty(files)) {
6440            Log.d(TAG, "No files in app dir " + dir);
6441            return;
6442        }
6443
6444        if (DEBUG_PACKAGE_SCANNING) {
6445            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6446                    + " flags=0x" + Integer.toHexString(parseFlags));
6447        }
6448
6449        for (File file : files) {
6450            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6451                    && !PackageInstallerService.isStageName(file.getName());
6452            if (!isPackage) {
6453                // Ignore entries which are not packages
6454                continue;
6455            }
6456            try {
6457                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6458                        scanFlags, currentTime, null);
6459            } catch (PackageManagerException e) {
6460                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6461
6462                // Delete invalid userdata apps
6463                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6464                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6465                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6466                    removeCodePathLI(file);
6467                }
6468            }
6469        }
6470    }
6471
6472    private static File getSettingsProblemFile() {
6473        File dataDir = Environment.getDataDirectory();
6474        File systemDir = new File(dataDir, "system");
6475        File fname = new File(systemDir, "uiderrors.txt");
6476        return fname;
6477    }
6478
6479    static void reportSettingsProblem(int priority, String msg) {
6480        logCriticalInfo(priority, msg);
6481    }
6482
6483    static void logCriticalInfo(int priority, String msg) {
6484        Slog.println(priority, TAG, msg);
6485        EventLogTags.writePmCriticalInfo(msg);
6486        try {
6487            File fname = getSettingsProblemFile();
6488            FileOutputStream out = new FileOutputStream(fname, true);
6489            PrintWriter pw = new FastPrintWriter(out);
6490            SimpleDateFormat formatter = new SimpleDateFormat();
6491            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6492            pw.println(dateString + ": " + msg);
6493            pw.close();
6494            FileUtils.setPermissions(
6495                    fname.toString(),
6496                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6497                    -1, -1);
6498        } catch (java.io.IOException e) {
6499        }
6500    }
6501
6502    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6503            int parseFlags) throws PackageManagerException {
6504        if (ps != null
6505                && ps.codePath.equals(srcFile)
6506                && ps.timeStamp == srcFile.lastModified()
6507                && !isCompatSignatureUpdateNeeded(pkg)
6508                && !isRecoverSignatureUpdateNeeded(pkg)) {
6509            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6510            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6511            ArraySet<PublicKey> signingKs;
6512            synchronized (mPackages) {
6513                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6514            }
6515            if (ps.signatures.mSignatures != null
6516                    && ps.signatures.mSignatures.length != 0
6517                    && signingKs != null) {
6518                // Optimization: reuse the existing cached certificates
6519                // if the package appears to be unchanged.
6520                pkg.mSignatures = ps.signatures.mSignatures;
6521                pkg.mSigningKeys = signingKs;
6522                return;
6523            }
6524
6525            Slog.w(TAG, "PackageSetting for " + ps.name
6526                    + " is missing signatures.  Collecting certs again to recover them.");
6527        } else {
6528            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6529        }
6530
6531        try {
6532            PackageParser.collectCertificates(pkg, parseFlags);
6533        } catch (PackageParserException e) {
6534            throw PackageManagerException.from(e);
6535        }
6536    }
6537
6538    /**
6539     *  Traces a package scan.
6540     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6541     */
6542    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6543            long currentTime, UserHandle user) throws PackageManagerException {
6544        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6545        try {
6546            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6547        } finally {
6548            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6549        }
6550    }
6551
6552    /**
6553     *  Scans a package and returns the newly parsed package.
6554     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6555     */
6556    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6557            long currentTime, UserHandle user) throws PackageManagerException {
6558        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6559        parseFlags |= mDefParseFlags;
6560        PackageParser pp = new PackageParser();
6561        pp.setSeparateProcesses(mSeparateProcesses);
6562        pp.setOnlyCoreApps(mOnlyCore);
6563        pp.setDisplayMetrics(mMetrics);
6564
6565        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6566            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6567        }
6568
6569        final PackageParser.Package pkg;
6570        try {
6571            pkg = pp.parsePackage(scanFile, parseFlags);
6572        } catch (PackageParserException e) {
6573            throw PackageManagerException.from(e);
6574        }
6575
6576        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6577    }
6578
6579    /**
6580     *  Scans a package and returns the newly parsed package.
6581     *  @throws PackageManagerException on a parse error.
6582     */
6583    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6584            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6585            throws PackageManagerException {
6586        // If the package has children and this is the first dive in the function
6587        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6588        // packages (parent and children) would be successfully scanned before the
6589        // actual scan since scanning mutates internal state and we want to atomically
6590        // install the package and its children.
6591        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6592            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6593                scanFlags |= SCAN_CHECK_ONLY;
6594            }
6595        } else {
6596            scanFlags &= ~SCAN_CHECK_ONLY;
6597        }
6598
6599        // Scan the parent
6600        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags,
6601                scanFlags, currentTime, user);
6602
6603        // Scan the children
6604        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6605        for (int i = 0; i < childCount; i++) {
6606            PackageParser.Package childPackage = pkg.childPackages.get(i);
6607            scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags,
6608                    currentTime, user);
6609        }
6610
6611
6612        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6613            return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6614        }
6615
6616        return scannedPkg;
6617    }
6618
6619    /**
6620     *  Scans a package and returns the newly parsed package.
6621     *  @throws PackageManagerException on a parse error.
6622     */
6623    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6624            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6625            throws PackageManagerException {
6626        PackageSetting ps = null;
6627        PackageSetting updatedPkg;
6628        // reader
6629        synchronized (mPackages) {
6630            // Look to see if we already know about this package.
6631            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6632            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6633                // This package has been renamed to its original name.  Let's
6634                // use that.
6635                ps = mSettings.peekPackageLPr(oldName);
6636            }
6637            // If there was no original package, see one for the real package name.
6638            if (ps == null) {
6639                ps = mSettings.peekPackageLPr(pkg.packageName);
6640            }
6641            // Check to see if this package could be hiding/updating a system
6642            // package.  Must look for it either under the original or real
6643            // package name depending on our state.
6644            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6645            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6646
6647            // If this is a package we don't know about on the system partition, we
6648            // may need to remove disabled child packages on the system partition
6649            // or may need to not add child packages if the parent apk is updated
6650            // on the data partition and no longer defines this child package.
6651            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6652                // If this is a parent package for an updated system app and this system
6653                // app got an OTA update which no longer defines some of the child packages
6654                // we have to prune them from the disabled system packages.
6655                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6656                if (disabledPs != null) {
6657                    final int scannedChildCount = (pkg.childPackages != null)
6658                            ? pkg.childPackages.size() : 0;
6659                    final int disabledChildCount = disabledPs.childPackageNames != null
6660                            ? disabledPs.childPackageNames.size() : 0;
6661                    for (int i = 0; i < disabledChildCount; i++) {
6662                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6663                        boolean disabledPackageAvailable = false;
6664                        for (int j = 0; j < scannedChildCount; j++) {
6665                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6666                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6667                                disabledPackageAvailable = true;
6668                                break;
6669                            }
6670                         }
6671                         if (!disabledPackageAvailable) {
6672                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6673                         }
6674                    }
6675                }
6676            }
6677        }
6678
6679        boolean updatedPkgBetter = false;
6680        // First check if this is a system package that may involve an update
6681        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6682            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6683            // it needs to drop FLAG_PRIVILEGED.
6684            if (locationIsPrivileged(scanFile)) {
6685                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6686            } else {
6687                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6688            }
6689
6690            if (ps != null && !ps.codePath.equals(scanFile)) {
6691                // The path has changed from what was last scanned...  check the
6692                // version of the new path against what we have stored to determine
6693                // what to do.
6694                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6695                if (pkg.mVersionCode <= ps.versionCode) {
6696                    // The system package has been updated and the code path does not match
6697                    // Ignore entry. Skip it.
6698                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6699                            + " ignored: updated version " + ps.versionCode
6700                            + " better than this " + pkg.mVersionCode);
6701                    if (!updatedPkg.codePath.equals(scanFile)) {
6702                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6703                                + ps.name + " changing from " + updatedPkg.codePathString
6704                                + " to " + scanFile);
6705                        updatedPkg.codePath = scanFile;
6706                        updatedPkg.codePathString = scanFile.toString();
6707                        updatedPkg.resourcePath = scanFile;
6708                        updatedPkg.resourcePathString = scanFile.toString();
6709                    }
6710                    updatedPkg.pkg = pkg;
6711                    updatedPkg.versionCode = pkg.mVersionCode;
6712
6713                    // Update the disabled system child packages to point to the package too.
6714                    final int childCount = updatedPkg.childPackageNames != null
6715                            ? updatedPkg.childPackageNames.size() : 0;
6716                    for (int i = 0; i < childCount; i++) {
6717                        String childPackageName = updatedPkg.childPackageNames.get(i);
6718                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6719                                childPackageName);
6720                        if (updatedChildPkg != null) {
6721                            updatedChildPkg.pkg = pkg;
6722                            updatedChildPkg.versionCode = pkg.mVersionCode;
6723                        }
6724                    }
6725
6726                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6727                            + scanFile + " ignored: updated version " + ps.versionCode
6728                            + " better than this " + pkg.mVersionCode);
6729                } else {
6730                    // The current app on the system partition is better than
6731                    // what we have updated to on the data partition; switch
6732                    // back to the system partition version.
6733                    // At this point, its safely assumed that package installation for
6734                    // apps in system partition will go through. If not there won't be a working
6735                    // version of the app
6736                    // writer
6737                    synchronized (mPackages) {
6738                        // Just remove the loaded entries from package lists.
6739                        mPackages.remove(ps.name);
6740                    }
6741
6742                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6743                            + " reverting from " + ps.codePathString
6744                            + ": new version " + pkg.mVersionCode
6745                            + " better than installed " + ps.versionCode);
6746
6747                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6748                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6749                    synchronized (mInstallLock) {
6750                        args.cleanUpResourcesLI();
6751                    }
6752                    synchronized (mPackages) {
6753                        mSettings.enableSystemPackageLPw(ps.name);
6754                    }
6755                    updatedPkgBetter = true;
6756                }
6757            }
6758        }
6759
6760        if (updatedPkg != null) {
6761            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6762            // initially
6763            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6764
6765            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6766            // flag set initially
6767            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6768                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6769            }
6770        }
6771
6772        // Verify certificates against what was last scanned
6773        collectCertificatesLI(ps, pkg, scanFile, parseFlags);
6774
6775        /*
6776         * A new system app appeared, but we already had a non-system one of the
6777         * same name installed earlier.
6778         */
6779        boolean shouldHideSystemApp = false;
6780        if (updatedPkg == null && ps != null
6781                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6782            /*
6783             * Check to make sure the signatures match first. If they don't,
6784             * wipe the installed application and its data.
6785             */
6786            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6787                    != PackageManager.SIGNATURE_MATCH) {
6788                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6789                        + " signatures don't match existing userdata copy; removing");
6790                deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null);
6791                ps = null;
6792            } else {
6793                /*
6794                 * If the newly-added system app is an older version than the
6795                 * already installed version, hide it. It will be scanned later
6796                 * and re-added like an update.
6797                 */
6798                if (pkg.mVersionCode <= ps.versionCode) {
6799                    shouldHideSystemApp = true;
6800                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6801                            + " but new version " + pkg.mVersionCode + " better than installed "
6802                            + ps.versionCode + "; hiding system");
6803                } else {
6804                    /*
6805                     * The newly found system app is a newer version that the
6806                     * one previously installed. Simply remove the
6807                     * already-installed application and replace it with our own
6808                     * while keeping the application data.
6809                     */
6810                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6811                            + " reverting from " + ps.codePathString + ": new version "
6812                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6813                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6814                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6815                    synchronized (mInstallLock) {
6816                        args.cleanUpResourcesLI();
6817                    }
6818                }
6819            }
6820        }
6821
6822        // The apk is forward locked (not public) if its code and resources
6823        // are kept in different files. (except for app in either system or
6824        // vendor path).
6825        // TODO grab this value from PackageSettings
6826        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6827            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6828                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6829            }
6830        }
6831
6832        // TODO: extend to support forward-locked splits
6833        String resourcePath = null;
6834        String baseResourcePath = null;
6835        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6836            if (ps != null && ps.resourcePathString != null) {
6837                resourcePath = ps.resourcePathString;
6838                baseResourcePath = ps.resourcePathString;
6839            } else {
6840                // Should not happen at all. Just log an error.
6841                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6842            }
6843        } else {
6844            resourcePath = pkg.codePath;
6845            baseResourcePath = pkg.baseCodePath;
6846        }
6847
6848        // Set application objects path explicitly.
6849        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6850        pkg.setApplicationInfoCodePath(pkg.codePath);
6851        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6852        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6853        pkg.setApplicationInfoResourcePath(resourcePath);
6854        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6855        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6856
6857        // Note that we invoke the following method only if we are about to unpack an application
6858        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6859                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6860
6861        /*
6862         * If the system app should be overridden by a previously installed
6863         * data, hide the system app now and let the /data/app scan pick it up
6864         * again.
6865         */
6866        if (shouldHideSystemApp) {
6867            synchronized (mPackages) {
6868                mSettings.disableSystemPackageLPw(pkg.packageName, true);
6869            }
6870        }
6871
6872        return scannedPkg;
6873    }
6874
6875    private static String fixProcessName(String defProcessName,
6876            String processName, int uid) {
6877        if (processName == null) {
6878            return defProcessName;
6879        }
6880        return processName;
6881    }
6882
6883    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6884            throws PackageManagerException {
6885        if (pkgSetting.signatures.mSignatures != null) {
6886            // Already existing package. Make sure signatures match
6887            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6888                    == PackageManager.SIGNATURE_MATCH;
6889            if (!match) {
6890                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6891                        == PackageManager.SIGNATURE_MATCH;
6892            }
6893            if (!match) {
6894                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6895                        == PackageManager.SIGNATURE_MATCH;
6896            }
6897            if (!match) {
6898                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6899                        + pkg.packageName + " signatures do not match the "
6900                        + "previously installed version; ignoring!");
6901            }
6902        }
6903
6904        // Check for shared user signatures
6905        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6906            // Already existing package. Make sure signatures match
6907            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6908                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6909            if (!match) {
6910                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6911                        == PackageManager.SIGNATURE_MATCH;
6912            }
6913            if (!match) {
6914                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6915                        == PackageManager.SIGNATURE_MATCH;
6916            }
6917            if (!match) {
6918                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6919                        "Package " + pkg.packageName
6920                        + " has no signatures that match those in shared user "
6921                        + pkgSetting.sharedUser.name + "; ignoring!");
6922            }
6923        }
6924    }
6925
6926    /**
6927     * Enforces that only the system UID or root's UID can call a method exposed
6928     * via Binder.
6929     *
6930     * @param message used as message if SecurityException is thrown
6931     * @throws SecurityException if the caller is not system or root
6932     */
6933    private static final void enforceSystemOrRoot(String message) {
6934        final int uid = Binder.getCallingUid();
6935        if (uid != Process.SYSTEM_UID && uid != 0) {
6936            throw new SecurityException(message);
6937        }
6938    }
6939
6940    @Override
6941    public void performFstrimIfNeeded() {
6942        enforceSystemOrRoot("Only the system can request fstrim");
6943
6944        // Before everything else, see whether we need to fstrim.
6945        try {
6946            IMountService ms = PackageHelper.getMountService();
6947            if (ms != null) {
6948                final boolean isUpgrade = isUpgrade();
6949                boolean doTrim = isUpgrade;
6950                if (doTrim) {
6951                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6952                } else {
6953                    final long interval = android.provider.Settings.Global.getLong(
6954                            mContext.getContentResolver(),
6955                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6956                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6957                    if (interval > 0) {
6958                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6959                        if (timeSinceLast > interval) {
6960                            doTrim = true;
6961                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6962                                    + "; running immediately");
6963                        }
6964                    }
6965                }
6966                if (doTrim) {
6967                    if (!isFirstBoot()) {
6968                        try {
6969                            ActivityManagerNative.getDefault().showBootMessage(
6970                                    mContext.getResources().getString(
6971                                            R.string.android_upgrading_fstrim), true);
6972                        } catch (RemoteException e) {
6973                        }
6974                    }
6975                    ms.runMaintenance();
6976                }
6977            } else {
6978                Slog.e(TAG, "Mount service unavailable!");
6979            }
6980        } catch (RemoteException e) {
6981            // Can't happen; MountService is local
6982        }
6983    }
6984
6985    @Override
6986    public void updatePackagesIfNeeded() {
6987        enforceSystemOrRoot("Only the system can request package update");
6988
6989        // We need to re-extract after an OTA.
6990        boolean causeUpgrade = isUpgrade();
6991
6992        // First boot or factory reset.
6993        // Note: we also handle devices that are upgrading to N right now as if it is their
6994        //       first boot, as they do not have profile data.
6995        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
6996
6997        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
6998        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
6999
7000        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7001            return;
7002        }
7003
7004        List<PackageParser.Package> pkgs;
7005        synchronized (mPackages) {
7006            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7007        }
7008
7009        int curr = 0;
7010        int total = pkgs.size();
7011        for (PackageParser.Package pkg : pkgs) {
7012            curr++;
7013
7014            if (DEBUG_DEXOPT) {
7015                Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName);
7016            }
7017
7018            if (!isFirstBoot()) {
7019                try {
7020                    ActivityManagerNative.getDefault().showBootMessage(
7021                            mContext.getResources().getString(R.string.android_upgrading_apk,
7022                                    curr, total), true);
7023                } catch (RemoteException e) {
7024                }
7025            }
7026
7027            if (PackageDexOptimizer.canOptimizePackage(pkg)) {
7028                // If the cache was pruned, any compiled odex files will likely be out of date
7029                // and would have to be patched (would be SELF_PATCHOAT, which is deprecated).
7030                // Instead, force the extraction in this case.
7031                performDexOpt(pkg.packageName,
7032                        null /* instructionSet */,
7033                        false /* checkProfiles */,
7034                        causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
7035                        false /* force */);
7036            }
7037        }
7038    }
7039
7040    @Override
7041    public void notifyPackageUse(String packageName) {
7042        synchronized (mPackages) {
7043            PackageParser.Package p = mPackages.get(packageName);
7044            if (p == null) {
7045                return;
7046            }
7047            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
7048        }
7049    }
7050
7051    // TODO: this is not used nor needed. Delete it.
7052    @Override
7053    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
7054        return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */,
7055                getFullCompilerFilter(), false /* force */);
7056    }
7057
7058    @Override
7059    public boolean performDexOpt(String packageName, String instructionSet,
7060            boolean checkProfiles, int compileReason, boolean force) {
7061        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7062                getCompilerFilterForReason(compileReason), force);
7063    }
7064
7065    @Override
7066    public boolean performDexOptMode(String packageName, String instructionSet,
7067            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7068        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7069                targetCompilerFilter, force);
7070    }
7071
7072    private boolean performDexOptTraced(String packageName, String instructionSet,
7073                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7074        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7075        try {
7076            return performDexOptInternal(packageName, instructionSet, checkProfiles,
7077                    targetCompilerFilter, force);
7078        } finally {
7079            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7080        }
7081    }
7082
7083    private boolean performDexOptInternal(String packageName, String instructionSet,
7084                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7085        PackageParser.Package p;
7086        final String targetInstructionSet;
7087        synchronized (mPackages) {
7088            p = mPackages.get(packageName);
7089            if (p == null) {
7090                return false;
7091            }
7092            mPackageUsage.write(false);
7093
7094            targetInstructionSet = instructionSet != null ? instructionSet :
7095                    getPrimaryInstructionSet(p.applicationInfo);
7096        }
7097        long callingId = Binder.clearCallingIdentity();
7098        try {
7099            synchronized (mInstallLock) {
7100                final String[] instructionSets = new String[] { targetInstructionSet };
7101                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
7102                        checkProfiles, targetCompilerFilter, force);
7103                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
7104            }
7105        } finally {
7106            Binder.restoreCallingIdentity(callingId);
7107        }
7108    }
7109
7110    public ArraySet<String> getOptimizablePackages() {
7111        ArraySet<String> pkgs = new ArraySet<String>();
7112        synchronized (mPackages) {
7113            for (PackageParser.Package p : mPackages.values()) {
7114                if (PackageDexOptimizer.canOptimizePackage(p)) {
7115                    pkgs.add(p.packageName);
7116                }
7117            }
7118        }
7119        return pkgs;
7120    }
7121
7122    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7123            String instructionSets[], boolean checkProfiles, String targetCompilerFilter,
7124            boolean force) {
7125        // Select the dex optimizer based on the force parameter.
7126        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7127        //       allocate an object here.
7128        PackageDexOptimizer pdo = force
7129                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7130                : mPackageDexOptimizer;
7131
7132        // Optimize all dependencies first. Note: we ignore the return value and march on
7133        // on errors.
7134        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7135        if (!deps.isEmpty()) {
7136            for (PackageParser.Package depPackage : deps) {
7137                // TODO: Analyze and investigate if we (should) profile libraries.
7138                // Currently this will do a full compilation of the library by default.
7139                pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */,
7140                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7141            }
7142        }
7143
7144        return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter);
7145    }
7146
7147    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7148        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7149            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7150            Set<String> collectedNames = new HashSet<>();
7151            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7152
7153            retValue.remove(p);
7154
7155            return retValue;
7156        } else {
7157            return Collections.emptyList();
7158        }
7159    }
7160
7161    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7162            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7163        if (!collectedNames.contains(p.packageName)) {
7164            collectedNames.add(p.packageName);
7165            collected.add(p);
7166
7167            if (p.usesLibraries != null) {
7168                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7169            }
7170            if (p.usesOptionalLibraries != null) {
7171                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7172                        collectedNames);
7173            }
7174        }
7175    }
7176
7177    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7178            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7179        for (String libName : libs) {
7180            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7181            if (libPkg != null) {
7182                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7183            }
7184        }
7185    }
7186
7187    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7188        synchronized (mPackages) {
7189            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7190            if (lib != null && lib.apk != null) {
7191                return mPackages.get(lib.apk);
7192            }
7193        }
7194        return null;
7195    }
7196
7197    public void shutdown() {
7198        mPackageUsage.write(true);
7199    }
7200
7201    @Override
7202    public void forceDexOpt(String packageName) {
7203        enforceSystemOrRoot("forceDexOpt");
7204
7205        PackageParser.Package pkg;
7206        synchronized (mPackages) {
7207            pkg = mPackages.get(packageName);
7208            if (pkg == null) {
7209                throw new IllegalArgumentException("Unknown package: " + packageName);
7210            }
7211        }
7212
7213        synchronized (mInstallLock) {
7214            final String[] instructionSets = new String[] {
7215                    getPrimaryInstructionSet(pkg.applicationInfo) };
7216
7217            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7218
7219            // Whoever is calling forceDexOpt wants a fully compiled package.
7220            // Don't use profiles since that may cause compilation to be skipped.
7221            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7222                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7223                    true /* force */);
7224
7225            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7226            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7227                throw new IllegalStateException("Failed to dexopt: " + res);
7228            }
7229        }
7230    }
7231
7232    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7233        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7234            Slog.w(TAG, "Unable to update from " + oldPkg.name
7235                    + " to " + newPkg.packageName
7236                    + ": old package not in system partition");
7237            return false;
7238        } else if (mPackages.get(oldPkg.name) != null) {
7239            Slog.w(TAG, "Unable to update from " + oldPkg.name
7240                    + " to " + newPkg.packageName
7241                    + ": old package still exists");
7242            return false;
7243        }
7244        return true;
7245    }
7246
7247    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
7248        // TODO: triage flags as part of 26466827
7249        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7250
7251        boolean res = true;
7252        final int[] users = sUserManager.getUserIds();
7253        for (int user : users) {
7254            try {
7255                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
7256            } catch (InstallerException e) {
7257                Slog.w(TAG, "Failed to delete data directory", e);
7258                res = false;
7259            }
7260        }
7261        return res;
7262    }
7263
7264    void removeCodePathLI(File codePath) {
7265        if (codePath.isDirectory()) {
7266            try {
7267                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7268            } catch (InstallerException e) {
7269                Slog.w(TAG, "Failed to remove code path", e);
7270            }
7271        } else {
7272            codePath.delete();
7273        }
7274    }
7275
7276    void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) {
7277        try {
7278            mInstaller.destroyAppData(volumeUuid, packageName, userId, flags);
7279        } catch (InstallerException e) {
7280            Slog.w(TAG, "Failed to destroy app data", e);
7281        }
7282    }
7283
7284    void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags,
7285            int appId, String seinfo) {
7286        try {
7287            mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo);
7288        } catch (InstallerException e) {
7289            Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
7290        }
7291    }
7292
7293    private void deleteProfilesLI(String packageName, boolean destroy) {
7294        final PackageParser.Package pkg;
7295        synchronized (mPackages) {
7296            pkg = mPackages.get(packageName);
7297        }
7298        if (pkg == null) {
7299            Slog.w(TAG, "Failed to delete profiles. No package: " + packageName);
7300            return;
7301        }
7302        deleteProfilesLI(pkg, destroy);
7303    }
7304
7305    private void deleteProfilesLI(PackageParser.Package pkg, boolean destroy) {
7306        try {
7307            if (destroy) {
7308                mInstaller.destroyAppProfiles(pkg.packageName);
7309            } else {
7310                mInstaller.clearAppProfiles(pkg.packageName);
7311            }
7312        } catch (InstallerException ex) {
7313            Log.e(TAG, "Could not delete profiles for package " + pkg.packageName);
7314        }
7315    }
7316
7317    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
7318        final PackageParser.Package pkg;
7319        synchronized (mPackages) {
7320            pkg = mPackages.get(packageName);
7321        }
7322        if (pkg == null) {
7323            Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName);
7324            return;
7325        }
7326        deleteCodeCacheDirsLI(pkg);
7327    }
7328
7329    private void deleteCodeCacheDirsLI(PackageParser.Package pkg) {
7330        // TODO: triage flags as part of 26466827
7331        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7332
7333        int[] users = sUserManager.getUserIds();
7334        int res = 0;
7335        for (int user : users) {
7336            // Remove the parent code cache
7337            try {
7338                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user,
7339                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7340            } catch (InstallerException e) {
7341                Slog.w(TAG, "Failed to delete code cache directory", e);
7342            }
7343            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7344            for (int i = 0; i < childCount; i++) {
7345                PackageParser.Package childPkg = pkg.childPackages.get(i);
7346                // Remove the child code cache
7347                try {
7348                    mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName,
7349                            user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7350                } catch (InstallerException e) {
7351                    Slog.w(TAG, "Failed to delete code cache directory", e);
7352                }
7353            }
7354        }
7355    }
7356
7357    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7358            long lastUpdateTime) {
7359        // Set parent install/update time
7360        PackageSetting ps = (PackageSetting) pkg.mExtras;
7361        if (ps != null) {
7362            ps.firstInstallTime = firstInstallTime;
7363            ps.lastUpdateTime = lastUpdateTime;
7364        }
7365        // Set children install/update time
7366        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7367        for (int i = 0; i < childCount; i++) {
7368            PackageParser.Package childPkg = pkg.childPackages.get(i);
7369            ps = (PackageSetting) childPkg.mExtras;
7370            if (ps != null) {
7371                ps.firstInstallTime = firstInstallTime;
7372                ps.lastUpdateTime = lastUpdateTime;
7373            }
7374        }
7375    }
7376
7377    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7378            PackageParser.Package changingLib) {
7379        if (file.path != null) {
7380            usesLibraryFiles.add(file.path);
7381            return;
7382        }
7383        PackageParser.Package p = mPackages.get(file.apk);
7384        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7385            // If we are doing this while in the middle of updating a library apk,
7386            // then we need to make sure to use that new apk for determining the
7387            // dependencies here.  (We haven't yet finished committing the new apk
7388            // to the package manager state.)
7389            if (p == null || p.packageName.equals(changingLib.packageName)) {
7390                p = changingLib;
7391            }
7392        }
7393        if (p != null) {
7394            usesLibraryFiles.addAll(p.getAllCodePaths());
7395        }
7396    }
7397
7398    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7399            PackageParser.Package changingLib) throws PackageManagerException {
7400        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7401            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7402            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7403            for (int i=0; i<N; i++) {
7404                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7405                if (file == null) {
7406                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7407                            "Package " + pkg.packageName + " requires unavailable shared library "
7408                            + pkg.usesLibraries.get(i) + "; failing!");
7409                }
7410                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7411            }
7412            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7413            for (int i=0; i<N; i++) {
7414                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7415                if (file == null) {
7416                    Slog.w(TAG, "Package " + pkg.packageName
7417                            + " desires unavailable shared library "
7418                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7419                } else {
7420                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7421                }
7422            }
7423            N = usesLibraryFiles.size();
7424            if (N > 0) {
7425                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7426            } else {
7427                pkg.usesLibraryFiles = null;
7428            }
7429        }
7430    }
7431
7432    private static boolean hasString(List<String> list, List<String> which) {
7433        if (list == null) {
7434            return false;
7435        }
7436        for (int i=list.size()-1; i>=0; i--) {
7437            for (int j=which.size()-1; j>=0; j--) {
7438                if (which.get(j).equals(list.get(i))) {
7439                    return true;
7440                }
7441            }
7442        }
7443        return false;
7444    }
7445
7446    private void updateAllSharedLibrariesLPw() {
7447        for (PackageParser.Package pkg : mPackages.values()) {
7448            try {
7449                updateSharedLibrariesLPw(pkg, null);
7450            } catch (PackageManagerException e) {
7451                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7452            }
7453        }
7454    }
7455
7456    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7457            PackageParser.Package changingPkg) {
7458        ArrayList<PackageParser.Package> res = null;
7459        for (PackageParser.Package pkg : mPackages.values()) {
7460            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7461                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7462                if (res == null) {
7463                    res = new ArrayList<PackageParser.Package>();
7464                }
7465                res.add(pkg);
7466                try {
7467                    updateSharedLibrariesLPw(pkg, changingPkg);
7468                } catch (PackageManagerException e) {
7469                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7470                }
7471            }
7472        }
7473        return res;
7474    }
7475
7476    /**
7477     * Derive the value of the {@code cpuAbiOverride} based on the provided
7478     * value and an optional stored value from the package settings.
7479     */
7480    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7481        String cpuAbiOverride = null;
7482
7483        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7484            cpuAbiOverride = null;
7485        } else if (abiOverride != null) {
7486            cpuAbiOverride = abiOverride;
7487        } else if (settings != null) {
7488            cpuAbiOverride = settings.cpuAbiOverrideString;
7489        }
7490
7491        return cpuAbiOverride;
7492    }
7493
7494    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
7495            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7496        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7497        // If the package has children and this is the first dive in the function
7498        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7499        // whether all packages (parent and children) would be successfully scanned
7500        // before the actual scan since scanning mutates internal state and we want
7501        // to atomically install the package and its children.
7502        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7503            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7504                scanFlags |= SCAN_CHECK_ONLY;
7505            }
7506        } else {
7507            scanFlags &= ~SCAN_CHECK_ONLY;
7508        }
7509
7510        final PackageParser.Package scannedPkg;
7511        try {
7512            // Scan the parent
7513            scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
7514            // Scan the children
7515            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7516            for (int i = 0; i < childCount; i++) {
7517                PackageParser.Package childPkg = pkg.childPackages.get(i);
7518                scanPackageLI(childPkg, parseFlags,
7519                        scanFlags, currentTime, user);
7520            }
7521        } finally {
7522            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7523        }
7524
7525        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7526            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
7527        }
7528
7529        return scannedPkg;
7530    }
7531
7532    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
7533            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7534        boolean success = false;
7535        try {
7536            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
7537                    currentTime, user);
7538            success = true;
7539            return res;
7540        } finally {
7541            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7542                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
7543            }
7544        }
7545    }
7546
7547    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
7548            int scanFlags, long currentTime, UserHandle user)
7549            throws PackageManagerException {
7550        final File scanFile = new File(pkg.codePath);
7551        if (pkg.applicationInfo.getCodePath() == null ||
7552                pkg.applicationInfo.getResourcePath() == null) {
7553            // Bail out. The resource and code paths haven't been set.
7554            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7555                    "Code and resource paths haven't been set correctly");
7556        }
7557
7558        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7559            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7560        } else {
7561            // Only allow system apps to be flagged as core apps.
7562            pkg.coreApp = false;
7563        }
7564
7565        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7566            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7567        }
7568
7569        if (mCustomResolverComponentName != null &&
7570                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7571            setUpCustomResolverActivity(pkg);
7572        }
7573
7574        if (pkg.packageName.equals("android")) {
7575            synchronized (mPackages) {
7576                if (mAndroidApplication != null) {
7577                    Slog.w(TAG, "*************************************************");
7578                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7579                    Slog.w(TAG, " file=" + scanFile);
7580                    Slog.w(TAG, "*************************************************");
7581                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7582                            "Core android package being redefined.  Skipping.");
7583                }
7584
7585                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7586                    // Set up information for our fall-back user intent resolution activity.
7587                    mPlatformPackage = pkg;
7588                    pkg.mVersionCode = mSdkVersion;
7589                    mAndroidApplication = pkg.applicationInfo;
7590
7591                    if (!mResolverReplaced) {
7592                        mResolveActivity.applicationInfo = mAndroidApplication;
7593                        mResolveActivity.name = ResolverActivity.class.getName();
7594                        mResolveActivity.packageName = mAndroidApplication.packageName;
7595                        mResolveActivity.processName = "system:ui";
7596                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7597                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7598                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7599                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7600                        mResolveActivity.exported = true;
7601                        mResolveActivity.enabled = true;
7602                        mResolveInfo.activityInfo = mResolveActivity;
7603                        mResolveInfo.priority = 0;
7604                        mResolveInfo.preferredOrder = 0;
7605                        mResolveInfo.match = 0;
7606                        mResolveComponentName = new ComponentName(
7607                                mAndroidApplication.packageName, mResolveActivity.name);
7608                    }
7609                }
7610            }
7611        }
7612
7613        if (DEBUG_PACKAGE_SCANNING) {
7614            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7615                Log.d(TAG, "Scanning package " + pkg.packageName);
7616        }
7617
7618        synchronized (mPackages) {
7619            if (mPackages.containsKey(pkg.packageName)
7620                    || mSharedLibraries.containsKey(pkg.packageName)) {
7621                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7622                        "Application package " + pkg.packageName
7623                                + " already installed.  Skipping duplicate.");
7624            }
7625
7626            // If we're only installing presumed-existing packages, require that the
7627            // scanned APK is both already known and at the path previously established
7628            // for it.  Previously unknown packages we pick up normally, but if we have an
7629            // a priori expectation about this package's install presence, enforce it.
7630            // With a singular exception for new system packages. When an OTA contains
7631            // a new system package, we allow the codepath to change from a system location
7632            // to the user-installed location. If we don't allow this change, any newer,
7633            // user-installed version of the application will be ignored.
7634            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7635                if (mExpectingBetter.containsKey(pkg.packageName)) {
7636                    logCriticalInfo(Log.WARN,
7637                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7638                } else {
7639                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7640                    if (known != null) {
7641                        if (DEBUG_PACKAGE_SCANNING) {
7642                            Log.d(TAG, "Examining " + pkg.codePath
7643                                    + " and requiring known paths " + known.codePathString
7644                                    + " & " + known.resourcePathString);
7645                        }
7646                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7647                                || !pkg.applicationInfo.getResourcePath().equals(
7648                                known.resourcePathString)) {
7649                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7650                                    "Application package " + pkg.packageName
7651                                            + " found at " + pkg.applicationInfo.getCodePath()
7652                                            + " but expected at " + known.codePathString
7653                                            + "; ignoring.");
7654                        }
7655                    }
7656                }
7657            }
7658        }
7659
7660        // Initialize package source and resource directories
7661        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7662        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7663
7664        SharedUserSetting suid = null;
7665        PackageSetting pkgSetting = null;
7666
7667        if (!isSystemApp(pkg)) {
7668            // Only system apps can use these features.
7669            pkg.mOriginalPackages = null;
7670            pkg.mRealPackage = null;
7671            pkg.mAdoptPermissions = null;
7672        }
7673
7674        // Getting the package setting may have a side-effect, so if we
7675        // are only checking if scan would succeed, stash a copy of the
7676        // old setting to restore at the end.
7677        PackageSetting nonMutatedPs = null;
7678
7679        // writer
7680        synchronized (mPackages) {
7681            if (pkg.mSharedUserId != null) {
7682                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7683                if (suid == null) {
7684                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7685                            "Creating application package " + pkg.packageName
7686                            + " for shared user failed");
7687                }
7688                if (DEBUG_PACKAGE_SCANNING) {
7689                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7690                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7691                                + "): packages=" + suid.packages);
7692                }
7693            }
7694
7695            // Check if we are renaming from an original package name.
7696            PackageSetting origPackage = null;
7697            String realName = null;
7698            if (pkg.mOriginalPackages != null) {
7699                // This package may need to be renamed to a previously
7700                // installed name.  Let's check on that...
7701                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7702                if (pkg.mOriginalPackages.contains(renamed)) {
7703                    // This package had originally been installed as the
7704                    // original name, and we have already taken care of
7705                    // transitioning to the new one.  Just update the new
7706                    // one to continue using the old name.
7707                    realName = pkg.mRealPackage;
7708                    if (!pkg.packageName.equals(renamed)) {
7709                        // Callers into this function may have already taken
7710                        // care of renaming the package; only do it here if
7711                        // it is not already done.
7712                        pkg.setPackageName(renamed);
7713                    }
7714
7715                } else {
7716                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7717                        if ((origPackage = mSettings.peekPackageLPr(
7718                                pkg.mOriginalPackages.get(i))) != null) {
7719                            // We do have the package already installed under its
7720                            // original name...  should we use it?
7721                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7722                                // New package is not compatible with original.
7723                                origPackage = null;
7724                                continue;
7725                            } else if (origPackage.sharedUser != null) {
7726                                // Make sure uid is compatible between packages.
7727                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7728                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7729                                            + " to " + pkg.packageName + ": old uid "
7730                                            + origPackage.sharedUser.name
7731                                            + " differs from " + pkg.mSharedUserId);
7732                                    origPackage = null;
7733                                    continue;
7734                                }
7735                            } else {
7736                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7737                                        + pkg.packageName + " to old name " + origPackage.name);
7738                            }
7739                            break;
7740                        }
7741                    }
7742                }
7743            }
7744
7745            if (mTransferedPackages.contains(pkg.packageName)) {
7746                Slog.w(TAG, "Package " + pkg.packageName
7747                        + " was transferred to another, but its .apk remains");
7748            }
7749
7750            // See comments in nonMutatedPs declaration
7751            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7752                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
7753                if (foundPs != null) {
7754                    nonMutatedPs = new PackageSetting(foundPs);
7755                }
7756            }
7757
7758            // Just create the setting, don't add it yet. For already existing packages
7759            // the PkgSetting exists already and doesn't have to be created.
7760            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7761                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7762                    pkg.applicationInfo.primaryCpuAbi,
7763                    pkg.applicationInfo.secondaryCpuAbi,
7764                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7765                    user, false);
7766            if (pkgSetting == null) {
7767                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7768                        "Creating application package " + pkg.packageName + " failed");
7769            }
7770
7771            if (pkgSetting.origPackage != null) {
7772                // If we are first transitioning from an original package,
7773                // fix up the new package's name now.  We need to do this after
7774                // looking up the package under its new name, so getPackageLP
7775                // can take care of fiddling things correctly.
7776                pkg.setPackageName(origPackage.name);
7777
7778                // File a report about this.
7779                String msg = "New package " + pkgSetting.realName
7780                        + " renamed to replace old package " + pkgSetting.name;
7781                reportSettingsProblem(Log.WARN, msg);
7782
7783                // Make a note of it.
7784                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7785                    mTransferedPackages.add(origPackage.name);
7786                }
7787
7788                // No longer need to retain this.
7789                pkgSetting.origPackage = null;
7790            }
7791
7792            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
7793                // Make a note of it.
7794                mTransferedPackages.add(pkg.packageName);
7795            }
7796
7797            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7798                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7799            }
7800
7801            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7802                // Check all shared libraries and map to their actual file path.
7803                // We only do this here for apps not on a system dir, because those
7804                // are the only ones that can fail an install due to this.  We
7805                // will take care of the system apps by updating all of their
7806                // library paths after the scan is done.
7807                updateSharedLibrariesLPw(pkg, null);
7808            }
7809
7810            if (mFoundPolicyFile) {
7811                SELinuxMMAC.assignSeinfoValue(pkg);
7812            }
7813
7814            pkg.applicationInfo.uid = pkgSetting.appId;
7815            pkg.mExtras = pkgSetting;
7816            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7817                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7818                    // We just determined the app is signed correctly, so bring
7819                    // over the latest parsed certs.
7820                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7821                } else {
7822                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7823                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7824                                "Package " + pkg.packageName + " upgrade keys do not match the "
7825                                + "previously installed version");
7826                    } else {
7827                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7828                        String msg = "System package " + pkg.packageName
7829                            + " signature changed; retaining data.";
7830                        reportSettingsProblem(Log.WARN, msg);
7831                    }
7832                }
7833            } else {
7834                try {
7835                    verifySignaturesLP(pkgSetting, pkg);
7836                    // We just determined the app is signed correctly, so bring
7837                    // over the latest parsed certs.
7838                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7839                } catch (PackageManagerException e) {
7840                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7841                        throw e;
7842                    }
7843                    // The signature has changed, but this package is in the system
7844                    // image...  let's recover!
7845                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7846                    // However...  if this package is part of a shared user, but it
7847                    // doesn't match the signature of the shared user, let's fail.
7848                    // What this means is that you can't change the signatures
7849                    // associated with an overall shared user, which doesn't seem all
7850                    // that unreasonable.
7851                    if (pkgSetting.sharedUser != null) {
7852                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7853                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7854                            throw new PackageManagerException(
7855                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7856                                            "Signature mismatch for shared user: "
7857                                            + pkgSetting.sharedUser);
7858                        }
7859                    }
7860                    // File a report about this.
7861                    String msg = "System package " + pkg.packageName
7862                        + " signature changed; retaining data.";
7863                    reportSettingsProblem(Log.WARN, msg);
7864                }
7865            }
7866            // Verify that this new package doesn't have any content providers
7867            // that conflict with existing packages.  Only do this if the
7868            // package isn't already installed, since we don't want to break
7869            // things that are installed.
7870            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7871                final int N = pkg.providers.size();
7872                int i;
7873                for (i=0; i<N; i++) {
7874                    PackageParser.Provider p = pkg.providers.get(i);
7875                    if (p.info.authority != null) {
7876                        String names[] = p.info.authority.split(";");
7877                        for (int j = 0; j < names.length; j++) {
7878                            if (mProvidersByAuthority.containsKey(names[j])) {
7879                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7880                                final String otherPackageName =
7881                                        ((other != null && other.getComponentName() != null) ?
7882                                                other.getComponentName().getPackageName() : "?");
7883                                throw new PackageManagerException(
7884                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7885                                                "Can't install because provider name " + names[j]
7886                                                + " (in package " + pkg.applicationInfo.packageName
7887                                                + ") is already used by " + otherPackageName);
7888                            }
7889                        }
7890                    }
7891                }
7892            }
7893
7894            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
7895                // This package wants to adopt ownership of permissions from
7896                // another package.
7897                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7898                    final String origName = pkg.mAdoptPermissions.get(i);
7899                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7900                    if (orig != null) {
7901                        if (verifyPackageUpdateLPr(orig, pkg)) {
7902                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7903                                    + pkg.packageName);
7904                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7905                        }
7906                    }
7907                }
7908            }
7909        }
7910
7911        final String pkgName = pkg.packageName;
7912
7913        final long scanFileTime = scanFile.lastModified();
7914        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7915        pkg.applicationInfo.processName = fixProcessName(
7916                pkg.applicationInfo.packageName,
7917                pkg.applicationInfo.processName,
7918                pkg.applicationInfo.uid);
7919
7920        if (pkg != mPlatformPackage) {
7921            // Get all of our default paths setup
7922            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7923        }
7924
7925        final String path = scanFile.getPath();
7926        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7927
7928        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7929            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7930
7931            // Some system apps still use directory structure for native libraries
7932            // in which case we might end up not detecting abi solely based on apk
7933            // structure. Try to detect abi based on directory structure.
7934            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7935                    pkg.applicationInfo.primaryCpuAbi == null) {
7936                setBundledAppAbisAndRoots(pkg, pkgSetting);
7937                setNativeLibraryPaths(pkg);
7938            }
7939
7940        } else {
7941            if ((scanFlags & SCAN_MOVE) != 0) {
7942                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7943                // but we already have this packages package info in the PackageSetting. We just
7944                // use that and derive the native library path based on the new codepath.
7945                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7946                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7947            }
7948
7949            // Set native library paths again. For moves, the path will be updated based on the
7950            // ABIs we've determined above. For non-moves, the path will be updated based on the
7951            // ABIs we determined during compilation, but the path will depend on the final
7952            // package path (after the rename away from the stage path).
7953            setNativeLibraryPaths(pkg);
7954        }
7955
7956        // This is a special case for the "system" package, where the ABI is
7957        // dictated by the zygote configuration (and init.rc). We should keep track
7958        // of this ABI so that we can deal with "normal" applications that run under
7959        // the same UID correctly.
7960        if (mPlatformPackage == pkg) {
7961            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7962                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7963        }
7964
7965        // If there's a mismatch between the abi-override in the package setting
7966        // and the abiOverride specified for the install. Warn about this because we
7967        // would've already compiled the app without taking the package setting into
7968        // account.
7969        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7970            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7971                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7972                        " for package " + pkg.packageName);
7973            }
7974        }
7975
7976        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7977        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7978        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7979
7980        // Copy the derived override back to the parsed package, so that we can
7981        // update the package settings accordingly.
7982        pkg.cpuAbiOverride = cpuAbiOverride;
7983
7984        if (DEBUG_ABI_SELECTION) {
7985            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7986                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7987                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7988        }
7989
7990        // Push the derived path down into PackageSettings so we know what to
7991        // clean up at uninstall time.
7992        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7993
7994        if (DEBUG_ABI_SELECTION) {
7995            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7996                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7997                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7998        }
7999
8000        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8001            // We don't do this here during boot because we can do it all
8002            // at once after scanning all existing packages.
8003            //
8004            // We also do this *before* we perform dexopt on this package, so that
8005            // we can avoid redundant dexopts, and also to make sure we've got the
8006            // code and package path correct.
8007            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8008                    pkg, true /* boot complete */);
8009        }
8010
8011        if (mFactoryTest && pkg.requestedPermissions.contains(
8012                android.Manifest.permission.FACTORY_TEST)) {
8013            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8014        }
8015
8016        ArrayList<PackageParser.Package> clientLibPkgs = null;
8017
8018        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8019            if (nonMutatedPs != null) {
8020                synchronized (mPackages) {
8021                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8022                }
8023            }
8024            return pkg;
8025        }
8026
8027        // Only privileged apps and updated privileged apps can add child packages.
8028        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8029            if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) {
8030                throw new PackageManagerException("Only privileged apps and updated "
8031                        + "privileged apps can add child packages. Ignoring package "
8032                        + pkg.packageName);
8033            }
8034            final int childCount = pkg.childPackages.size();
8035            for (int i = 0; i < childCount; i++) {
8036                PackageParser.Package childPkg = pkg.childPackages.get(i);
8037                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8038                        childPkg.packageName)) {
8039                    throw new PackageManagerException("Cannot override a child package of "
8040                            + "another disabled system app. Ignoring package " + pkg.packageName);
8041                }
8042            }
8043        }
8044
8045        // writer
8046        synchronized (mPackages) {
8047            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8048                // Only system apps can add new shared libraries.
8049                if (pkg.libraryNames != null) {
8050                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8051                        String name = pkg.libraryNames.get(i);
8052                        boolean allowed = false;
8053                        if (pkg.isUpdatedSystemApp()) {
8054                            // New library entries can only be added through the
8055                            // system image.  This is important to get rid of a lot
8056                            // of nasty edge cases: for example if we allowed a non-
8057                            // system update of the app to add a library, then uninstalling
8058                            // the update would make the library go away, and assumptions
8059                            // we made such as through app install filtering would now
8060                            // have allowed apps on the device which aren't compatible
8061                            // with it.  Better to just have the restriction here, be
8062                            // conservative, and create many fewer cases that can negatively
8063                            // impact the user experience.
8064                            final PackageSetting sysPs = mSettings
8065                                    .getDisabledSystemPkgLPr(pkg.packageName);
8066                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8067                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8068                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8069                                        allowed = true;
8070                                        break;
8071                                    }
8072                                }
8073                            }
8074                        } else {
8075                            allowed = true;
8076                        }
8077                        if (allowed) {
8078                            if (!mSharedLibraries.containsKey(name)) {
8079                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8080                            } else if (!name.equals(pkg.packageName)) {
8081                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8082                                        + name + " already exists; skipping");
8083                            }
8084                        } else {
8085                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8086                                    + name + " that is not declared on system image; skipping");
8087                        }
8088                    }
8089                    if ((scanFlags & SCAN_BOOTING) == 0) {
8090                        // If we are not booting, we need to update any applications
8091                        // that are clients of our shared library.  If we are booting,
8092                        // this will all be done once the scan is complete.
8093                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8094                    }
8095                }
8096            }
8097        }
8098
8099        // Request the ActivityManager to kill the process(only for existing packages)
8100        // so that we do not end up in a confused state while the user is still using the older
8101        // version of the application while the new one gets installed.
8102        final boolean isReplacing = (scanFlags & SCAN_REPLACING) != 0;
8103        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
8104        if (killApp) {
8105            if (isReplacing) {
8106                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
8107
8108                killApplication(pkg.applicationInfo.packageName,
8109                            pkg.applicationInfo.uid, "replace pkg");
8110
8111                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8112            }
8113        }
8114
8115        // Also need to kill any apps that are dependent on the library.
8116        if (clientLibPkgs != null) {
8117            for (int i=0; i<clientLibPkgs.size(); i++) {
8118                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8119                killApplication(clientPkg.applicationInfo.packageName,
8120                        clientPkg.applicationInfo.uid, "update lib");
8121            }
8122        }
8123
8124        // Make sure we're not adding any bogus keyset info
8125        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8126        ksms.assertScannedPackageValid(pkg);
8127
8128        // writer
8129        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8130
8131        boolean createIdmapFailed = false;
8132        synchronized (mPackages) {
8133            // We don't expect installation to fail beyond this point
8134
8135            // Add the new setting to mSettings
8136            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8137            // Add the new setting to mPackages
8138            mPackages.put(pkg.applicationInfo.packageName, pkg);
8139            // Make sure we don't accidentally delete its data.
8140            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8141            while (iter.hasNext()) {
8142                PackageCleanItem item = iter.next();
8143                if (pkgName.equals(item.packageName)) {
8144                    iter.remove();
8145                }
8146            }
8147
8148            // Take care of first install / last update times.
8149            if (currentTime != 0) {
8150                if (pkgSetting.firstInstallTime == 0) {
8151                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8152                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8153                    pkgSetting.lastUpdateTime = currentTime;
8154                }
8155            } else if (pkgSetting.firstInstallTime == 0) {
8156                // We need *something*.  Take time time stamp of the file.
8157                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8158            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8159                if (scanFileTime != pkgSetting.timeStamp) {
8160                    // A package on the system image has changed; consider this
8161                    // to be an update.
8162                    pkgSetting.lastUpdateTime = scanFileTime;
8163                }
8164            }
8165
8166            // Add the package's KeySets to the global KeySetManagerService
8167            ksms.addScannedPackageLPw(pkg);
8168
8169            int N = pkg.providers.size();
8170            StringBuilder r = null;
8171            int i;
8172            for (i=0; i<N; i++) {
8173                PackageParser.Provider p = pkg.providers.get(i);
8174                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8175                        p.info.processName, pkg.applicationInfo.uid);
8176                mProviders.addProvider(p);
8177                p.syncable = p.info.isSyncable;
8178                if (p.info.authority != null) {
8179                    String names[] = p.info.authority.split(";");
8180                    p.info.authority = null;
8181                    for (int j = 0; j < names.length; j++) {
8182                        if (j == 1 && p.syncable) {
8183                            // We only want the first authority for a provider to possibly be
8184                            // syncable, so if we already added this provider using a different
8185                            // authority clear the syncable flag. We copy the provider before
8186                            // changing it because the mProviders object contains a reference
8187                            // to a provider that we don't want to change.
8188                            // Only do this for the second authority since the resulting provider
8189                            // object can be the same for all future authorities for this provider.
8190                            p = new PackageParser.Provider(p);
8191                            p.syncable = false;
8192                        }
8193                        if (!mProvidersByAuthority.containsKey(names[j])) {
8194                            mProvidersByAuthority.put(names[j], p);
8195                            if (p.info.authority == null) {
8196                                p.info.authority = names[j];
8197                            } else {
8198                                p.info.authority = p.info.authority + ";" + names[j];
8199                            }
8200                            if (DEBUG_PACKAGE_SCANNING) {
8201                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
8202                                    Log.d(TAG, "Registered content provider: " + names[j]
8203                                            + ", className = " + p.info.name + ", isSyncable = "
8204                                            + p.info.isSyncable);
8205                            }
8206                        } else {
8207                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8208                            Slog.w(TAG, "Skipping provider name " + names[j] +
8209                                    " (in package " + pkg.applicationInfo.packageName +
8210                                    "): name already used by "
8211                                    + ((other != null && other.getComponentName() != null)
8212                                            ? other.getComponentName().getPackageName() : "?"));
8213                        }
8214                    }
8215                }
8216                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8217                    if (r == null) {
8218                        r = new StringBuilder(256);
8219                    } else {
8220                        r.append(' ');
8221                    }
8222                    r.append(p.info.name);
8223                }
8224            }
8225            if (r != null) {
8226                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8227            }
8228
8229            N = pkg.services.size();
8230            r = null;
8231            for (i=0; i<N; i++) {
8232                PackageParser.Service s = pkg.services.get(i);
8233                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8234                        s.info.processName, pkg.applicationInfo.uid);
8235                mServices.addService(s);
8236                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8237                    if (r == null) {
8238                        r = new StringBuilder(256);
8239                    } else {
8240                        r.append(' ');
8241                    }
8242                    r.append(s.info.name);
8243                }
8244            }
8245            if (r != null) {
8246                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8247            }
8248
8249            N = pkg.receivers.size();
8250            r = null;
8251            for (i=0; i<N; i++) {
8252                PackageParser.Activity a = pkg.receivers.get(i);
8253                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8254                        a.info.processName, pkg.applicationInfo.uid);
8255                mReceivers.addActivity(a, "receiver");
8256                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8257                    if (r == null) {
8258                        r = new StringBuilder(256);
8259                    } else {
8260                        r.append(' ');
8261                    }
8262                    r.append(a.info.name);
8263                }
8264            }
8265            if (r != null) {
8266                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8267            }
8268
8269            N = pkg.activities.size();
8270            r = null;
8271            for (i=0; i<N; i++) {
8272                PackageParser.Activity a = pkg.activities.get(i);
8273                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8274                        a.info.processName, pkg.applicationInfo.uid);
8275                mActivities.addActivity(a, "activity");
8276                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8277                    if (r == null) {
8278                        r = new StringBuilder(256);
8279                    } else {
8280                        r.append(' ');
8281                    }
8282                    r.append(a.info.name);
8283                }
8284            }
8285            if (r != null) {
8286                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8287            }
8288
8289            N = pkg.permissionGroups.size();
8290            r = null;
8291            for (i=0; i<N; i++) {
8292                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8293                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8294                if (cur == null) {
8295                    mPermissionGroups.put(pg.info.name, pg);
8296                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8297                        if (r == null) {
8298                            r = new StringBuilder(256);
8299                        } else {
8300                            r.append(' ');
8301                        }
8302                        r.append(pg.info.name);
8303                    }
8304                } else {
8305                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8306                            + pg.info.packageName + " ignored: original from "
8307                            + cur.info.packageName);
8308                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8309                        if (r == null) {
8310                            r = new StringBuilder(256);
8311                        } else {
8312                            r.append(' ');
8313                        }
8314                        r.append("DUP:");
8315                        r.append(pg.info.name);
8316                    }
8317                }
8318            }
8319            if (r != null) {
8320                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8321            }
8322
8323            N = pkg.permissions.size();
8324            r = null;
8325            for (i=0; i<N; i++) {
8326                PackageParser.Permission p = pkg.permissions.get(i);
8327
8328                // Assume by default that we did not install this permission into the system.
8329                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8330
8331                // Now that permission groups have a special meaning, we ignore permission
8332                // groups for legacy apps to prevent unexpected behavior. In particular,
8333                // permissions for one app being granted to someone just becase they happen
8334                // to be in a group defined by another app (before this had no implications).
8335                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8336                    p.group = mPermissionGroups.get(p.info.group);
8337                    // Warn for a permission in an unknown group.
8338                    if (p.info.group != null && p.group == null) {
8339                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8340                                + p.info.packageName + " in an unknown group " + p.info.group);
8341                    }
8342                }
8343
8344                ArrayMap<String, BasePermission> permissionMap =
8345                        p.tree ? mSettings.mPermissionTrees
8346                                : mSettings.mPermissions;
8347                BasePermission bp = permissionMap.get(p.info.name);
8348
8349                // Allow system apps to redefine non-system permissions
8350                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8351                    final boolean currentOwnerIsSystem = (bp.perm != null
8352                            && isSystemApp(bp.perm.owner));
8353                    if (isSystemApp(p.owner)) {
8354                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8355                            // It's a built-in permission and no owner, take ownership now
8356                            bp.packageSetting = pkgSetting;
8357                            bp.perm = p;
8358                            bp.uid = pkg.applicationInfo.uid;
8359                            bp.sourcePackage = p.info.packageName;
8360                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8361                        } else if (!currentOwnerIsSystem) {
8362                            String msg = "New decl " + p.owner + " of permission  "
8363                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8364                            reportSettingsProblem(Log.WARN, msg);
8365                            bp = null;
8366                        }
8367                    }
8368                }
8369
8370                if (bp == null) {
8371                    bp = new BasePermission(p.info.name, p.info.packageName,
8372                            BasePermission.TYPE_NORMAL);
8373                    permissionMap.put(p.info.name, bp);
8374                }
8375
8376                if (bp.perm == null) {
8377                    if (bp.sourcePackage == null
8378                            || bp.sourcePackage.equals(p.info.packageName)) {
8379                        BasePermission tree = findPermissionTreeLP(p.info.name);
8380                        if (tree == null
8381                                || tree.sourcePackage.equals(p.info.packageName)) {
8382                            bp.packageSetting = pkgSetting;
8383                            bp.perm = p;
8384                            bp.uid = pkg.applicationInfo.uid;
8385                            bp.sourcePackage = p.info.packageName;
8386                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8387                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8388                                if (r == null) {
8389                                    r = new StringBuilder(256);
8390                                } else {
8391                                    r.append(' ');
8392                                }
8393                                r.append(p.info.name);
8394                            }
8395                        } else {
8396                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8397                                    + p.info.packageName + " ignored: base tree "
8398                                    + tree.name + " is from package "
8399                                    + tree.sourcePackage);
8400                        }
8401                    } else {
8402                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8403                                + p.info.packageName + " ignored: original from "
8404                                + bp.sourcePackage);
8405                    }
8406                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8407                    if (r == null) {
8408                        r = new StringBuilder(256);
8409                    } else {
8410                        r.append(' ');
8411                    }
8412                    r.append("DUP:");
8413                    r.append(p.info.name);
8414                }
8415                if (bp.perm == p) {
8416                    bp.protectionLevel = p.info.protectionLevel;
8417                }
8418            }
8419
8420            if (r != null) {
8421                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8422            }
8423
8424            N = pkg.instrumentation.size();
8425            r = null;
8426            for (i=0; i<N; i++) {
8427                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8428                a.info.packageName = pkg.applicationInfo.packageName;
8429                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8430                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8431                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8432                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8433                a.info.dataDir = pkg.applicationInfo.dataDir;
8434                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8435                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8436
8437                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8438                // need other information about the application, like the ABI and what not ?
8439                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8440                mInstrumentation.put(a.getComponentName(), a);
8441                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8442                    if (r == null) {
8443                        r = new StringBuilder(256);
8444                    } else {
8445                        r.append(' ');
8446                    }
8447                    r.append(a.info.name);
8448                }
8449            }
8450            if (r != null) {
8451                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8452            }
8453
8454            if (pkg.protectedBroadcasts != null) {
8455                N = pkg.protectedBroadcasts.size();
8456                for (i=0; i<N; i++) {
8457                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8458                }
8459            }
8460
8461            pkgSetting.setTimeStamp(scanFileTime);
8462
8463            // Create idmap files for pairs of (packages, overlay packages).
8464            // Note: "android", ie framework-res.apk, is handled by native layers.
8465            if (pkg.mOverlayTarget != null) {
8466                // This is an overlay package.
8467                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8468                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8469                        mOverlays.put(pkg.mOverlayTarget,
8470                                new ArrayMap<String, PackageParser.Package>());
8471                    }
8472                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8473                    map.put(pkg.packageName, pkg);
8474                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8475                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8476                        createIdmapFailed = true;
8477                    }
8478                }
8479            } else if (mOverlays.containsKey(pkg.packageName) &&
8480                    !pkg.packageName.equals("android")) {
8481                // This is a regular package, with one or more known overlay packages.
8482                createIdmapsForPackageLI(pkg);
8483            }
8484        }
8485
8486        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8487
8488        if (createIdmapFailed) {
8489            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8490                    "scanPackageLI failed to createIdmap");
8491        }
8492        return pkg;
8493    }
8494
8495    /**
8496     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8497     * is derived purely on the basis of the contents of {@code scanFile} and
8498     * {@code cpuAbiOverride}.
8499     *
8500     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8501     */
8502    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8503                                 String cpuAbiOverride, boolean extractLibs)
8504            throws PackageManagerException {
8505        // TODO: We can probably be smarter about this stuff. For installed apps,
8506        // we can calculate this information at install time once and for all. For
8507        // system apps, we can probably assume that this information doesn't change
8508        // after the first boot scan. As things stand, we do lots of unnecessary work.
8509
8510        // Give ourselves some initial paths; we'll come back for another
8511        // pass once we've determined ABI below.
8512        setNativeLibraryPaths(pkg);
8513
8514        // We would never need to extract libs for forward-locked and external packages,
8515        // since the container service will do it for us. We shouldn't attempt to
8516        // extract libs from system app when it was not updated.
8517        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8518                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8519            extractLibs = false;
8520        }
8521
8522        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8523        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8524
8525        NativeLibraryHelper.Handle handle = null;
8526        try {
8527            handle = NativeLibraryHelper.Handle.create(pkg);
8528            // TODO(multiArch): This can be null for apps that didn't go through the
8529            // usual installation process. We can calculate it again, like we
8530            // do during install time.
8531            //
8532            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8533            // unnecessary.
8534            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8535
8536            // Null out the abis so that they can be recalculated.
8537            pkg.applicationInfo.primaryCpuAbi = null;
8538            pkg.applicationInfo.secondaryCpuAbi = null;
8539            if (isMultiArch(pkg.applicationInfo)) {
8540                // Warn if we've set an abiOverride for multi-lib packages..
8541                // By definition, we need to copy both 32 and 64 bit libraries for
8542                // such packages.
8543                if (pkg.cpuAbiOverride != null
8544                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8545                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8546                }
8547
8548                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8549                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8550                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8551                    if (extractLibs) {
8552                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8553                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8554                                useIsaSpecificSubdirs);
8555                    } else {
8556                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8557                    }
8558                }
8559
8560                maybeThrowExceptionForMultiArchCopy(
8561                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8562
8563                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8564                    if (extractLibs) {
8565                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8566                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8567                                useIsaSpecificSubdirs);
8568                    } else {
8569                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8570                    }
8571                }
8572
8573                maybeThrowExceptionForMultiArchCopy(
8574                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8575
8576                if (abi64 >= 0) {
8577                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8578                }
8579
8580                if (abi32 >= 0) {
8581                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8582                    if (abi64 >= 0) {
8583                        if (cpuAbiOverride == null && pkg.use32bitAbi) {
8584                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8585                            pkg.applicationInfo.primaryCpuAbi = abi;
8586                        } else {
8587                            pkg.applicationInfo.secondaryCpuAbi = abi;
8588                        }
8589                    } else {
8590                        pkg.applicationInfo.primaryCpuAbi = abi;
8591                    }
8592                }
8593
8594            } else {
8595                String[] abiList = (cpuAbiOverride != null) ?
8596                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8597
8598                // Enable gross and lame hacks for apps that are built with old
8599                // SDK tools. We must scan their APKs for renderscript bitcode and
8600                // not launch them if it's present. Don't bother checking on devices
8601                // that don't have 64 bit support.
8602                boolean needsRenderScriptOverride = false;
8603                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8604                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8605                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8606                    needsRenderScriptOverride = true;
8607                }
8608
8609                final int copyRet;
8610                if (extractLibs) {
8611                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8612                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8613                } else {
8614                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8615                }
8616
8617                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8618                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8619                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8620                }
8621
8622                if (copyRet >= 0) {
8623                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8624                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8625                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8626                } else if (needsRenderScriptOverride) {
8627                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8628                }
8629            }
8630        } catch (IOException ioe) {
8631            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8632        } finally {
8633            IoUtils.closeQuietly(handle);
8634        }
8635
8636        // Now that we've calculated the ABIs and determined if it's an internal app,
8637        // we will go ahead and populate the nativeLibraryPath.
8638        setNativeLibraryPaths(pkg);
8639    }
8640
8641    /**
8642     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8643     * i.e, so that all packages can be run inside a single process if required.
8644     *
8645     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8646     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8647     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8648     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8649     * updating a package that belongs to a shared user.
8650     *
8651     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8652     * adds unnecessary complexity.
8653     */
8654    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8655            PackageParser.Package scannedPackage, boolean bootComplete) {
8656        String requiredInstructionSet = null;
8657        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8658            requiredInstructionSet = VMRuntime.getInstructionSet(
8659                     scannedPackage.applicationInfo.primaryCpuAbi);
8660        }
8661
8662        PackageSetting requirer = null;
8663        for (PackageSetting ps : packagesForUser) {
8664            // If packagesForUser contains scannedPackage, we skip it. This will happen
8665            // when scannedPackage is an update of an existing package. Without this check,
8666            // we will never be able to change the ABI of any package belonging to a shared
8667            // user, even if it's compatible with other packages.
8668            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8669                if (ps.primaryCpuAbiString == null) {
8670                    continue;
8671                }
8672
8673                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8674                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8675                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8676                    // this but there's not much we can do.
8677                    String errorMessage = "Instruction set mismatch, "
8678                            + ((requirer == null) ? "[caller]" : requirer)
8679                            + " requires " + requiredInstructionSet + " whereas " + ps
8680                            + " requires " + instructionSet;
8681                    Slog.w(TAG, errorMessage);
8682                }
8683
8684                if (requiredInstructionSet == null) {
8685                    requiredInstructionSet = instructionSet;
8686                    requirer = ps;
8687                }
8688            }
8689        }
8690
8691        if (requiredInstructionSet != null) {
8692            String adjustedAbi;
8693            if (requirer != null) {
8694                // requirer != null implies that either scannedPackage was null or that scannedPackage
8695                // did not require an ABI, in which case we have to adjust scannedPackage to match
8696                // the ABI of the set (which is the same as requirer's ABI)
8697                adjustedAbi = requirer.primaryCpuAbiString;
8698                if (scannedPackage != null) {
8699                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8700                }
8701            } else {
8702                // requirer == null implies that we're updating all ABIs in the set to
8703                // match scannedPackage.
8704                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8705            }
8706
8707            for (PackageSetting ps : packagesForUser) {
8708                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8709                    if (ps.primaryCpuAbiString != null) {
8710                        continue;
8711                    }
8712
8713                    ps.primaryCpuAbiString = adjustedAbi;
8714                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8715                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8716                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8717                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8718                                + " (requirer="
8719                                + (requirer == null ? "null" : requirer.pkg.packageName)
8720                                + ", scannedPackage="
8721                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8722                                + ")");
8723                        try {
8724                            mInstaller.rmdex(ps.codePathString,
8725                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8726                        } catch (InstallerException ignored) {
8727                        }
8728                    }
8729                }
8730            }
8731        }
8732    }
8733
8734    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8735        synchronized (mPackages) {
8736            mResolverReplaced = true;
8737            // Set up information for custom user intent resolution activity.
8738            mResolveActivity.applicationInfo = pkg.applicationInfo;
8739            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8740            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8741            mResolveActivity.processName = pkg.applicationInfo.packageName;
8742            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8743            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8744                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8745            mResolveActivity.theme = 0;
8746            mResolveActivity.exported = true;
8747            mResolveActivity.enabled = true;
8748            mResolveInfo.activityInfo = mResolveActivity;
8749            mResolveInfo.priority = 0;
8750            mResolveInfo.preferredOrder = 0;
8751            mResolveInfo.match = 0;
8752            mResolveComponentName = mCustomResolverComponentName;
8753            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8754                    mResolveComponentName);
8755        }
8756    }
8757
8758    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8759        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8760
8761        // Set up information for ephemeral installer activity
8762        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8763        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8764        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8765        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8766        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8767        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8768                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8769        mEphemeralInstallerActivity.theme = 0;
8770        mEphemeralInstallerActivity.exported = true;
8771        mEphemeralInstallerActivity.enabled = true;
8772        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8773        mEphemeralInstallerInfo.priority = 0;
8774        mEphemeralInstallerInfo.preferredOrder = 0;
8775        mEphemeralInstallerInfo.match = 0;
8776
8777        if (DEBUG_EPHEMERAL) {
8778            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8779        }
8780    }
8781
8782    private static String calculateBundledApkRoot(final String codePathString) {
8783        final File codePath = new File(codePathString);
8784        final File codeRoot;
8785        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8786            codeRoot = Environment.getRootDirectory();
8787        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8788            codeRoot = Environment.getOemDirectory();
8789        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8790            codeRoot = Environment.getVendorDirectory();
8791        } else {
8792            // Unrecognized code path; take its top real segment as the apk root:
8793            // e.g. /something/app/blah.apk => /something
8794            try {
8795                File f = codePath.getCanonicalFile();
8796                File parent = f.getParentFile();    // non-null because codePath is a file
8797                File tmp;
8798                while ((tmp = parent.getParentFile()) != null) {
8799                    f = parent;
8800                    parent = tmp;
8801                }
8802                codeRoot = f;
8803                Slog.w(TAG, "Unrecognized code path "
8804                        + codePath + " - using " + codeRoot);
8805            } catch (IOException e) {
8806                // Can't canonicalize the code path -- shenanigans?
8807                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8808                return Environment.getRootDirectory().getPath();
8809            }
8810        }
8811        return codeRoot.getPath();
8812    }
8813
8814    /**
8815     * Derive and set the location of native libraries for the given package,
8816     * which varies depending on where and how the package was installed.
8817     */
8818    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8819        final ApplicationInfo info = pkg.applicationInfo;
8820        final String codePath = pkg.codePath;
8821        final File codeFile = new File(codePath);
8822        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8823        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8824
8825        info.nativeLibraryRootDir = null;
8826        info.nativeLibraryRootRequiresIsa = false;
8827        info.nativeLibraryDir = null;
8828        info.secondaryNativeLibraryDir = null;
8829
8830        if (isApkFile(codeFile)) {
8831            // Monolithic install
8832            if (bundledApp) {
8833                // If "/system/lib64/apkname" exists, assume that is the per-package
8834                // native library directory to use; otherwise use "/system/lib/apkname".
8835                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8836                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8837                        getPrimaryInstructionSet(info));
8838
8839                // This is a bundled system app so choose the path based on the ABI.
8840                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8841                // is just the default path.
8842                final String apkName = deriveCodePathName(codePath);
8843                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8844                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8845                        apkName).getAbsolutePath();
8846
8847                if (info.secondaryCpuAbi != null) {
8848                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8849                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8850                            secondaryLibDir, apkName).getAbsolutePath();
8851                }
8852            } else if (asecApp) {
8853                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8854                        .getAbsolutePath();
8855            } else {
8856                final String apkName = deriveCodePathName(codePath);
8857                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8858                        .getAbsolutePath();
8859            }
8860
8861            info.nativeLibraryRootRequiresIsa = false;
8862            info.nativeLibraryDir = info.nativeLibraryRootDir;
8863        } else {
8864            // Cluster install
8865            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8866            info.nativeLibraryRootRequiresIsa = true;
8867
8868            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8869                    getPrimaryInstructionSet(info)).getAbsolutePath();
8870
8871            if (info.secondaryCpuAbi != null) {
8872                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8873                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8874            }
8875        }
8876    }
8877
8878    /**
8879     * Calculate the abis and roots for a bundled app. These can uniquely
8880     * be determined from the contents of the system partition, i.e whether
8881     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8882     * of this information, and instead assume that the system was built
8883     * sensibly.
8884     */
8885    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8886                                           PackageSetting pkgSetting) {
8887        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8888
8889        // If "/system/lib64/apkname" exists, assume that is the per-package
8890        // native library directory to use; otherwise use "/system/lib/apkname".
8891        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8892        setBundledAppAbi(pkg, apkRoot, apkName);
8893        // pkgSetting might be null during rescan following uninstall of updates
8894        // to a bundled app, so accommodate that possibility.  The settings in
8895        // that case will be established later from the parsed package.
8896        //
8897        // If the settings aren't null, sync them up with what we've just derived.
8898        // note that apkRoot isn't stored in the package settings.
8899        if (pkgSetting != null) {
8900            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8901            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8902        }
8903    }
8904
8905    /**
8906     * Deduces the ABI of a bundled app and sets the relevant fields on the
8907     * parsed pkg object.
8908     *
8909     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8910     *        under which system libraries are installed.
8911     * @param apkName the name of the installed package.
8912     */
8913    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8914        final File codeFile = new File(pkg.codePath);
8915
8916        final boolean has64BitLibs;
8917        final boolean has32BitLibs;
8918        if (isApkFile(codeFile)) {
8919            // Monolithic install
8920            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8921            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8922        } else {
8923            // Cluster install
8924            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8925            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8926                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8927                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8928                has64BitLibs = (new File(rootDir, isa)).exists();
8929            } else {
8930                has64BitLibs = false;
8931            }
8932            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8933                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8934                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8935                has32BitLibs = (new File(rootDir, isa)).exists();
8936            } else {
8937                has32BitLibs = false;
8938            }
8939        }
8940
8941        if (has64BitLibs && !has32BitLibs) {
8942            // The package has 64 bit libs, but not 32 bit libs. Its primary
8943            // ABI should be 64 bit. We can safely assume here that the bundled
8944            // native libraries correspond to the most preferred ABI in the list.
8945
8946            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8947            pkg.applicationInfo.secondaryCpuAbi = null;
8948        } else if (has32BitLibs && !has64BitLibs) {
8949            // The package has 32 bit libs but not 64 bit libs. Its primary
8950            // ABI should be 32 bit.
8951
8952            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8953            pkg.applicationInfo.secondaryCpuAbi = null;
8954        } else if (has32BitLibs && has64BitLibs) {
8955            // The application has both 64 and 32 bit bundled libraries. We check
8956            // here that the app declares multiArch support, and warn if it doesn't.
8957            //
8958            // We will be lenient here and record both ABIs. The primary will be the
8959            // ABI that's higher on the list, i.e, a device that's configured to prefer
8960            // 64 bit apps will see a 64 bit primary ABI,
8961
8962            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8963                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8964            }
8965
8966            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8967                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8968                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8969            } else {
8970                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8971                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8972            }
8973        } else {
8974            pkg.applicationInfo.primaryCpuAbi = null;
8975            pkg.applicationInfo.secondaryCpuAbi = null;
8976        }
8977    }
8978
8979    private void killPackage(PackageParser.Package pkg, String reason) {
8980        // Kill the parent package
8981        killApplication(pkg.packageName, pkg.applicationInfo.uid, reason);
8982        // Kill the child packages
8983        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8984        for (int i = 0; i < childCount; i++) {
8985            PackageParser.Package childPkg = pkg.childPackages.get(i);
8986            killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason);
8987        }
8988    }
8989
8990    private void killApplication(String pkgName, int appId, String reason) {
8991        // Request the ActivityManager to kill the process(only for existing packages)
8992        // so that we do not end up in a confused state while the user is still using the older
8993        // version of the application while the new one gets installed.
8994        IActivityManager am = ActivityManagerNative.getDefault();
8995        if (am != null) {
8996            try {
8997                am.killApplicationWithAppId(pkgName, appId, reason);
8998            } catch (RemoteException e) {
8999            }
9000        }
9001    }
9002
9003    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9004        // Remove the parent package setting
9005        PackageSetting ps = (PackageSetting) pkg.mExtras;
9006        if (ps != null) {
9007            removePackageLI(ps, chatty);
9008        }
9009        // Remove the child package setting
9010        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9011        for (int i = 0; i < childCount; i++) {
9012            PackageParser.Package childPkg = pkg.childPackages.get(i);
9013            ps = (PackageSetting) childPkg.mExtras;
9014            if (ps != null) {
9015                removePackageLI(ps, chatty);
9016            }
9017        }
9018    }
9019
9020    void removePackageLI(PackageSetting ps, boolean chatty) {
9021        if (DEBUG_INSTALL) {
9022            if (chatty)
9023                Log.d(TAG, "Removing package " + ps.name);
9024        }
9025
9026        // writer
9027        synchronized (mPackages) {
9028            mPackages.remove(ps.name);
9029            final PackageParser.Package pkg = ps.pkg;
9030            if (pkg != null) {
9031                cleanPackageDataStructuresLILPw(pkg, chatty);
9032            }
9033        }
9034    }
9035
9036    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9037        if (DEBUG_INSTALL) {
9038            if (chatty)
9039                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9040        }
9041
9042        // writer
9043        synchronized (mPackages) {
9044            // Remove the parent package
9045            mPackages.remove(pkg.applicationInfo.packageName);
9046            cleanPackageDataStructuresLILPw(pkg, chatty);
9047
9048            // Remove the child packages
9049            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9050            for (int i = 0; i < childCount; i++) {
9051                PackageParser.Package childPkg = pkg.childPackages.get(i);
9052                mPackages.remove(childPkg.applicationInfo.packageName);
9053                cleanPackageDataStructuresLILPw(childPkg, chatty);
9054            }
9055        }
9056    }
9057
9058    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9059        int N = pkg.providers.size();
9060        StringBuilder r = null;
9061        int i;
9062        for (i=0; i<N; i++) {
9063            PackageParser.Provider p = pkg.providers.get(i);
9064            mProviders.removeProvider(p);
9065            if (p.info.authority == null) {
9066
9067                /* There was another ContentProvider with this authority when
9068                 * this app was installed so this authority is null,
9069                 * Ignore it as we don't have to unregister the provider.
9070                 */
9071                continue;
9072            }
9073            String names[] = p.info.authority.split(";");
9074            for (int j = 0; j < names.length; j++) {
9075                if (mProvidersByAuthority.get(names[j]) == p) {
9076                    mProvidersByAuthority.remove(names[j]);
9077                    if (DEBUG_REMOVE) {
9078                        if (chatty)
9079                            Log.d(TAG, "Unregistered content provider: " + names[j]
9080                                    + ", className = " + p.info.name + ", isSyncable = "
9081                                    + p.info.isSyncable);
9082                    }
9083                }
9084            }
9085            if (DEBUG_REMOVE && chatty) {
9086                if (r == null) {
9087                    r = new StringBuilder(256);
9088                } else {
9089                    r.append(' ');
9090                }
9091                r.append(p.info.name);
9092            }
9093        }
9094        if (r != null) {
9095            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9096        }
9097
9098        N = pkg.services.size();
9099        r = null;
9100        for (i=0; i<N; i++) {
9101            PackageParser.Service s = pkg.services.get(i);
9102            mServices.removeService(s);
9103            if (chatty) {
9104                if (r == null) {
9105                    r = new StringBuilder(256);
9106                } else {
9107                    r.append(' ');
9108                }
9109                r.append(s.info.name);
9110            }
9111        }
9112        if (r != null) {
9113            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9114        }
9115
9116        N = pkg.receivers.size();
9117        r = null;
9118        for (i=0; i<N; i++) {
9119            PackageParser.Activity a = pkg.receivers.get(i);
9120            mReceivers.removeActivity(a, "receiver");
9121            if (DEBUG_REMOVE && chatty) {
9122                if (r == null) {
9123                    r = new StringBuilder(256);
9124                } else {
9125                    r.append(' ');
9126                }
9127                r.append(a.info.name);
9128            }
9129        }
9130        if (r != null) {
9131            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9132        }
9133
9134        N = pkg.activities.size();
9135        r = null;
9136        for (i=0; i<N; i++) {
9137            PackageParser.Activity a = pkg.activities.get(i);
9138            mActivities.removeActivity(a, "activity");
9139            if (DEBUG_REMOVE && chatty) {
9140                if (r == null) {
9141                    r = new StringBuilder(256);
9142                } else {
9143                    r.append(' ');
9144                }
9145                r.append(a.info.name);
9146            }
9147        }
9148        if (r != null) {
9149            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9150        }
9151
9152        N = pkg.permissions.size();
9153        r = null;
9154        for (i=0; i<N; i++) {
9155            PackageParser.Permission p = pkg.permissions.get(i);
9156            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9157            if (bp == null) {
9158                bp = mSettings.mPermissionTrees.get(p.info.name);
9159            }
9160            if (bp != null && bp.perm == p) {
9161                bp.perm = null;
9162                if (DEBUG_REMOVE && chatty) {
9163                    if (r == null) {
9164                        r = new StringBuilder(256);
9165                    } else {
9166                        r.append(' ');
9167                    }
9168                    r.append(p.info.name);
9169                }
9170            }
9171            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9172                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9173                if (appOpPkgs != null) {
9174                    appOpPkgs.remove(pkg.packageName);
9175                }
9176            }
9177        }
9178        if (r != null) {
9179            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9180        }
9181
9182        N = pkg.requestedPermissions.size();
9183        r = null;
9184        for (i=0; i<N; i++) {
9185            String perm = pkg.requestedPermissions.get(i);
9186            BasePermission bp = mSettings.mPermissions.get(perm);
9187            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9188                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9189                if (appOpPkgs != null) {
9190                    appOpPkgs.remove(pkg.packageName);
9191                    if (appOpPkgs.isEmpty()) {
9192                        mAppOpPermissionPackages.remove(perm);
9193                    }
9194                }
9195            }
9196        }
9197        if (r != null) {
9198            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9199        }
9200
9201        N = pkg.instrumentation.size();
9202        r = null;
9203        for (i=0; i<N; i++) {
9204            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9205            mInstrumentation.remove(a.getComponentName());
9206            if (DEBUG_REMOVE && chatty) {
9207                if (r == null) {
9208                    r = new StringBuilder(256);
9209                } else {
9210                    r.append(' ');
9211                }
9212                r.append(a.info.name);
9213            }
9214        }
9215        if (r != null) {
9216            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9217        }
9218
9219        r = null;
9220        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9221            // Only system apps can hold shared libraries.
9222            if (pkg.libraryNames != null) {
9223                for (i=0; i<pkg.libraryNames.size(); i++) {
9224                    String name = pkg.libraryNames.get(i);
9225                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9226                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9227                        mSharedLibraries.remove(name);
9228                        if (DEBUG_REMOVE && chatty) {
9229                            if (r == null) {
9230                                r = new StringBuilder(256);
9231                            } else {
9232                                r.append(' ');
9233                            }
9234                            r.append(name);
9235                        }
9236                    }
9237                }
9238            }
9239        }
9240        if (r != null) {
9241            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9242        }
9243    }
9244
9245    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9246        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9247            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9248                return true;
9249            }
9250        }
9251        return false;
9252    }
9253
9254    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9255    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9256    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9257
9258    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9259        // Update the parent permissions
9260        updatePermissionsLPw(pkg.packageName, pkg, flags);
9261        // Update the child permissions
9262        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9263        for (int i = 0; i < childCount; i++) {
9264            PackageParser.Package childPkg = pkg.childPackages.get(i);
9265            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9266        }
9267    }
9268
9269    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9270            int flags) {
9271        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9272        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9273    }
9274
9275    private void updatePermissionsLPw(String changingPkg,
9276            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9277        // Make sure there are no dangling permission trees.
9278        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9279        while (it.hasNext()) {
9280            final BasePermission bp = it.next();
9281            if (bp.packageSetting == null) {
9282                // We may not yet have parsed the package, so just see if
9283                // we still know about its settings.
9284                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9285            }
9286            if (bp.packageSetting == null) {
9287                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9288                        + " from package " + bp.sourcePackage);
9289                it.remove();
9290            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9291                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9292                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9293                            + " from package " + bp.sourcePackage);
9294                    flags |= UPDATE_PERMISSIONS_ALL;
9295                    it.remove();
9296                }
9297            }
9298        }
9299
9300        // Make sure all dynamic permissions have been assigned to a package,
9301        // and make sure there are no dangling permissions.
9302        it = mSettings.mPermissions.values().iterator();
9303        while (it.hasNext()) {
9304            final BasePermission bp = it.next();
9305            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9306                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9307                        + bp.name + " pkg=" + bp.sourcePackage
9308                        + " info=" + bp.pendingInfo);
9309                if (bp.packageSetting == null && bp.pendingInfo != null) {
9310                    final BasePermission tree = findPermissionTreeLP(bp.name);
9311                    if (tree != null && tree.perm != null) {
9312                        bp.packageSetting = tree.packageSetting;
9313                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9314                                new PermissionInfo(bp.pendingInfo));
9315                        bp.perm.info.packageName = tree.perm.info.packageName;
9316                        bp.perm.info.name = bp.name;
9317                        bp.uid = tree.uid;
9318                    }
9319                }
9320            }
9321            if (bp.packageSetting == null) {
9322                // We may not yet have parsed the package, so just see if
9323                // we still know about its settings.
9324                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9325            }
9326            if (bp.packageSetting == null) {
9327                Slog.w(TAG, "Removing dangling permission: " + bp.name
9328                        + " from package " + bp.sourcePackage);
9329                it.remove();
9330            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9331                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9332                    Slog.i(TAG, "Removing old permission: " + bp.name
9333                            + " from package " + bp.sourcePackage);
9334                    flags |= UPDATE_PERMISSIONS_ALL;
9335                    it.remove();
9336                }
9337            }
9338        }
9339
9340        // Now update the permissions for all packages, in particular
9341        // replace the granted permissions of the system packages.
9342        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9343            for (PackageParser.Package pkg : mPackages.values()) {
9344                if (pkg != pkgInfo) {
9345                    // Only replace for packages on requested volume
9346                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9347                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9348                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9349                    grantPermissionsLPw(pkg, replace, changingPkg);
9350                }
9351            }
9352        }
9353
9354        if (pkgInfo != null) {
9355            // Only replace for packages on requested volume
9356            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9357            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9358                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9359            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9360        }
9361    }
9362
9363    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9364            String packageOfInterest) {
9365        // IMPORTANT: There are two types of permissions: install and runtime.
9366        // Install time permissions are granted when the app is installed to
9367        // all device users and users added in the future. Runtime permissions
9368        // are granted at runtime explicitly to specific users. Normal and signature
9369        // protected permissions are install time permissions. Dangerous permissions
9370        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9371        // otherwise they are runtime permissions. This function does not manage
9372        // runtime permissions except for the case an app targeting Lollipop MR1
9373        // being upgraded to target a newer SDK, in which case dangerous permissions
9374        // are transformed from install time to runtime ones.
9375
9376        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9377        if (ps == null) {
9378            return;
9379        }
9380
9381        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9382
9383        PermissionsState permissionsState = ps.getPermissionsState();
9384        PermissionsState origPermissions = permissionsState;
9385
9386        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9387
9388        boolean runtimePermissionsRevoked = false;
9389        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9390
9391        boolean changedInstallPermission = false;
9392
9393        if (replace) {
9394            ps.installPermissionsFixed = false;
9395            if (!ps.isSharedUser()) {
9396                origPermissions = new PermissionsState(permissionsState);
9397                permissionsState.reset();
9398            } else {
9399                // We need to know only about runtime permission changes since the
9400                // calling code always writes the install permissions state but
9401                // the runtime ones are written only if changed. The only cases of
9402                // changed runtime permissions here are promotion of an install to
9403                // runtime and revocation of a runtime from a shared user.
9404                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9405                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9406                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9407                    runtimePermissionsRevoked = true;
9408                }
9409            }
9410        }
9411
9412        permissionsState.setGlobalGids(mGlobalGids);
9413
9414        final int N = pkg.requestedPermissions.size();
9415        for (int i=0; i<N; i++) {
9416            final String name = pkg.requestedPermissions.get(i);
9417            final BasePermission bp = mSettings.mPermissions.get(name);
9418
9419            if (DEBUG_INSTALL) {
9420                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9421            }
9422
9423            if (bp == null || bp.packageSetting == null) {
9424                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9425                    Slog.w(TAG, "Unknown permission " + name
9426                            + " in package " + pkg.packageName);
9427                }
9428                continue;
9429            }
9430
9431            final String perm = bp.name;
9432            boolean allowedSig = false;
9433            int grant = GRANT_DENIED;
9434
9435            // Keep track of app op permissions.
9436            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9437                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9438                if (pkgs == null) {
9439                    pkgs = new ArraySet<>();
9440                    mAppOpPermissionPackages.put(bp.name, pkgs);
9441                }
9442                pkgs.add(pkg.packageName);
9443            }
9444
9445            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9446            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9447                    >= Build.VERSION_CODES.M;
9448            switch (level) {
9449                case PermissionInfo.PROTECTION_NORMAL: {
9450                    // For all apps normal permissions are install time ones.
9451                    grant = GRANT_INSTALL;
9452                } break;
9453
9454                case PermissionInfo.PROTECTION_DANGEROUS: {
9455                    // If a permission review is required for legacy apps we represent
9456                    // their permissions as always granted runtime ones since we need
9457                    // to keep the review required permission flag per user while an
9458                    // install permission's state is shared across all users.
9459                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9460                        // For legacy apps dangerous permissions are install time ones.
9461                        grant = GRANT_INSTALL;
9462                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9463                        // For legacy apps that became modern, install becomes runtime.
9464                        grant = GRANT_UPGRADE;
9465                    } else if (mPromoteSystemApps
9466                            && isSystemApp(ps)
9467                            && mExistingSystemPackages.contains(ps.name)) {
9468                        // For legacy system apps, install becomes runtime.
9469                        // We cannot check hasInstallPermission() for system apps since those
9470                        // permissions were granted implicitly and not persisted pre-M.
9471                        grant = GRANT_UPGRADE;
9472                    } else {
9473                        // For modern apps keep runtime permissions unchanged.
9474                        grant = GRANT_RUNTIME;
9475                    }
9476                } break;
9477
9478                case PermissionInfo.PROTECTION_SIGNATURE: {
9479                    // For all apps signature permissions are install time ones.
9480                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9481                    if (allowedSig) {
9482                        grant = GRANT_INSTALL;
9483                    }
9484                } break;
9485            }
9486
9487            if (DEBUG_INSTALL) {
9488                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9489            }
9490
9491            if (grant != GRANT_DENIED) {
9492                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9493                    // If this is an existing, non-system package, then
9494                    // we can't add any new permissions to it.
9495                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9496                        // Except...  if this is a permission that was added
9497                        // to the platform (note: need to only do this when
9498                        // updating the platform).
9499                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9500                            grant = GRANT_DENIED;
9501                        }
9502                    }
9503                }
9504
9505                switch (grant) {
9506                    case GRANT_INSTALL: {
9507                        // Revoke this as runtime permission to handle the case of
9508                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9509                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9510                            if (origPermissions.getRuntimePermissionState(
9511                                    bp.name, userId) != null) {
9512                                // Revoke the runtime permission and clear the flags.
9513                                origPermissions.revokeRuntimePermission(bp, userId);
9514                                origPermissions.updatePermissionFlags(bp, userId,
9515                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9516                                // If we revoked a permission permission, we have to write.
9517                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9518                                        changedRuntimePermissionUserIds, userId);
9519                            }
9520                        }
9521                        // Grant an install permission.
9522                        if (permissionsState.grantInstallPermission(bp) !=
9523                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9524                            changedInstallPermission = true;
9525                        }
9526                    } break;
9527
9528                    case GRANT_RUNTIME: {
9529                        // Grant previously granted runtime permissions.
9530                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9531                            PermissionState permissionState = origPermissions
9532                                    .getRuntimePermissionState(bp.name, userId);
9533                            int flags = permissionState != null
9534                                    ? permissionState.getFlags() : 0;
9535                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9536                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9537                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9538                                    // If we cannot put the permission as it was, we have to write.
9539                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9540                                            changedRuntimePermissionUserIds, userId);
9541                                }
9542                                // If the app supports runtime permissions no need for a review.
9543                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9544                                        && appSupportsRuntimePermissions
9545                                        && (flags & PackageManager
9546                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9547                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9548                                    // Since we changed the flags, we have to write.
9549                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9550                                            changedRuntimePermissionUserIds, userId);
9551                                }
9552                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9553                                    && !appSupportsRuntimePermissions) {
9554                                // For legacy apps that need a permission review, every new
9555                                // runtime permission is granted but it is pending a review.
9556                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9557                                    permissionsState.grantRuntimePermission(bp, userId);
9558                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9559                                    // We changed the permission and flags, hence have to write.
9560                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9561                                            changedRuntimePermissionUserIds, userId);
9562                                }
9563                            }
9564                            // Propagate the permission flags.
9565                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9566                        }
9567                    } break;
9568
9569                    case GRANT_UPGRADE: {
9570                        // Grant runtime permissions for a previously held install permission.
9571                        PermissionState permissionState = origPermissions
9572                                .getInstallPermissionState(bp.name);
9573                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9574
9575                        if (origPermissions.revokeInstallPermission(bp)
9576                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9577                            // We will be transferring the permission flags, so clear them.
9578                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9579                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9580                            changedInstallPermission = true;
9581                        }
9582
9583                        // If the permission is not to be promoted to runtime we ignore it and
9584                        // also its other flags as they are not applicable to install permissions.
9585                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9586                            for (int userId : currentUserIds) {
9587                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9588                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9589                                    // Transfer the permission flags.
9590                                    permissionsState.updatePermissionFlags(bp, userId,
9591                                            flags, flags);
9592                                    // If we granted the permission, we have to write.
9593                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9594                                            changedRuntimePermissionUserIds, userId);
9595                                }
9596                            }
9597                        }
9598                    } break;
9599
9600                    default: {
9601                        if (packageOfInterest == null
9602                                || packageOfInterest.equals(pkg.packageName)) {
9603                            Slog.w(TAG, "Not granting permission " + perm
9604                                    + " to package " + pkg.packageName
9605                                    + " because it was previously installed without");
9606                        }
9607                    } break;
9608                }
9609            } else {
9610                if (permissionsState.revokeInstallPermission(bp) !=
9611                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9612                    // Also drop the permission flags.
9613                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9614                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9615                    changedInstallPermission = true;
9616                    Slog.i(TAG, "Un-granting permission " + perm
9617                            + " from package " + pkg.packageName
9618                            + " (protectionLevel=" + bp.protectionLevel
9619                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9620                            + ")");
9621                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9622                    // Don't print warning for app op permissions, since it is fine for them
9623                    // not to be granted, there is a UI for the user to decide.
9624                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9625                        Slog.w(TAG, "Not granting permission " + perm
9626                                + " to package " + pkg.packageName
9627                                + " (protectionLevel=" + bp.protectionLevel
9628                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9629                                + ")");
9630                    }
9631                }
9632            }
9633        }
9634
9635        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9636                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9637            // This is the first that we have heard about this package, so the
9638            // permissions we have now selected are fixed until explicitly
9639            // changed.
9640            ps.installPermissionsFixed = true;
9641        }
9642
9643        // Persist the runtime permissions state for users with changes. If permissions
9644        // were revoked because no app in the shared user declares them we have to
9645        // write synchronously to avoid losing runtime permissions state.
9646        for (int userId : changedRuntimePermissionUserIds) {
9647            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9648        }
9649
9650        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9651    }
9652
9653    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9654        boolean allowed = false;
9655        final int NP = PackageParser.NEW_PERMISSIONS.length;
9656        for (int ip=0; ip<NP; ip++) {
9657            final PackageParser.NewPermissionInfo npi
9658                    = PackageParser.NEW_PERMISSIONS[ip];
9659            if (npi.name.equals(perm)
9660                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9661                allowed = true;
9662                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9663                        + pkg.packageName);
9664                break;
9665            }
9666        }
9667        return allowed;
9668    }
9669
9670    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9671            BasePermission bp, PermissionsState origPermissions) {
9672        boolean allowed;
9673        allowed = (compareSignatures(
9674                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9675                        == PackageManager.SIGNATURE_MATCH)
9676                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9677                        == PackageManager.SIGNATURE_MATCH);
9678        if (!allowed && (bp.protectionLevel
9679                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9680            if (isSystemApp(pkg)) {
9681                // For updated system applications, a system permission
9682                // is granted only if it had been defined by the original application.
9683                if (pkg.isUpdatedSystemApp()) {
9684                    final PackageSetting sysPs = mSettings
9685                            .getDisabledSystemPkgLPr(pkg.packageName);
9686                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9687                        // If the original was granted this permission, we take
9688                        // that grant decision as read and propagate it to the
9689                        // update.
9690                        if (sysPs.isPrivileged()) {
9691                            allowed = true;
9692                        }
9693                    } else {
9694                        // The system apk may have been updated with an older
9695                        // version of the one on the data partition, but which
9696                        // granted a new system permission that it didn't have
9697                        // before.  In this case we do want to allow the app to
9698                        // now get the new permission if the ancestral apk is
9699                        // privileged to get it.
9700                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9701                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9702                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9703                                    allowed = true;
9704                                    break;
9705                                }
9706                            }
9707                        }
9708                        // Also if a privileged parent package on the system image or any of
9709                        // its children requested a privileged permission, the updated child
9710                        // packages can also get the permission.
9711                        if (pkg.parentPackage != null) {
9712                            final PackageSetting disabledSysParentPs = mSettings
9713                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9714                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9715                                    && disabledSysParentPs.isPrivileged()) {
9716                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9717                                    allowed = true;
9718                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9719                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9720                                    for (int i = 0; i < count; i++) {
9721                                        PackageParser.Package disabledSysChildPkg =
9722                                                disabledSysParentPs.pkg.childPackages.get(i);
9723                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9724                                                perm)) {
9725                                            allowed = true;
9726                                            break;
9727                                        }
9728                                    }
9729                                }
9730                            }
9731                        }
9732                    }
9733                } else {
9734                    allowed = isPrivilegedApp(pkg);
9735                }
9736            }
9737        }
9738        if (!allowed) {
9739            if (!allowed && (bp.protectionLevel
9740                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9741                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9742                // If this was a previously normal/dangerous permission that got moved
9743                // to a system permission as part of the runtime permission redesign, then
9744                // we still want to blindly grant it to old apps.
9745                allowed = true;
9746            }
9747            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9748                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9749                // If this permission is to be granted to the system installer and
9750                // this app is an installer, then it gets the permission.
9751                allowed = true;
9752            }
9753            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9754                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9755                // If this permission is to be granted to the system verifier and
9756                // this app is a verifier, then it gets the permission.
9757                allowed = true;
9758            }
9759            if (!allowed && (bp.protectionLevel
9760                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9761                    && isSystemApp(pkg)) {
9762                // Any pre-installed system app is allowed to get this permission.
9763                allowed = true;
9764            }
9765            if (!allowed && (bp.protectionLevel
9766                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9767                // For development permissions, a development permission
9768                // is granted only if it was already granted.
9769                allowed = origPermissions.hasInstallPermission(perm);
9770            }
9771            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
9772                    && pkg.packageName.equals(mSetupWizardPackage)) {
9773                // If this permission is to be granted to the system setup wizard and
9774                // this app is a setup wizard, then it gets the permission.
9775                allowed = true;
9776            }
9777        }
9778        return allowed;
9779    }
9780
9781    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
9782        final int permCount = pkg.requestedPermissions.size();
9783        for (int j = 0; j < permCount; j++) {
9784            String requestedPermission = pkg.requestedPermissions.get(j);
9785            if (permission.equals(requestedPermission)) {
9786                return true;
9787            }
9788        }
9789        return false;
9790    }
9791
9792    final class ActivityIntentResolver
9793            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9794        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9795                boolean defaultOnly, int userId) {
9796            if (!sUserManager.exists(userId)) return null;
9797            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9798            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9799        }
9800
9801        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9802                int userId) {
9803            if (!sUserManager.exists(userId)) return null;
9804            mFlags = flags;
9805            return super.queryIntent(intent, resolvedType,
9806                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9807        }
9808
9809        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9810                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9811            if (!sUserManager.exists(userId)) return null;
9812            if (packageActivities == null) {
9813                return null;
9814            }
9815            mFlags = flags;
9816            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9817            final int N = packageActivities.size();
9818            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9819                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9820
9821            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9822            for (int i = 0; i < N; ++i) {
9823                intentFilters = packageActivities.get(i).intents;
9824                if (intentFilters != null && intentFilters.size() > 0) {
9825                    PackageParser.ActivityIntentInfo[] array =
9826                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9827                    intentFilters.toArray(array);
9828                    listCut.add(array);
9829                }
9830            }
9831            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9832        }
9833
9834        /**
9835         * Finds a privileged activity that matches the specified activity names.
9836         */
9837        private PackageParser.Activity findMatchingActivity(
9838                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
9839            for (PackageParser.Activity sysActivity : activityList) {
9840                if (sysActivity.info.name.equals(activityInfo.name)) {
9841                    return sysActivity;
9842                }
9843                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
9844                    return sysActivity;
9845                }
9846                if (sysActivity.info.targetActivity != null) {
9847                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
9848                        return sysActivity;
9849                    }
9850                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
9851                        return sysActivity;
9852                    }
9853                }
9854            }
9855            return null;
9856        }
9857
9858        public class IterGenerator<E> {
9859            public Iterator<E> generate(ActivityIntentInfo info) {
9860                return null;
9861            }
9862        }
9863
9864        public class ActionIterGenerator extends IterGenerator<String> {
9865            @Override
9866            public Iterator<String> generate(ActivityIntentInfo info) {
9867                return info.actionsIterator();
9868            }
9869        }
9870
9871        public class CategoriesIterGenerator extends IterGenerator<String> {
9872            @Override
9873            public Iterator<String> generate(ActivityIntentInfo info) {
9874                return info.categoriesIterator();
9875            }
9876        }
9877
9878        public class SchemesIterGenerator extends IterGenerator<String> {
9879            @Override
9880            public Iterator<String> generate(ActivityIntentInfo info) {
9881                return info.schemesIterator();
9882            }
9883        }
9884
9885        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
9886            @Override
9887            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
9888                return info.authoritiesIterator();
9889            }
9890        }
9891
9892        /**
9893         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
9894         * MODIFIED. Do not pass in a list that should not be changed.
9895         */
9896        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
9897                IterGenerator<T> generator, Iterator<T> searchIterator) {
9898            // loop through the set of actions; every one must be found in the intent filter
9899            while (searchIterator.hasNext()) {
9900                // we must have at least one filter in the list to consider a match
9901                if (intentList.size() == 0) {
9902                    break;
9903                }
9904
9905                final T searchAction = searchIterator.next();
9906
9907                // loop through the set of intent filters
9908                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
9909                while (intentIter.hasNext()) {
9910                    final ActivityIntentInfo intentInfo = intentIter.next();
9911                    boolean selectionFound = false;
9912
9913                    // loop through the intent filter's selection criteria; at least one
9914                    // of them must match the searched criteria
9915                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
9916                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
9917                        final T intentSelection = intentSelectionIter.next();
9918                        if (intentSelection != null && intentSelection.equals(searchAction)) {
9919                            selectionFound = true;
9920                            break;
9921                        }
9922                    }
9923
9924                    // the selection criteria wasn't found in this filter's set; this filter
9925                    // is not a potential match
9926                    if (!selectionFound) {
9927                        intentIter.remove();
9928                    }
9929                }
9930            }
9931        }
9932
9933        private boolean isProtectedAction(ActivityIntentInfo filter) {
9934            final Iterator<String> actionsIter = filter.actionsIterator();
9935            while (actionsIter != null && actionsIter.hasNext()) {
9936                final String filterAction = actionsIter.next();
9937                if (PROTECTED_ACTIONS.contains(filterAction)) {
9938                    return true;
9939                }
9940            }
9941            return false;
9942        }
9943
9944        /**
9945         * Adjusts the priority of the given intent filter according to policy.
9946         * <p>
9947         * <ul>
9948         * <li>The priority for non privileged applications is capped to '0'</li>
9949         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
9950         * <li>The priority for unbundled updates to privileged applications is capped to the
9951         *      priority defined on the system partition</li>
9952         * </ul>
9953         * <p>
9954         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
9955         * allowed to obtain any priority on any action.
9956         */
9957        private void adjustPriority(
9958                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
9959            // nothing to do; priority is fine as-is
9960            if (intent.getPriority() <= 0) {
9961                return;
9962            }
9963
9964            final ActivityInfo activityInfo = intent.activity.info;
9965            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
9966
9967            final boolean privilegedApp =
9968                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
9969            if (!privilegedApp) {
9970                // non-privileged applications can never define a priority >0
9971                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
9972                        + " package: " + applicationInfo.packageName
9973                        + " activity: " + intent.activity.className
9974                        + " origPrio: " + intent.getPriority());
9975                intent.setPriority(0);
9976                return;
9977            }
9978
9979            if (systemActivities == null) {
9980                // the system package is not disabled; we're parsing the system partition
9981                if (isProtectedAction(intent)) {
9982                    if (mDeferProtectedFilters) {
9983                        // We can't deal with these just yet. No component should ever obtain a
9984                        // >0 priority for a protected actions, with ONE exception -- the setup
9985                        // wizard. The setup wizard, however, cannot be known until we're able to
9986                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
9987                        // until all intent filters have been processed. Chicken, meet egg.
9988                        // Let the filter temporarily have a high priority and rectify the
9989                        // priorities after all system packages have been scanned.
9990                        mProtectedFilters.add(intent);
9991                        if (DEBUG_FILTERS) {
9992                            Slog.i(TAG, "Protected action; save for later;"
9993                                    + " package: " + applicationInfo.packageName
9994                                    + " activity: " + intent.activity.className
9995                                    + " origPrio: " + intent.getPriority());
9996                        }
9997                        return;
9998                    } else {
9999                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10000                            Slog.i(TAG, "No setup wizard;"
10001                                + " All protected intents capped to priority 0");
10002                        }
10003                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10004                            if (DEBUG_FILTERS) {
10005                                Slog.i(TAG, "Found setup wizard;"
10006                                    + " allow priority " + intent.getPriority() + ";"
10007                                    + " package: " + intent.activity.info.packageName
10008                                    + " activity: " + intent.activity.className
10009                                    + " priority: " + intent.getPriority());
10010                            }
10011                            // setup wizard gets whatever it wants
10012                            return;
10013                        }
10014                        Slog.w(TAG, "Protected action; cap priority to 0;"
10015                                + " package: " + intent.activity.info.packageName
10016                                + " activity: " + intent.activity.className
10017                                + " origPrio: " + intent.getPriority());
10018                        intent.setPriority(0);
10019                        return;
10020                    }
10021                }
10022                // privileged apps on the system image get whatever priority they request
10023                return;
10024            }
10025
10026            // privileged app unbundled update ... try to find the same activity
10027            final PackageParser.Activity foundActivity =
10028                    findMatchingActivity(systemActivities, activityInfo);
10029            if (foundActivity == null) {
10030                // this is a new activity; it cannot obtain >0 priority
10031                if (DEBUG_FILTERS) {
10032                    Slog.i(TAG, "New activity; cap priority to 0;"
10033                            + " package: " + applicationInfo.packageName
10034                            + " activity: " + intent.activity.className
10035                            + " origPrio: " + intent.getPriority());
10036                }
10037                intent.setPriority(0);
10038                return;
10039            }
10040
10041            // found activity, now check for filter equivalence
10042
10043            // a shallow copy is enough; we modify the list, not its contents
10044            final List<ActivityIntentInfo> intentListCopy =
10045                    new ArrayList<>(foundActivity.intents);
10046            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10047
10048            // find matching action subsets
10049            final Iterator<String> actionsIterator = intent.actionsIterator();
10050            if (actionsIterator != null) {
10051                getIntentListSubset(
10052                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10053                if (intentListCopy.size() == 0) {
10054                    // no more intents to match; we're not equivalent
10055                    if (DEBUG_FILTERS) {
10056                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10057                                + " package: " + applicationInfo.packageName
10058                                + " activity: " + intent.activity.className
10059                                + " origPrio: " + intent.getPriority());
10060                    }
10061                    intent.setPriority(0);
10062                    return;
10063                }
10064            }
10065
10066            // find matching category subsets
10067            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10068            if (categoriesIterator != null) {
10069                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10070                        categoriesIterator);
10071                if (intentListCopy.size() == 0) {
10072                    // no more intents to match; we're not equivalent
10073                    if (DEBUG_FILTERS) {
10074                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10075                                + " package: " + applicationInfo.packageName
10076                                + " activity: " + intent.activity.className
10077                                + " origPrio: " + intent.getPriority());
10078                    }
10079                    intent.setPriority(0);
10080                    return;
10081                }
10082            }
10083
10084            // find matching schemes subsets
10085            final Iterator<String> schemesIterator = intent.schemesIterator();
10086            if (schemesIterator != null) {
10087                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10088                        schemesIterator);
10089                if (intentListCopy.size() == 0) {
10090                    // no more intents to match; we're not equivalent
10091                    if (DEBUG_FILTERS) {
10092                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10093                                + " package: " + applicationInfo.packageName
10094                                + " activity: " + intent.activity.className
10095                                + " origPrio: " + intent.getPriority());
10096                    }
10097                    intent.setPriority(0);
10098                    return;
10099                }
10100            }
10101
10102            // find matching authorities subsets
10103            final Iterator<IntentFilter.AuthorityEntry>
10104                    authoritiesIterator = intent.authoritiesIterator();
10105            if (authoritiesIterator != null) {
10106                getIntentListSubset(intentListCopy,
10107                        new AuthoritiesIterGenerator(),
10108                        authoritiesIterator);
10109                if (intentListCopy.size() == 0) {
10110                    // no more intents to match; we're not equivalent
10111                    if (DEBUG_FILTERS) {
10112                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10113                                + " package: " + applicationInfo.packageName
10114                                + " activity: " + intent.activity.className
10115                                + " origPrio: " + intent.getPriority());
10116                    }
10117                    intent.setPriority(0);
10118                    return;
10119                }
10120            }
10121
10122            // we found matching filter(s); app gets the max priority of all intents
10123            int cappedPriority = 0;
10124            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10125                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10126            }
10127            if (intent.getPriority() > cappedPriority) {
10128                if (DEBUG_FILTERS) {
10129                    Slog.i(TAG, "Found matching filter(s);"
10130                            + " cap priority to " + cappedPriority + ";"
10131                            + " package: " + applicationInfo.packageName
10132                            + " activity: " + intent.activity.className
10133                            + " origPrio: " + intent.getPriority());
10134                }
10135                intent.setPriority(cappedPriority);
10136                return;
10137            }
10138            // all this for nothing; the requested priority was <= what was on the system
10139        }
10140
10141        public final void addActivity(PackageParser.Activity a, String type) {
10142            mActivities.put(a.getComponentName(), a);
10143            if (DEBUG_SHOW_INFO)
10144                Log.v(
10145                TAG, "  " + type + " " +
10146                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10147            if (DEBUG_SHOW_INFO)
10148                Log.v(TAG, "    Class=" + a.info.name);
10149            final int NI = a.intents.size();
10150            for (int j=0; j<NI; j++) {
10151                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10152                if ("activity".equals(type)) {
10153                    final PackageSetting ps =
10154                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10155                    final List<PackageParser.Activity> systemActivities =
10156                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10157                    adjustPriority(systemActivities, intent);
10158                }
10159                if (DEBUG_SHOW_INFO) {
10160                    Log.v(TAG, "    IntentFilter:");
10161                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10162                }
10163                if (!intent.debugCheck()) {
10164                    Log.w(TAG, "==> For Activity " + a.info.name);
10165                }
10166                addFilter(intent);
10167            }
10168        }
10169
10170        public final void removeActivity(PackageParser.Activity a, String type) {
10171            mActivities.remove(a.getComponentName());
10172            if (DEBUG_SHOW_INFO) {
10173                Log.v(TAG, "  " + type + " "
10174                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10175                                : a.info.name) + ":");
10176                Log.v(TAG, "    Class=" + a.info.name);
10177            }
10178            final int NI = a.intents.size();
10179            for (int j=0; j<NI; j++) {
10180                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10181                if (DEBUG_SHOW_INFO) {
10182                    Log.v(TAG, "    IntentFilter:");
10183                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10184                }
10185                removeFilter(intent);
10186            }
10187        }
10188
10189        @Override
10190        protected boolean allowFilterResult(
10191                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10192            ActivityInfo filterAi = filter.activity.info;
10193            for (int i=dest.size()-1; i>=0; i--) {
10194                ActivityInfo destAi = dest.get(i).activityInfo;
10195                if (destAi.name == filterAi.name
10196                        && destAi.packageName == filterAi.packageName) {
10197                    return false;
10198                }
10199            }
10200            return true;
10201        }
10202
10203        @Override
10204        protected ActivityIntentInfo[] newArray(int size) {
10205            return new ActivityIntentInfo[size];
10206        }
10207
10208        @Override
10209        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10210            if (!sUserManager.exists(userId)) return true;
10211            PackageParser.Package p = filter.activity.owner;
10212            if (p != null) {
10213                PackageSetting ps = (PackageSetting)p.mExtras;
10214                if (ps != null) {
10215                    // System apps are never considered stopped for purposes of
10216                    // filtering, because there may be no way for the user to
10217                    // actually re-launch them.
10218                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10219                            && ps.getStopped(userId);
10220                }
10221            }
10222            return false;
10223        }
10224
10225        @Override
10226        protected boolean isPackageForFilter(String packageName,
10227                PackageParser.ActivityIntentInfo info) {
10228            return packageName.equals(info.activity.owner.packageName);
10229        }
10230
10231        @Override
10232        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10233                int match, int userId) {
10234            if (!sUserManager.exists(userId)) return null;
10235            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10236                return null;
10237            }
10238            final PackageParser.Activity activity = info.activity;
10239            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10240            if (ps == null) {
10241                return null;
10242            }
10243            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10244                    ps.readUserState(userId), userId);
10245            if (ai == null) {
10246                return null;
10247            }
10248            final ResolveInfo res = new ResolveInfo();
10249            res.activityInfo = ai;
10250            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10251                res.filter = info;
10252            }
10253            if (info != null) {
10254                res.handleAllWebDataURI = info.handleAllWebDataURI();
10255            }
10256            res.priority = info.getPriority();
10257            res.preferredOrder = activity.owner.mPreferredOrder;
10258            //System.out.println("Result: " + res.activityInfo.className +
10259            //                   " = " + res.priority);
10260            res.match = match;
10261            res.isDefault = info.hasDefault;
10262            res.labelRes = info.labelRes;
10263            res.nonLocalizedLabel = info.nonLocalizedLabel;
10264            if (userNeedsBadging(userId)) {
10265                res.noResourceId = true;
10266            } else {
10267                res.icon = info.icon;
10268            }
10269            res.iconResourceId = info.icon;
10270            res.system = res.activityInfo.applicationInfo.isSystemApp();
10271            return res;
10272        }
10273
10274        @Override
10275        protected void sortResults(List<ResolveInfo> results) {
10276            Collections.sort(results, mResolvePrioritySorter);
10277        }
10278
10279        @Override
10280        protected void dumpFilter(PrintWriter out, String prefix,
10281                PackageParser.ActivityIntentInfo filter) {
10282            out.print(prefix); out.print(
10283                    Integer.toHexString(System.identityHashCode(filter.activity)));
10284                    out.print(' ');
10285                    filter.activity.printComponentShortName(out);
10286                    out.print(" filter ");
10287                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10288        }
10289
10290        @Override
10291        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10292            return filter.activity;
10293        }
10294
10295        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10296            PackageParser.Activity activity = (PackageParser.Activity)label;
10297            out.print(prefix); out.print(
10298                    Integer.toHexString(System.identityHashCode(activity)));
10299                    out.print(' ');
10300                    activity.printComponentShortName(out);
10301            if (count > 1) {
10302                out.print(" ("); out.print(count); out.print(" filters)");
10303            }
10304            out.println();
10305        }
10306
10307        // Keys are String (activity class name), values are Activity.
10308        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10309                = new ArrayMap<ComponentName, PackageParser.Activity>();
10310        private int mFlags;
10311    }
10312
10313    private final class ServiceIntentResolver
10314            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10315        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10316                boolean defaultOnly, int userId) {
10317            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10318            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10319        }
10320
10321        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10322                int userId) {
10323            if (!sUserManager.exists(userId)) return null;
10324            mFlags = flags;
10325            return super.queryIntent(intent, resolvedType,
10326                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10327        }
10328
10329        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10330                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10331            if (!sUserManager.exists(userId)) return null;
10332            if (packageServices == null) {
10333                return null;
10334            }
10335            mFlags = flags;
10336            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10337            final int N = packageServices.size();
10338            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10339                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10340
10341            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10342            for (int i = 0; i < N; ++i) {
10343                intentFilters = packageServices.get(i).intents;
10344                if (intentFilters != null && intentFilters.size() > 0) {
10345                    PackageParser.ServiceIntentInfo[] array =
10346                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10347                    intentFilters.toArray(array);
10348                    listCut.add(array);
10349                }
10350            }
10351            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10352        }
10353
10354        public final void addService(PackageParser.Service s) {
10355            mServices.put(s.getComponentName(), s);
10356            if (DEBUG_SHOW_INFO) {
10357                Log.v(TAG, "  "
10358                        + (s.info.nonLocalizedLabel != null
10359                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10360                Log.v(TAG, "    Class=" + s.info.name);
10361            }
10362            final int NI = s.intents.size();
10363            int j;
10364            for (j=0; j<NI; j++) {
10365                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10366                if (DEBUG_SHOW_INFO) {
10367                    Log.v(TAG, "    IntentFilter:");
10368                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10369                }
10370                if (!intent.debugCheck()) {
10371                    Log.w(TAG, "==> For Service " + s.info.name);
10372                }
10373                addFilter(intent);
10374            }
10375        }
10376
10377        public final void removeService(PackageParser.Service s) {
10378            mServices.remove(s.getComponentName());
10379            if (DEBUG_SHOW_INFO) {
10380                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10381                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10382                Log.v(TAG, "    Class=" + s.info.name);
10383            }
10384            final int NI = s.intents.size();
10385            int j;
10386            for (j=0; j<NI; j++) {
10387                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10388                if (DEBUG_SHOW_INFO) {
10389                    Log.v(TAG, "    IntentFilter:");
10390                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10391                }
10392                removeFilter(intent);
10393            }
10394        }
10395
10396        @Override
10397        protected boolean allowFilterResult(
10398                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10399            ServiceInfo filterSi = filter.service.info;
10400            for (int i=dest.size()-1; i>=0; i--) {
10401                ServiceInfo destAi = dest.get(i).serviceInfo;
10402                if (destAi.name == filterSi.name
10403                        && destAi.packageName == filterSi.packageName) {
10404                    return false;
10405                }
10406            }
10407            return true;
10408        }
10409
10410        @Override
10411        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10412            return new PackageParser.ServiceIntentInfo[size];
10413        }
10414
10415        @Override
10416        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10417            if (!sUserManager.exists(userId)) return true;
10418            PackageParser.Package p = filter.service.owner;
10419            if (p != null) {
10420                PackageSetting ps = (PackageSetting)p.mExtras;
10421                if (ps != null) {
10422                    // System apps are never considered stopped for purposes of
10423                    // filtering, because there may be no way for the user to
10424                    // actually re-launch them.
10425                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10426                            && ps.getStopped(userId);
10427                }
10428            }
10429            return false;
10430        }
10431
10432        @Override
10433        protected boolean isPackageForFilter(String packageName,
10434                PackageParser.ServiceIntentInfo info) {
10435            return packageName.equals(info.service.owner.packageName);
10436        }
10437
10438        @Override
10439        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10440                int match, int userId) {
10441            if (!sUserManager.exists(userId)) return null;
10442            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10443            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10444                return null;
10445            }
10446            final PackageParser.Service service = info.service;
10447            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10448            if (ps == null) {
10449                return null;
10450            }
10451            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10452                    ps.readUserState(userId), userId);
10453            if (si == null) {
10454                return null;
10455            }
10456            final ResolveInfo res = new ResolveInfo();
10457            res.serviceInfo = si;
10458            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10459                res.filter = filter;
10460            }
10461            res.priority = info.getPriority();
10462            res.preferredOrder = service.owner.mPreferredOrder;
10463            res.match = match;
10464            res.isDefault = info.hasDefault;
10465            res.labelRes = info.labelRes;
10466            res.nonLocalizedLabel = info.nonLocalizedLabel;
10467            res.icon = info.icon;
10468            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10469            return res;
10470        }
10471
10472        @Override
10473        protected void sortResults(List<ResolveInfo> results) {
10474            Collections.sort(results, mResolvePrioritySorter);
10475        }
10476
10477        @Override
10478        protected void dumpFilter(PrintWriter out, String prefix,
10479                PackageParser.ServiceIntentInfo filter) {
10480            out.print(prefix); out.print(
10481                    Integer.toHexString(System.identityHashCode(filter.service)));
10482                    out.print(' ');
10483                    filter.service.printComponentShortName(out);
10484                    out.print(" filter ");
10485                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10486        }
10487
10488        @Override
10489        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10490            return filter.service;
10491        }
10492
10493        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10494            PackageParser.Service service = (PackageParser.Service)label;
10495            out.print(prefix); out.print(
10496                    Integer.toHexString(System.identityHashCode(service)));
10497                    out.print(' ');
10498                    service.printComponentShortName(out);
10499            if (count > 1) {
10500                out.print(" ("); out.print(count); out.print(" filters)");
10501            }
10502            out.println();
10503        }
10504
10505//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10506//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10507//            final List<ResolveInfo> retList = Lists.newArrayList();
10508//            while (i.hasNext()) {
10509//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10510//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10511//                    retList.add(resolveInfo);
10512//                }
10513//            }
10514//            return retList;
10515//        }
10516
10517        // Keys are String (activity class name), values are Activity.
10518        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10519                = new ArrayMap<ComponentName, PackageParser.Service>();
10520        private int mFlags;
10521    };
10522
10523    private final class ProviderIntentResolver
10524            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10525        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10526                boolean defaultOnly, int userId) {
10527            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10528            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10529        }
10530
10531        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10532                int userId) {
10533            if (!sUserManager.exists(userId))
10534                return null;
10535            mFlags = flags;
10536            return super.queryIntent(intent, resolvedType,
10537                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10538        }
10539
10540        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10541                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10542            if (!sUserManager.exists(userId))
10543                return null;
10544            if (packageProviders == null) {
10545                return null;
10546            }
10547            mFlags = flags;
10548            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10549            final int N = packageProviders.size();
10550            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10551                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10552
10553            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10554            for (int i = 0; i < N; ++i) {
10555                intentFilters = packageProviders.get(i).intents;
10556                if (intentFilters != null && intentFilters.size() > 0) {
10557                    PackageParser.ProviderIntentInfo[] array =
10558                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10559                    intentFilters.toArray(array);
10560                    listCut.add(array);
10561                }
10562            }
10563            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10564        }
10565
10566        public final void addProvider(PackageParser.Provider p) {
10567            if (mProviders.containsKey(p.getComponentName())) {
10568                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10569                return;
10570            }
10571
10572            mProviders.put(p.getComponentName(), p);
10573            if (DEBUG_SHOW_INFO) {
10574                Log.v(TAG, "  "
10575                        + (p.info.nonLocalizedLabel != null
10576                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10577                Log.v(TAG, "    Class=" + p.info.name);
10578            }
10579            final int NI = p.intents.size();
10580            int j;
10581            for (j = 0; j < NI; j++) {
10582                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10583                if (DEBUG_SHOW_INFO) {
10584                    Log.v(TAG, "    IntentFilter:");
10585                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10586                }
10587                if (!intent.debugCheck()) {
10588                    Log.w(TAG, "==> For Provider " + p.info.name);
10589                }
10590                addFilter(intent);
10591            }
10592        }
10593
10594        public final void removeProvider(PackageParser.Provider p) {
10595            mProviders.remove(p.getComponentName());
10596            if (DEBUG_SHOW_INFO) {
10597                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10598                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10599                Log.v(TAG, "    Class=" + p.info.name);
10600            }
10601            final int NI = p.intents.size();
10602            int j;
10603            for (j = 0; j < NI; j++) {
10604                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10605                if (DEBUG_SHOW_INFO) {
10606                    Log.v(TAG, "    IntentFilter:");
10607                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10608                }
10609                removeFilter(intent);
10610            }
10611        }
10612
10613        @Override
10614        protected boolean allowFilterResult(
10615                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10616            ProviderInfo filterPi = filter.provider.info;
10617            for (int i = dest.size() - 1; i >= 0; i--) {
10618                ProviderInfo destPi = dest.get(i).providerInfo;
10619                if (destPi.name == filterPi.name
10620                        && destPi.packageName == filterPi.packageName) {
10621                    return false;
10622                }
10623            }
10624            return true;
10625        }
10626
10627        @Override
10628        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10629            return new PackageParser.ProviderIntentInfo[size];
10630        }
10631
10632        @Override
10633        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10634            if (!sUserManager.exists(userId))
10635                return true;
10636            PackageParser.Package p = filter.provider.owner;
10637            if (p != null) {
10638                PackageSetting ps = (PackageSetting) p.mExtras;
10639                if (ps != null) {
10640                    // System apps are never considered stopped for purposes of
10641                    // filtering, because there may be no way for the user to
10642                    // actually re-launch them.
10643                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10644                            && ps.getStopped(userId);
10645                }
10646            }
10647            return false;
10648        }
10649
10650        @Override
10651        protected boolean isPackageForFilter(String packageName,
10652                PackageParser.ProviderIntentInfo info) {
10653            return packageName.equals(info.provider.owner.packageName);
10654        }
10655
10656        @Override
10657        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10658                int match, int userId) {
10659            if (!sUserManager.exists(userId))
10660                return null;
10661            final PackageParser.ProviderIntentInfo info = filter;
10662            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10663                return null;
10664            }
10665            final PackageParser.Provider provider = info.provider;
10666            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10667            if (ps == null) {
10668                return null;
10669            }
10670            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10671                    ps.readUserState(userId), userId);
10672            if (pi == null) {
10673                return null;
10674            }
10675            final ResolveInfo res = new ResolveInfo();
10676            res.providerInfo = pi;
10677            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10678                res.filter = filter;
10679            }
10680            res.priority = info.getPriority();
10681            res.preferredOrder = provider.owner.mPreferredOrder;
10682            res.match = match;
10683            res.isDefault = info.hasDefault;
10684            res.labelRes = info.labelRes;
10685            res.nonLocalizedLabel = info.nonLocalizedLabel;
10686            res.icon = info.icon;
10687            res.system = res.providerInfo.applicationInfo.isSystemApp();
10688            return res;
10689        }
10690
10691        @Override
10692        protected void sortResults(List<ResolveInfo> results) {
10693            Collections.sort(results, mResolvePrioritySorter);
10694        }
10695
10696        @Override
10697        protected void dumpFilter(PrintWriter out, String prefix,
10698                PackageParser.ProviderIntentInfo filter) {
10699            out.print(prefix);
10700            out.print(
10701                    Integer.toHexString(System.identityHashCode(filter.provider)));
10702            out.print(' ');
10703            filter.provider.printComponentShortName(out);
10704            out.print(" filter ");
10705            out.println(Integer.toHexString(System.identityHashCode(filter)));
10706        }
10707
10708        @Override
10709        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10710            return filter.provider;
10711        }
10712
10713        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10714            PackageParser.Provider provider = (PackageParser.Provider)label;
10715            out.print(prefix); out.print(
10716                    Integer.toHexString(System.identityHashCode(provider)));
10717                    out.print(' ');
10718                    provider.printComponentShortName(out);
10719            if (count > 1) {
10720                out.print(" ("); out.print(count); out.print(" filters)");
10721            }
10722            out.println();
10723        }
10724
10725        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10726                = new ArrayMap<ComponentName, PackageParser.Provider>();
10727        private int mFlags;
10728    }
10729
10730    private static final class EphemeralIntentResolver
10731            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10732        @Override
10733        protected EphemeralResolveIntentInfo[] newArray(int size) {
10734            return new EphemeralResolveIntentInfo[size];
10735        }
10736
10737        @Override
10738        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10739            return true;
10740        }
10741
10742        @Override
10743        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10744                int userId) {
10745            if (!sUserManager.exists(userId)) {
10746                return null;
10747            }
10748            return info.getEphemeralResolveInfo();
10749        }
10750    }
10751
10752    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10753            new Comparator<ResolveInfo>() {
10754        public int compare(ResolveInfo r1, ResolveInfo r2) {
10755            int v1 = r1.priority;
10756            int v2 = r2.priority;
10757            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10758            if (v1 != v2) {
10759                return (v1 > v2) ? -1 : 1;
10760            }
10761            v1 = r1.preferredOrder;
10762            v2 = r2.preferredOrder;
10763            if (v1 != v2) {
10764                return (v1 > v2) ? -1 : 1;
10765            }
10766            if (r1.isDefault != r2.isDefault) {
10767                return r1.isDefault ? -1 : 1;
10768            }
10769            v1 = r1.match;
10770            v2 = r2.match;
10771            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
10772            if (v1 != v2) {
10773                return (v1 > v2) ? -1 : 1;
10774            }
10775            if (r1.system != r2.system) {
10776                return r1.system ? -1 : 1;
10777            }
10778            if (r1.activityInfo != null) {
10779                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
10780            }
10781            if (r1.serviceInfo != null) {
10782                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
10783            }
10784            if (r1.providerInfo != null) {
10785                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
10786            }
10787            return 0;
10788        }
10789    };
10790
10791    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
10792            new Comparator<ProviderInfo>() {
10793        public int compare(ProviderInfo p1, ProviderInfo p2) {
10794            final int v1 = p1.initOrder;
10795            final int v2 = p2.initOrder;
10796            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
10797        }
10798    };
10799
10800    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
10801            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
10802            final int[] userIds) {
10803        mHandler.post(new Runnable() {
10804            @Override
10805            public void run() {
10806                try {
10807                    final IActivityManager am = ActivityManagerNative.getDefault();
10808                    if (am == null) return;
10809                    final int[] resolvedUserIds;
10810                    if (userIds == null) {
10811                        resolvedUserIds = am.getRunningUserIds();
10812                    } else {
10813                        resolvedUserIds = userIds;
10814                    }
10815                    for (int id : resolvedUserIds) {
10816                        final Intent intent = new Intent(action,
10817                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
10818                        if (extras != null) {
10819                            intent.putExtras(extras);
10820                        }
10821                        if (targetPkg != null) {
10822                            intent.setPackage(targetPkg);
10823                        }
10824                        // Modify the UID when posting to other users
10825                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
10826                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
10827                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
10828                            intent.putExtra(Intent.EXTRA_UID, uid);
10829                        }
10830                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
10831                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
10832                        if (DEBUG_BROADCASTS) {
10833                            RuntimeException here = new RuntimeException("here");
10834                            here.fillInStackTrace();
10835                            Slog.d(TAG, "Sending to user " + id + ": "
10836                                    + intent.toShortString(false, true, false, false)
10837                                    + " " + intent.getExtras(), here);
10838                        }
10839                        am.broadcastIntent(null, intent, null, finishedReceiver,
10840                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
10841                                null, finishedReceiver != null, false, id);
10842                    }
10843                } catch (RemoteException ex) {
10844                }
10845            }
10846        });
10847    }
10848
10849    /**
10850     * Check if the external storage media is available. This is true if there
10851     * is a mounted external storage medium or if the external storage is
10852     * emulated.
10853     */
10854    private boolean isExternalMediaAvailable() {
10855        return mMediaMounted || Environment.isExternalStorageEmulated();
10856    }
10857
10858    @Override
10859    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
10860        // writer
10861        synchronized (mPackages) {
10862            if (!isExternalMediaAvailable()) {
10863                // If the external storage is no longer mounted at this point,
10864                // the caller may not have been able to delete all of this
10865                // packages files and can not delete any more.  Bail.
10866                return null;
10867            }
10868            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
10869            if (lastPackage != null) {
10870                pkgs.remove(lastPackage);
10871            }
10872            if (pkgs.size() > 0) {
10873                return pkgs.get(0);
10874            }
10875        }
10876        return null;
10877    }
10878
10879    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
10880        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
10881                userId, andCode ? 1 : 0, packageName);
10882        if (mSystemReady) {
10883            msg.sendToTarget();
10884        } else {
10885            if (mPostSystemReadyMessages == null) {
10886                mPostSystemReadyMessages = new ArrayList<>();
10887            }
10888            mPostSystemReadyMessages.add(msg);
10889        }
10890    }
10891
10892    void startCleaningPackages() {
10893        // reader
10894        if (!isExternalMediaAvailable()) {
10895            return;
10896        }
10897        synchronized (mPackages) {
10898            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
10899                return;
10900            }
10901        }
10902        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
10903        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
10904        IActivityManager am = ActivityManagerNative.getDefault();
10905        if (am != null) {
10906            try {
10907                am.startService(null, intent, null, mContext.getOpPackageName(),
10908                        UserHandle.USER_SYSTEM);
10909            } catch (RemoteException e) {
10910            }
10911        }
10912    }
10913
10914    @Override
10915    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
10916            int installFlags, String installerPackageName, int userId) {
10917        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
10918
10919        final int callingUid = Binder.getCallingUid();
10920        enforceCrossUserPermission(callingUid, userId,
10921                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
10922
10923        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10924            try {
10925                if (observer != null) {
10926                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10927                }
10928            } catch (RemoteException re) {
10929            }
10930            return;
10931        }
10932
10933        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10934            installFlags |= PackageManager.INSTALL_FROM_ADB;
10935
10936        } else {
10937            // Caller holds INSTALL_PACKAGES permission, so we're less strict
10938            // about installerPackageName.
10939
10940            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10941            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10942        }
10943
10944        UserHandle user;
10945        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10946            user = UserHandle.ALL;
10947        } else {
10948            user = new UserHandle(userId);
10949        }
10950
10951        // Only system components can circumvent runtime permissions when installing.
10952        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10953                && mContext.checkCallingOrSelfPermission(Manifest.permission
10954                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10955            throw new SecurityException("You need the "
10956                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10957                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10958        }
10959
10960        final File originFile = new File(originPath);
10961        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10962
10963        final Message msg = mHandler.obtainMessage(INIT_COPY);
10964        final VerificationInfo verificationInfo = new VerificationInfo(
10965                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
10966        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
10967                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
10968                null /*packageAbiOverride*/, null /*grantedPermissions*/,
10969                null /*certificates*/);
10970        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10971        msg.obj = params;
10972
10973        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10974                System.identityHashCode(msg.obj));
10975        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10976                System.identityHashCode(msg.obj));
10977
10978        mHandler.sendMessage(msg);
10979    }
10980
10981    void installStage(String packageName, File stagedDir, String stagedCid,
10982            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10983            String installerPackageName, int installerUid, UserHandle user,
10984            Certificate[][] certificates) {
10985        if (DEBUG_EPHEMERAL) {
10986            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10987                Slog.d(TAG, "Ephemeral install of " + packageName);
10988            }
10989        }
10990        final VerificationInfo verificationInfo = new VerificationInfo(
10991                sessionParams.originatingUri, sessionParams.referrerUri,
10992                sessionParams.originatingUid, installerUid);
10993
10994        final OriginInfo origin;
10995        if (stagedDir != null) {
10996            origin = OriginInfo.fromStagedFile(stagedDir);
10997        } else {
10998            origin = OriginInfo.fromStagedContainer(stagedCid);
10999        }
11000
11001        final Message msg = mHandler.obtainMessage(INIT_COPY);
11002        final InstallParams params = new InstallParams(origin, null, observer,
11003                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11004                verificationInfo, user, sessionParams.abiOverride,
11005                sessionParams.grantedRuntimePermissions, certificates);
11006        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11007        msg.obj = params;
11008
11009        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11010                System.identityHashCode(msg.obj));
11011        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11012                System.identityHashCode(msg.obj));
11013
11014        mHandler.sendMessage(msg);
11015    }
11016
11017    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11018            int userId) {
11019        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11020        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11021    }
11022
11023    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11024            int appId, int userId) {
11025        Bundle extras = new Bundle(1);
11026        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11027
11028        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11029                packageName, extras, 0, null, null, new int[] {userId});
11030        try {
11031            IActivityManager am = ActivityManagerNative.getDefault();
11032            if (isSystem && am.isUserRunning(userId, 0)) {
11033                // The just-installed/enabled app is bundled on the system, so presumed
11034                // to be able to run automatically without needing an explicit launch.
11035                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11036                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11037                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11038                        .setPackage(packageName);
11039                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11040                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11041            }
11042        } catch (RemoteException e) {
11043            // shouldn't happen
11044            Slog.w(TAG, "Unable to bootstrap installed package", e);
11045        }
11046    }
11047
11048    @Override
11049    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11050            int userId) {
11051        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11052        PackageSetting pkgSetting;
11053        final int uid = Binder.getCallingUid();
11054        enforceCrossUserPermission(uid, userId,
11055                true /* requireFullPermission */, true /* checkShell */,
11056                "setApplicationHiddenSetting for user " + userId);
11057
11058        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11059            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11060            return false;
11061        }
11062
11063        long callingId = Binder.clearCallingIdentity();
11064        try {
11065            boolean sendAdded = false;
11066            boolean sendRemoved = false;
11067            // writer
11068            synchronized (mPackages) {
11069                pkgSetting = mSettings.mPackages.get(packageName);
11070                if (pkgSetting == null) {
11071                    return false;
11072                }
11073                if (pkgSetting.getHidden(userId) != hidden) {
11074                    pkgSetting.setHidden(hidden, userId);
11075                    mSettings.writePackageRestrictionsLPr(userId);
11076                    if (hidden) {
11077                        sendRemoved = true;
11078                    } else {
11079                        sendAdded = true;
11080                    }
11081                }
11082            }
11083            if (sendAdded) {
11084                sendPackageAddedForUser(packageName, pkgSetting, userId);
11085                return true;
11086            }
11087            if (sendRemoved) {
11088                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11089                        "hiding pkg");
11090                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11091                return true;
11092            }
11093        } finally {
11094            Binder.restoreCallingIdentity(callingId);
11095        }
11096        return false;
11097    }
11098
11099    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11100            int userId) {
11101        final PackageRemovedInfo info = new PackageRemovedInfo();
11102        info.removedPackage = packageName;
11103        info.removedUsers = new int[] {userId};
11104        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11105        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11106    }
11107
11108    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11109        if (pkgList.length > 0) {
11110            Bundle extras = new Bundle(1);
11111            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11112
11113            sendPackageBroadcast(
11114                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11115                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11116                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11117                    new int[] {userId});
11118        }
11119    }
11120
11121    /**
11122     * Returns true if application is not found or there was an error. Otherwise it returns
11123     * the hidden state of the package for the given user.
11124     */
11125    @Override
11126    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11127        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11128        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11129                true /* requireFullPermission */, false /* checkShell */,
11130                "getApplicationHidden for user " + userId);
11131        PackageSetting pkgSetting;
11132        long callingId = Binder.clearCallingIdentity();
11133        try {
11134            // writer
11135            synchronized (mPackages) {
11136                pkgSetting = mSettings.mPackages.get(packageName);
11137                if (pkgSetting == null) {
11138                    return true;
11139                }
11140                return pkgSetting.getHidden(userId);
11141            }
11142        } finally {
11143            Binder.restoreCallingIdentity(callingId);
11144        }
11145    }
11146
11147    /**
11148     * @hide
11149     */
11150    @Override
11151    public int installExistingPackageAsUser(String packageName, int userId) {
11152        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11153                null);
11154        PackageSetting pkgSetting;
11155        final int uid = Binder.getCallingUid();
11156        enforceCrossUserPermission(uid, userId,
11157                true /* requireFullPermission */, true /* checkShell */,
11158                "installExistingPackage for user " + userId);
11159        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11160            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11161        }
11162
11163        long callingId = Binder.clearCallingIdentity();
11164        try {
11165            boolean installed = false;
11166
11167            // writer
11168            synchronized (mPackages) {
11169                pkgSetting = mSettings.mPackages.get(packageName);
11170                if (pkgSetting == null) {
11171                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11172                }
11173                if (!pkgSetting.getInstalled(userId)) {
11174                    pkgSetting.setInstalled(true, userId);
11175                    pkgSetting.setHidden(false, userId);
11176                    mSettings.writePackageRestrictionsLPr(userId);
11177                    installed = true;
11178                }
11179            }
11180
11181            if (installed) {
11182                if (pkgSetting.pkg != null) {
11183                    prepareAppDataAfterInstall(pkgSetting.pkg);
11184                }
11185                sendPackageAddedForUser(packageName, pkgSetting, userId);
11186            }
11187        } finally {
11188            Binder.restoreCallingIdentity(callingId);
11189        }
11190
11191        return PackageManager.INSTALL_SUCCEEDED;
11192    }
11193
11194    boolean isUserRestricted(int userId, String restrictionKey) {
11195        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11196        if (restrictions.getBoolean(restrictionKey, false)) {
11197            Log.w(TAG, "User is restricted: " + restrictionKey);
11198            return true;
11199        }
11200        return false;
11201    }
11202
11203    @Override
11204    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11205            int userId) {
11206        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11207        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11208                true /* requireFullPermission */, true /* checkShell */,
11209                "setPackagesSuspended for user " + userId);
11210
11211        if (ArrayUtils.isEmpty(packageNames)) {
11212            return packageNames;
11213        }
11214
11215        // List of package names for whom the suspended state has changed.
11216        List<String> changedPackages = new ArrayList<>(packageNames.length);
11217        // List of package names for whom the suspended state is not set as requested in this
11218        // method.
11219        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11220        for (int i = 0; i < packageNames.length; i++) {
11221            String packageName = packageNames[i];
11222            long callingId = Binder.clearCallingIdentity();
11223            try {
11224                boolean changed = false;
11225                final int appId;
11226                synchronized (mPackages) {
11227                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11228                    if (pkgSetting == null) {
11229                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11230                                + "\". Skipping suspending/un-suspending.");
11231                        unactionedPackages.add(packageName);
11232                        continue;
11233                    }
11234                    appId = pkgSetting.appId;
11235                    if (pkgSetting.getSuspended(userId) != suspended) {
11236                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11237                            unactionedPackages.add(packageName);
11238                            continue;
11239                        }
11240                        pkgSetting.setSuspended(suspended, userId);
11241                        mSettings.writePackageRestrictionsLPr(userId);
11242                        changed = true;
11243                        changedPackages.add(packageName);
11244                    }
11245                }
11246
11247                if (changed && suspended) {
11248                    killApplication(packageName, UserHandle.getUid(userId, appId),
11249                            "suspending package");
11250                }
11251            } finally {
11252                Binder.restoreCallingIdentity(callingId);
11253            }
11254        }
11255
11256        if (!changedPackages.isEmpty()) {
11257            sendPackagesSuspendedForUser(changedPackages.toArray(
11258                    new String[changedPackages.size()]), userId, suspended);
11259        }
11260
11261        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11262    }
11263
11264    @Override
11265    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11266        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11267                true /* requireFullPermission */, false /* checkShell */,
11268                "isPackageSuspendedForUser for user " + userId);
11269        synchronized (mPackages) {
11270            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11271            if (pkgSetting == null) {
11272                throw new IllegalArgumentException("Unknown target package: " + packageName);
11273            }
11274            return pkgSetting.getSuspended(userId);
11275        }
11276    }
11277
11278    /**
11279     * TODO: cache and disallow blocking the active dialer.
11280     *
11281     * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions
11282     */
11283    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11284        if (isPackageDeviceAdmin(packageName, userId)) {
11285            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11286                    + "\": has an active device admin");
11287            return false;
11288        }
11289
11290        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11291        if (packageName.equals(activeLauncherPackageName)) {
11292            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11293                    + "\": contains the active launcher");
11294            return false;
11295        }
11296
11297        if (packageName.equals(mRequiredInstallerPackage)) {
11298            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11299                    + "\": required for package installation");
11300            return false;
11301        }
11302
11303        if (packageName.equals(mRequiredVerifierPackage)) {
11304            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11305                    + "\": required for package verification");
11306            return false;
11307        }
11308
11309        final PackageParser.Package pkg = mPackages.get(packageName);
11310        if (pkg != null && isPrivilegedApp(pkg)) {
11311            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11312                    + "\": is a privileged app");
11313            return false;
11314        }
11315
11316        return true;
11317    }
11318
11319    private String getActiveLauncherPackageName(int userId) {
11320        Intent intent = new Intent(Intent.ACTION_MAIN);
11321        intent.addCategory(Intent.CATEGORY_HOME);
11322        ResolveInfo resolveInfo = resolveIntent(
11323                intent,
11324                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11325                PackageManager.MATCH_DEFAULT_ONLY,
11326                userId);
11327
11328        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11329    }
11330
11331    @Override
11332    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11333        mContext.enforceCallingOrSelfPermission(
11334                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11335                "Only package verification agents can verify applications");
11336
11337        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11338        final PackageVerificationResponse response = new PackageVerificationResponse(
11339                verificationCode, Binder.getCallingUid());
11340        msg.arg1 = id;
11341        msg.obj = response;
11342        mHandler.sendMessage(msg);
11343    }
11344
11345    @Override
11346    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11347            long millisecondsToDelay) {
11348        mContext.enforceCallingOrSelfPermission(
11349                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11350                "Only package verification agents can extend verification timeouts");
11351
11352        final PackageVerificationState state = mPendingVerification.get(id);
11353        final PackageVerificationResponse response = new PackageVerificationResponse(
11354                verificationCodeAtTimeout, Binder.getCallingUid());
11355
11356        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11357            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11358        }
11359        if (millisecondsToDelay < 0) {
11360            millisecondsToDelay = 0;
11361        }
11362        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11363                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11364            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11365        }
11366
11367        if ((state != null) && !state.timeoutExtended()) {
11368            state.extendTimeout();
11369
11370            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11371            msg.arg1 = id;
11372            msg.obj = response;
11373            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11374        }
11375    }
11376
11377    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11378            int verificationCode, UserHandle user) {
11379        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11380        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11381        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11382        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11383        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11384
11385        mContext.sendBroadcastAsUser(intent, user,
11386                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11387    }
11388
11389    private ComponentName matchComponentForVerifier(String packageName,
11390            List<ResolveInfo> receivers) {
11391        ActivityInfo targetReceiver = null;
11392
11393        final int NR = receivers.size();
11394        for (int i = 0; i < NR; i++) {
11395            final ResolveInfo info = receivers.get(i);
11396            if (info.activityInfo == null) {
11397                continue;
11398            }
11399
11400            if (packageName.equals(info.activityInfo.packageName)) {
11401                targetReceiver = info.activityInfo;
11402                break;
11403            }
11404        }
11405
11406        if (targetReceiver == null) {
11407            return null;
11408        }
11409
11410        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11411    }
11412
11413    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11414            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11415        if (pkgInfo.verifiers.length == 0) {
11416            return null;
11417        }
11418
11419        final int N = pkgInfo.verifiers.length;
11420        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11421        for (int i = 0; i < N; i++) {
11422            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11423
11424            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11425                    receivers);
11426            if (comp == null) {
11427                continue;
11428            }
11429
11430            final int verifierUid = getUidForVerifier(verifierInfo);
11431            if (verifierUid == -1) {
11432                continue;
11433            }
11434
11435            if (DEBUG_VERIFY) {
11436                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11437                        + " with the correct signature");
11438            }
11439            sufficientVerifiers.add(comp);
11440            verificationState.addSufficientVerifier(verifierUid);
11441        }
11442
11443        return sufficientVerifiers;
11444    }
11445
11446    private int getUidForVerifier(VerifierInfo verifierInfo) {
11447        synchronized (mPackages) {
11448            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11449            if (pkg == null) {
11450                return -1;
11451            } else if (pkg.mSignatures.length != 1) {
11452                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11453                        + " has more than one signature; ignoring");
11454                return -1;
11455            }
11456
11457            /*
11458             * If the public key of the package's signature does not match
11459             * our expected public key, then this is a different package and
11460             * we should skip.
11461             */
11462
11463            final byte[] expectedPublicKey;
11464            try {
11465                final Signature verifierSig = pkg.mSignatures[0];
11466                final PublicKey publicKey = verifierSig.getPublicKey();
11467                expectedPublicKey = publicKey.getEncoded();
11468            } catch (CertificateException e) {
11469                return -1;
11470            }
11471
11472            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11473
11474            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11475                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11476                        + " does not have the expected public key; ignoring");
11477                return -1;
11478            }
11479
11480            return pkg.applicationInfo.uid;
11481        }
11482    }
11483
11484    @Override
11485    public void finishPackageInstall(int token) {
11486        enforceSystemOrRoot("Only the system is allowed to finish installs");
11487
11488        if (DEBUG_INSTALL) {
11489            Slog.v(TAG, "BM finishing package install for " + token);
11490        }
11491        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11492
11493        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11494        mHandler.sendMessage(msg);
11495    }
11496
11497    /**
11498     * Get the verification agent timeout.
11499     *
11500     * @return verification timeout in milliseconds
11501     */
11502    private long getVerificationTimeout() {
11503        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11504                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11505                DEFAULT_VERIFICATION_TIMEOUT);
11506    }
11507
11508    /**
11509     * Get the default verification agent response code.
11510     *
11511     * @return default verification response code
11512     */
11513    private int getDefaultVerificationResponse() {
11514        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11515                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11516                DEFAULT_VERIFICATION_RESPONSE);
11517    }
11518
11519    /**
11520     * Check whether or not package verification has been enabled.
11521     *
11522     * @return true if verification should be performed
11523     */
11524    private boolean isVerificationEnabled(int userId, int installFlags) {
11525        if (!DEFAULT_VERIFY_ENABLE) {
11526            return false;
11527        }
11528        // Ephemeral apps don't get the full verification treatment
11529        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11530            if (DEBUG_EPHEMERAL) {
11531                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11532            }
11533            return false;
11534        }
11535
11536        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11537
11538        // Check if installing from ADB
11539        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11540            // Do not run verification in a test harness environment
11541            if (ActivityManager.isRunningInTestHarness()) {
11542                return false;
11543            }
11544            if (ensureVerifyAppsEnabled) {
11545                return true;
11546            }
11547            // Check if the developer does not want package verification for ADB installs
11548            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11549                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11550                return false;
11551            }
11552        }
11553
11554        if (ensureVerifyAppsEnabled) {
11555            return true;
11556        }
11557
11558        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11559                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11560    }
11561
11562    @Override
11563    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11564            throws RemoteException {
11565        mContext.enforceCallingOrSelfPermission(
11566                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11567                "Only intentfilter verification agents can verify applications");
11568
11569        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11570        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11571                Binder.getCallingUid(), verificationCode, failedDomains);
11572        msg.arg1 = id;
11573        msg.obj = response;
11574        mHandler.sendMessage(msg);
11575    }
11576
11577    @Override
11578    public int getIntentVerificationStatus(String packageName, int userId) {
11579        synchronized (mPackages) {
11580            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11581        }
11582    }
11583
11584    @Override
11585    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11586        mContext.enforceCallingOrSelfPermission(
11587                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11588
11589        boolean result = false;
11590        synchronized (mPackages) {
11591            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11592        }
11593        if (result) {
11594            scheduleWritePackageRestrictionsLocked(userId);
11595        }
11596        return result;
11597    }
11598
11599    @Override
11600    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
11601            String packageName) {
11602        synchronized (mPackages) {
11603            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
11604        }
11605    }
11606
11607    @Override
11608    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
11609        if (TextUtils.isEmpty(packageName)) {
11610            return ParceledListSlice.emptyList();
11611        }
11612        synchronized (mPackages) {
11613            PackageParser.Package pkg = mPackages.get(packageName);
11614            if (pkg == null || pkg.activities == null) {
11615                return ParceledListSlice.emptyList();
11616            }
11617            final int count = pkg.activities.size();
11618            ArrayList<IntentFilter> result = new ArrayList<>();
11619            for (int n=0; n<count; n++) {
11620                PackageParser.Activity activity = pkg.activities.get(n);
11621                if (activity.intents != null && activity.intents.size() > 0) {
11622                    result.addAll(activity.intents);
11623                }
11624            }
11625            return new ParceledListSlice<>(result);
11626        }
11627    }
11628
11629    @Override
11630    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11631        mContext.enforceCallingOrSelfPermission(
11632                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11633
11634        synchronized (mPackages) {
11635            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11636            if (packageName != null) {
11637                result |= updateIntentVerificationStatus(packageName,
11638                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11639                        userId);
11640                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11641                        packageName, userId);
11642            }
11643            return result;
11644        }
11645    }
11646
11647    @Override
11648    public String getDefaultBrowserPackageName(int userId) {
11649        synchronized (mPackages) {
11650            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11651        }
11652    }
11653
11654    /**
11655     * Get the "allow unknown sources" setting.
11656     *
11657     * @return the current "allow unknown sources" setting
11658     */
11659    private int getUnknownSourcesSettings() {
11660        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
11661                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
11662                -1);
11663    }
11664
11665    @Override
11666    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11667        final int uid = Binder.getCallingUid();
11668        // writer
11669        synchronized (mPackages) {
11670            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11671            if (targetPackageSetting == null) {
11672                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11673            }
11674
11675            PackageSetting installerPackageSetting;
11676            if (installerPackageName != null) {
11677                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11678                if (installerPackageSetting == null) {
11679                    throw new IllegalArgumentException("Unknown installer package: "
11680                            + installerPackageName);
11681                }
11682            } else {
11683                installerPackageSetting = null;
11684            }
11685
11686            Signature[] callerSignature;
11687            Object obj = mSettings.getUserIdLPr(uid);
11688            if (obj != null) {
11689                if (obj instanceof SharedUserSetting) {
11690                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11691                } else if (obj instanceof PackageSetting) {
11692                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11693                } else {
11694                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11695                }
11696            } else {
11697                throw new SecurityException("Unknown calling UID: " + uid);
11698            }
11699
11700            // Verify: can't set installerPackageName to a package that is
11701            // not signed with the same cert as the caller.
11702            if (installerPackageSetting != null) {
11703                if (compareSignatures(callerSignature,
11704                        installerPackageSetting.signatures.mSignatures)
11705                        != PackageManager.SIGNATURE_MATCH) {
11706                    throw new SecurityException(
11707                            "Caller does not have same cert as new installer package "
11708                            + installerPackageName);
11709                }
11710            }
11711
11712            // Verify: if target already has an installer package, it must
11713            // be signed with the same cert as the caller.
11714            if (targetPackageSetting.installerPackageName != null) {
11715                PackageSetting setting = mSettings.mPackages.get(
11716                        targetPackageSetting.installerPackageName);
11717                // If the currently set package isn't valid, then it's always
11718                // okay to change it.
11719                if (setting != null) {
11720                    if (compareSignatures(callerSignature,
11721                            setting.signatures.mSignatures)
11722                            != PackageManager.SIGNATURE_MATCH) {
11723                        throw new SecurityException(
11724                                "Caller does not have same cert as old installer package "
11725                                + targetPackageSetting.installerPackageName);
11726                    }
11727                }
11728            }
11729
11730            // Okay!
11731            targetPackageSetting.installerPackageName = installerPackageName;
11732            scheduleWriteSettingsLocked();
11733        }
11734    }
11735
11736    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11737        // Queue up an async operation since the package installation may take a little while.
11738        mHandler.post(new Runnable() {
11739            public void run() {
11740                mHandler.removeCallbacks(this);
11741                 // Result object to be returned
11742                PackageInstalledInfo res = new PackageInstalledInfo();
11743                res.setReturnCode(currentStatus);
11744                res.uid = -1;
11745                res.pkg = null;
11746                res.removedInfo = null;
11747                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11748                    args.doPreInstall(res.returnCode);
11749                    synchronized (mInstallLock) {
11750                        installPackageTracedLI(args, res);
11751                    }
11752                    args.doPostInstall(res.returnCode, res.uid);
11753                }
11754
11755                // A restore should be performed at this point if (a) the install
11756                // succeeded, (b) the operation is not an update, and (c) the new
11757                // package has not opted out of backup participation.
11758                final boolean update = res.removedInfo != null
11759                        && res.removedInfo.removedPackage != null;
11760                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
11761                boolean doRestore = !update
11762                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
11763
11764                // Set up the post-install work request bookkeeping.  This will be used
11765                // and cleaned up by the post-install event handling regardless of whether
11766                // there's a restore pass performed.  Token values are >= 1.
11767                int token;
11768                if (mNextInstallToken < 0) mNextInstallToken = 1;
11769                token = mNextInstallToken++;
11770
11771                PostInstallData data = new PostInstallData(args, res);
11772                mRunningInstalls.put(token, data);
11773                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
11774
11775                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
11776                    // Pass responsibility to the Backup Manager.  It will perform a
11777                    // restore if appropriate, then pass responsibility back to the
11778                    // Package Manager to run the post-install observer callbacks
11779                    // and broadcasts.
11780                    IBackupManager bm = IBackupManager.Stub.asInterface(
11781                            ServiceManager.getService(Context.BACKUP_SERVICE));
11782                    if (bm != null) {
11783                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
11784                                + " to BM for possible restore");
11785                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11786                        try {
11787                            // TODO: http://b/22388012
11788                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
11789                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
11790                            } else {
11791                                doRestore = false;
11792                            }
11793                        } catch (RemoteException e) {
11794                            // can't happen; the backup manager is local
11795                        } catch (Exception e) {
11796                            Slog.e(TAG, "Exception trying to enqueue restore", e);
11797                            doRestore = false;
11798                        }
11799                    } else {
11800                        Slog.e(TAG, "Backup Manager not found!");
11801                        doRestore = false;
11802                    }
11803                }
11804
11805                if (!doRestore) {
11806                    // No restore possible, or the Backup Manager was mysteriously not
11807                    // available -- just fire the post-install work request directly.
11808                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
11809
11810                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
11811
11812                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11813                    mHandler.sendMessage(msg);
11814                }
11815            }
11816        });
11817    }
11818
11819    private abstract class HandlerParams {
11820        private static final int MAX_RETRIES = 4;
11821
11822        /**
11823         * Number of times startCopy() has been attempted and had a non-fatal
11824         * error.
11825         */
11826        private int mRetries = 0;
11827
11828        /** User handle for the user requesting the information or installation. */
11829        private final UserHandle mUser;
11830        String traceMethod;
11831        int traceCookie;
11832
11833        HandlerParams(UserHandle user) {
11834            mUser = user;
11835        }
11836
11837        UserHandle getUser() {
11838            return mUser;
11839        }
11840
11841        HandlerParams setTraceMethod(String traceMethod) {
11842            this.traceMethod = traceMethod;
11843            return this;
11844        }
11845
11846        HandlerParams setTraceCookie(int traceCookie) {
11847            this.traceCookie = traceCookie;
11848            return this;
11849        }
11850
11851        final boolean startCopy() {
11852            boolean res;
11853            try {
11854                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
11855
11856                if (++mRetries > MAX_RETRIES) {
11857                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
11858                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
11859                    handleServiceError();
11860                    return false;
11861                } else {
11862                    handleStartCopy();
11863                    res = true;
11864                }
11865            } catch (RemoteException e) {
11866                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
11867                mHandler.sendEmptyMessage(MCS_RECONNECT);
11868                res = false;
11869            }
11870            handleReturnCode();
11871            return res;
11872        }
11873
11874        final void serviceError() {
11875            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
11876            handleServiceError();
11877            handleReturnCode();
11878        }
11879
11880        abstract void handleStartCopy() throws RemoteException;
11881        abstract void handleServiceError();
11882        abstract void handleReturnCode();
11883    }
11884
11885    class MeasureParams extends HandlerParams {
11886        private final PackageStats mStats;
11887        private boolean mSuccess;
11888
11889        private final IPackageStatsObserver mObserver;
11890
11891        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
11892            super(new UserHandle(stats.userHandle));
11893            mObserver = observer;
11894            mStats = stats;
11895        }
11896
11897        @Override
11898        public String toString() {
11899            return "MeasureParams{"
11900                + Integer.toHexString(System.identityHashCode(this))
11901                + " " + mStats.packageName + "}";
11902        }
11903
11904        @Override
11905        void handleStartCopy() throws RemoteException {
11906            synchronized (mInstallLock) {
11907                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
11908            }
11909
11910            if (mSuccess) {
11911                final boolean mounted;
11912                if (Environment.isExternalStorageEmulated()) {
11913                    mounted = true;
11914                } else {
11915                    final String status = Environment.getExternalStorageState();
11916                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
11917                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
11918                }
11919
11920                if (mounted) {
11921                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
11922
11923                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
11924                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
11925
11926                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
11927                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
11928
11929                    // Always subtract cache size, since it's a subdirectory
11930                    mStats.externalDataSize -= mStats.externalCacheSize;
11931
11932                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
11933                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
11934
11935                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
11936                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
11937                }
11938            }
11939        }
11940
11941        @Override
11942        void handleReturnCode() {
11943            if (mObserver != null) {
11944                try {
11945                    mObserver.onGetStatsCompleted(mStats, mSuccess);
11946                } catch (RemoteException e) {
11947                    Slog.i(TAG, "Observer no longer exists.");
11948                }
11949            }
11950        }
11951
11952        @Override
11953        void handleServiceError() {
11954            Slog.e(TAG, "Could not measure application " + mStats.packageName
11955                            + " external storage");
11956        }
11957    }
11958
11959    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
11960            throws RemoteException {
11961        long result = 0;
11962        for (File path : paths) {
11963            result += mcs.calculateDirectorySize(path.getAbsolutePath());
11964        }
11965        return result;
11966    }
11967
11968    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
11969        for (File path : paths) {
11970            try {
11971                mcs.clearDirectory(path.getAbsolutePath());
11972            } catch (RemoteException e) {
11973            }
11974        }
11975    }
11976
11977    static class OriginInfo {
11978        /**
11979         * Location where install is coming from, before it has been
11980         * copied/renamed into place. This could be a single monolithic APK
11981         * file, or a cluster directory. This location may be untrusted.
11982         */
11983        final File file;
11984        final String cid;
11985
11986        /**
11987         * Flag indicating that {@link #file} or {@link #cid} has already been
11988         * staged, meaning downstream users don't need to defensively copy the
11989         * contents.
11990         */
11991        final boolean staged;
11992
11993        /**
11994         * Flag indicating that {@link #file} or {@link #cid} is an already
11995         * installed app that is being moved.
11996         */
11997        final boolean existing;
11998
11999        final String resolvedPath;
12000        final File resolvedFile;
12001
12002        static OriginInfo fromNothing() {
12003            return new OriginInfo(null, null, false, false);
12004        }
12005
12006        static OriginInfo fromUntrustedFile(File file) {
12007            return new OriginInfo(file, null, false, false);
12008        }
12009
12010        static OriginInfo fromExistingFile(File file) {
12011            return new OriginInfo(file, null, false, true);
12012        }
12013
12014        static OriginInfo fromStagedFile(File file) {
12015            return new OriginInfo(file, null, true, false);
12016        }
12017
12018        static OriginInfo fromStagedContainer(String cid) {
12019            return new OriginInfo(null, cid, true, false);
12020        }
12021
12022        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12023            this.file = file;
12024            this.cid = cid;
12025            this.staged = staged;
12026            this.existing = existing;
12027
12028            if (cid != null) {
12029                resolvedPath = PackageHelper.getSdDir(cid);
12030                resolvedFile = new File(resolvedPath);
12031            } else if (file != null) {
12032                resolvedPath = file.getAbsolutePath();
12033                resolvedFile = file;
12034            } else {
12035                resolvedPath = null;
12036                resolvedFile = null;
12037            }
12038        }
12039    }
12040
12041    static class MoveInfo {
12042        final int moveId;
12043        final String fromUuid;
12044        final String toUuid;
12045        final String packageName;
12046        final String dataAppName;
12047        final int appId;
12048        final String seinfo;
12049        final int targetSdkVersion;
12050
12051        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12052                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12053            this.moveId = moveId;
12054            this.fromUuid = fromUuid;
12055            this.toUuid = toUuid;
12056            this.packageName = packageName;
12057            this.dataAppName = dataAppName;
12058            this.appId = appId;
12059            this.seinfo = seinfo;
12060            this.targetSdkVersion = targetSdkVersion;
12061        }
12062    }
12063
12064    static class VerificationInfo {
12065        /** A constant used to indicate that a uid value is not present. */
12066        public static final int NO_UID = -1;
12067
12068        /** URI referencing where the package was downloaded from. */
12069        final Uri originatingUri;
12070
12071        /** HTTP referrer URI associated with the originatingURI. */
12072        final Uri referrer;
12073
12074        /** UID of the application that the install request originated from. */
12075        final int originatingUid;
12076
12077        /** UID of application requesting the install */
12078        final int installerUid;
12079
12080        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12081            this.originatingUri = originatingUri;
12082            this.referrer = referrer;
12083            this.originatingUid = originatingUid;
12084            this.installerUid = installerUid;
12085        }
12086    }
12087
12088    class InstallParams extends HandlerParams {
12089        final OriginInfo origin;
12090        final MoveInfo move;
12091        final IPackageInstallObserver2 observer;
12092        int installFlags;
12093        final String installerPackageName;
12094        final String volumeUuid;
12095        private InstallArgs mArgs;
12096        private int mRet;
12097        final String packageAbiOverride;
12098        final String[] grantedRuntimePermissions;
12099        final VerificationInfo verificationInfo;
12100        final Certificate[][] certificates;
12101
12102        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12103                int installFlags, String installerPackageName, String volumeUuid,
12104                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12105                String[] grantedPermissions, Certificate[][] certificates) {
12106            super(user);
12107            this.origin = origin;
12108            this.move = move;
12109            this.observer = observer;
12110            this.installFlags = installFlags;
12111            this.installerPackageName = installerPackageName;
12112            this.volumeUuid = volumeUuid;
12113            this.verificationInfo = verificationInfo;
12114            this.packageAbiOverride = packageAbiOverride;
12115            this.grantedRuntimePermissions = grantedPermissions;
12116            this.certificates = certificates;
12117        }
12118
12119        @Override
12120        public String toString() {
12121            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12122                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12123        }
12124
12125        private int installLocationPolicy(PackageInfoLite pkgLite) {
12126            String packageName = pkgLite.packageName;
12127            int installLocation = pkgLite.installLocation;
12128            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12129            // reader
12130            synchronized (mPackages) {
12131                // Currently installed package which the new package is attempting to replace or
12132                // null if no such package is installed.
12133                PackageParser.Package installedPkg = mPackages.get(packageName);
12134                // Package which currently owns the data which the new package will own if installed.
12135                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12136                // will be null whereas dataOwnerPkg will contain information about the package
12137                // which was uninstalled while keeping its data.
12138                PackageParser.Package dataOwnerPkg = installedPkg;
12139                if (dataOwnerPkg  == null) {
12140                    PackageSetting ps = mSettings.mPackages.get(packageName);
12141                    if (ps != null) {
12142                        dataOwnerPkg = ps.pkg;
12143                    }
12144                }
12145
12146                if (dataOwnerPkg != null) {
12147                    // If installed, the package will get access to data left on the device by its
12148                    // predecessor. As a security measure, this is permited only if this is not a
12149                    // version downgrade or if the predecessor package is marked as debuggable and
12150                    // a downgrade is explicitly requested.
12151                    //
12152                    // On debuggable platform builds, downgrades are permitted even for
12153                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12154                    // not offer security guarantees and thus it's OK to disable some security
12155                    // mechanisms to make debugging/testing easier on those builds. However, even on
12156                    // debuggable builds downgrades of packages are permitted only if requested via
12157                    // installFlags. This is because we aim to keep the behavior of debuggable
12158                    // platform builds as close as possible to the behavior of non-debuggable
12159                    // platform builds.
12160                    final boolean downgradeRequested =
12161                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12162                    final boolean packageDebuggable =
12163                                (dataOwnerPkg.applicationInfo.flags
12164                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12165                    final boolean downgradePermitted =
12166                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12167                    if (!downgradePermitted) {
12168                        try {
12169                            checkDowngrade(dataOwnerPkg, pkgLite);
12170                        } catch (PackageManagerException e) {
12171                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12172                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12173                        }
12174                    }
12175                }
12176
12177                if (installedPkg != null) {
12178                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12179                        // Check for updated system application.
12180                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12181                            if (onSd) {
12182                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12183                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12184                            }
12185                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12186                        } else {
12187                            if (onSd) {
12188                                // Install flag overrides everything.
12189                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12190                            }
12191                            // If current upgrade specifies particular preference
12192                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12193                                // Application explicitly specified internal.
12194                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12195                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12196                                // App explictly prefers external. Let policy decide
12197                            } else {
12198                                // Prefer previous location
12199                                if (isExternal(installedPkg)) {
12200                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12201                                }
12202                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12203                            }
12204                        }
12205                    } else {
12206                        // Invalid install. Return error code
12207                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12208                    }
12209                }
12210            }
12211            // All the special cases have been taken care of.
12212            // Return result based on recommended install location.
12213            if (onSd) {
12214                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12215            }
12216            return pkgLite.recommendedInstallLocation;
12217        }
12218
12219        /*
12220         * Invoke remote method to get package information and install
12221         * location values. Override install location based on default
12222         * policy if needed and then create install arguments based
12223         * on the install location.
12224         */
12225        public void handleStartCopy() throws RemoteException {
12226            int ret = PackageManager.INSTALL_SUCCEEDED;
12227
12228            // If we're already staged, we've firmly committed to an install location
12229            if (origin.staged) {
12230                if (origin.file != null) {
12231                    installFlags |= PackageManager.INSTALL_INTERNAL;
12232                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12233                } else if (origin.cid != null) {
12234                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12235                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12236                } else {
12237                    throw new IllegalStateException("Invalid stage location");
12238                }
12239            }
12240
12241            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12242            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12243            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12244            PackageInfoLite pkgLite = null;
12245
12246            if (onInt && onSd) {
12247                // Check if both bits are set.
12248                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12249                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12250            } else if (onSd && ephemeral) {
12251                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12252                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12253            } else {
12254                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12255                        packageAbiOverride);
12256
12257                if (DEBUG_EPHEMERAL && ephemeral) {
12258                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12259                }
12260
12261                /*
12262                 * If we have too little free space, try to free cache
12263                 * before giving up.
12264                 */
12265                if (!origin.staged && pkgLite.recommendedInstallLocation
12266                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12267                    // TODO: focus freeing disk space on the target device
12268                    final StorageManager storage = StorageManager.from(mContext);
12269                    final long lowThreshold = storage.getStorageLowBytes(
12270                            Environment.getDataDirectory());
12271
12272                    final long sizeBytes = mContainerService.calculateInstalledSize(
12273                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12274
12275                    try {
12276                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12277                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12278                                installFlags, packageAbiOverride);
12279                    } catch (InstallerException e) {
12280                        Slog.w(TAG, "Failed to free cache", e);
12281                    }
12282
12283                    /*
12284                     * The cache free must have deleted the file we
12285                     * downloaded to install.
12286                     *
12287                     * TODO: fix the "freeCache" call to not delete
12288                     *       the file we care about.
12289                     */
12290                    if (pkgLite.recommendedInstallLocation
12291                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12292                        pkgLite.recommendedInstallLocation
12293                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12294                    }
12295                }
12296            }
12297
12298            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12299                int loc = pkgLite.recommendedInstallLocation;
12300                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12301                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12302                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12303                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12304                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12305                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12306                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12307                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12308                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12309                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12310                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12311                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12312                } else {
12313                    // Override with defaults if needed.
12314                    loc = installLocationPolicy(pkgLite);
12315                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12316                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12317                    } else if (!onSd && !onInt) {
12318                        // Override install location with flags
12319                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12320                            // Set the flag to install on external media.
12321                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12322                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12323                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12324                            if (DEBUG_EPHEMERAL) {
12325                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12326                            }
12327                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12328                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12329                                    |PackageManager.INSTALL_INTERNAL);
12330                        } else {
12331                            // Make sure the flag for installing on external
12332                            // media is unset
12333                            installFlags |= PackageManager.INSTALL_INTERNAL;
12334                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12335                        }
12336                    }
12337                }
12338            }
12339
12340            final InstallArgs args = createInstallArgs(this);
12341            mArgs = args;
12342
12343            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12344                // TODO: http://b/22976637
12345                // Apps installed for "all" users use the device owner to verify the app
12346                UserHandle verifierUser = getUser();
12347                if (verifierUser == UserHandle.ALL) {
12348                    verifierUser = UserHandle.SYSTEM;
12349                }
12350
12351                /*
12352                 * Determine if we have any installed package verifiers. If we
12353                 * do, then we'll defer to them to verify the packages.
12354                 */
12355                final int requiredUid = mRequiredVerifierPackage == null ? -1
12356                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12357                                verifierUser.getIdentifier());
12358                if (!origin.existing && requiredUid != -1
12359                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12360                    final Intent verification = new Intent(
12361                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12362                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12363                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12364                            PACKAGE_MIME_TYPE);
12365                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12366
12367                    // Query all live verifiers based on current user state
12368                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12369                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12370
12371                    if (DEBUG_VERIFY) {
12372                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12373                                + verification.toString() + " with " + pkgLite.verifiers.length
12374                                + " optional verifiers");
12375                    }
12376
12377                    final int verificationId = mPendingVerificationToken++;
12378
12379                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12380
12381                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12382                            installerPackageName);
12383
12384                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12385                            installFlags);
12386
12387                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12388                            pkgLite.packageName);
12389
12390                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12391                            pkgLite.versionCode);
12392
12393                    if (verificationInfo != null) {
12394                        if (verificationInfo.originatingUri != null) {
12395                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12396                                    verificationInfo.originatingUri);
12397                        }
12398                        if (verificationInfo.referrer != null) {
12399                            verification.putExtra(Intent.EXTRA_REFERRER,
12400                                    verificationInfo.referrer);
12401                        }
12402                        if (verificationInfo.originatingUid >= 0) {
12403                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12404                                    verificationInfo.originatingUid);
12405                        }
12406                        if (verificationInfo.installerUid >= 0) {
12407                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12408                                    verificationInfo.installerUid);
12409                        }
12410                    }
12411
12412                    final PackageVerificationState verificationState = new PackageVerificationState(
12413                            requiredUid, args);
12414
12415                    mPendingVerification.append(verificationId, verificationState);
12416
12417                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12418                            receivers, verificationState);
12419
12420                    /*
12421                     * If any sufficient verifiers were listed in the package
12422                     * manifest, attempt to ask them.
12423                     */
12424                    if (sufficientVerifiers != null) {
12425                        final int N = sufficientVerifiers.size();
12426                        if (N == 0) {
12427                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12428                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12429                        } else {
12430                            for (int i = 0; i < N; i++) {
12431                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12432
12433                                final Intent sufficientIntent = new Intent(verification);
12434                                sufficientIntent.setComponent(verifierComponent);
12435                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12436                            }
12437                        }
12438                    }
12439
12440                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12441                            mRequiredVerifierPackage, receivers);
12442                    if (ret == PackageManager.INSTALL_SUCCEEDED
12443                            && mRequiredVerifierPackage != null) {
12444                        Trace.asyncTraceBegin(
12445                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12446                        /*
12447                         * Send the intent to the required verification agent,
12448                         * but only start the verification timeout after the
12449                         * target BroadcastReceivers have run.
12450                         */
12451                        verification.setComponent(requiredVerifierComponent);
12452                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12453                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12454                                new BroadcastReceiver() {
12455                                    @Override
12456                                    public void onReceive(Context context, Intent intent) {
12457                                        final Message msg = mHandler
12458                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12459                                        msg.arg1 = verificationId;
12460                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12461                                    }
12462                                }, null, 0, null, null);
12463
12464                        /*
12465                         * We don't want the copy to proceed until verification
12466                         * succeeds, so null out this field.
12467                         */
12468                        mArgs = null;
12469                    }
12470                } else {
12471                    /*
12472                     * No package verification is enabled, so immediately start
12473                     * the remote call to initiate copy using temporary file.
12474                     */
12475                    ret = args.copyApk(mContainerService, true);
12476                }
12477            }
12478
12479            mRet = ret;
12480        }
12481
12482        @Override
12483        void handleReturnCode() {
12484            // If mArgs is null, then MCS couldn't be reached. When it
12485            // reconnects, it will try again to install. At that point, this
12486            // will succeed.
12487            if (mArgs != null) {
12488                processPendingInstall(mArgs, mRet);
12489            }
12490        }
12491
12492        @Override
12493        void handleServiceError() {
12494            mArgs = createInstallArgs(this);
12495            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12496        }
12497
12498        public boolean isForwardLocked() {
12499            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12500        }
12501    }
12502
12503    /**
12504     * Used during creation of InstallArgs
12505     *
12506     * @param installFlags package installation flags
12507     * @return true if should be installed on external storage
12508     */
12509    private static boolean installOnExternalAsec(int installFlags) {
12510        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12511            return false;
12512        }
12513        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12514            return true;
12515        }
12516        return false;
12517    }
12518
12519    /**
12520     * Used during creation of InstallArgs
12521     *
12522     * @param installFlags package installation flags
12523     * @return true if should be installed as forward locked
12524     */
12525    private static boolean installForwardLocked(int installFlags) {
12526        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12527    }
12528
12529    private InstallArgs createInstallArgs(InstallParams params) {
12530        if (params.move != null) {
12531            return new MoveInstallArgs(params);
12532        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
12533            return new AsecInstallArgs(params);
12534        } else {
12535            return new FileInstallArgs(params);
12536        }
12537    }
12538
12539    /**
12540     * Create args that describe an existing installed package. Typically used
12541     * when cleaning up old installs, or used as a move source.
12542     */
12543    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
12544            String resourcePath, String[] instructionSets) {
12545        final boolean isInAsec;
12546        if (installOnExternalAsec(installFlags)) {
12547            /* Apps on SD card are always in ASEC containers. */
12548            isInAsec = true;
12549        } else if (installForwardLocked(installFlags)
12550                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
12551            /*
12552             * Forward-locked apps are only in ASEC containers if they're the
12553             * new style
12554             */
12555            isInAsec = true;
12556        } else {
12557            isInAsec = false;
12558        }
12559
12560        if (isInAsec) {
12561            return new AsecInstallArgs(codePath, instructionSets,
12562                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
12563        } else {
12564            return new FileInstallArgs(codePath, resourcePath, instructionSets);
12565        }
12566    }
12567
12568    static abstract class InstallArgs {
12569        /** @see InstallParams#origin */
12570        final OriginInfo origin;
12571        /** @see InstallParams#move */
12572        final MoveInfo move;
12573
12574        final IPackageInstallObserver2 observer;
12575        // Always refers to PackageManager flags only
12576        final int installFlags;
12577        final String installerPackageName;
12578        final String volumeUuid;
12579        final UserHandle user;
12580        final String abiOverride;
12581        final String[] installGrantPermissions;
12582        /** If non-null, drop an async trace when the install completes */
12583        final String traceMethod;
12584        final int traceCookie;
12585        final Certificate[][] certificates;
12586
12587        // The list of instruction sets supported by this app. This is currently
12588        // only used during the rmdex() phase to clean up resources. We can get rid of this
12589        // if we move dex files under the common app path.
12590        /* nullable */ String[] instructionSets;
12591
12592        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12593                int installFlags, String installerPackageName, String volumeUuid,
12594                UserHandle user, String[] instructionSets,
12595                String abiOverride, String[] installGrantPermissions,
12596                String traceMethod, int traceCookie, Certificate[][] certificates) {
12597            this.origin = origin;
12598            this.move = move;
12599            this.installFlags = installFlags;
12600            this.observer = observer;
12601            this.installerPackageName = installerPackageName;
12602            this.volumeUuid = volumeUuid;
12603            this.user = user;
12604            this.instructionSets = instructionSets;
12605            this.abiOverride = abiOverride;
12606            this.installGrantPermissions = installGrantPermissions;
12607            this.traceMethod = traceMethod;
12608            this.traceCookie = traceCookie;
12609            this.certificates = certificates;
12610        }
12611
12612        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
12613        abstract int doPreInstall(int status);
12614
12615        /**
12616         * Rename package into final resting place. All paths on the given
12617         * scanned package should be updated to reflect the rename.
12618         */
12619        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
12620        abstract int doPostInstall(int status, int uid);
12621
12622        /** @see PackageSettingBase#codePathString */
12623        abstract String getCodePath();
12624        /** @see PackageSettingBase#resourcePathString */
12625        abstract String getResourcePath();
12626
12627        // Need installer lock especially for dex file removal.
12628        abstract void cleanUpResourcesLI();
12629        abstract boolean doPostDeleteLI(boolean delete);
12630
12631        /**
12632         * Called before the source arguments are copied. This is used mostly
12633         * for MoveParams when it needs to read the source file to put it in the
12634         * destination.
12635         */
12636        int doPreCopy() {
12637            return PackageManager.INSTALL_SUCCEEDED;
12638        }
12639
12640        /**
12641         * Called after the source arguments are copied. This is used mostly for
12642         * MoveParams when it needs to read the source file to put it in the
12643         * destination.
12644         */
12645        int doPostCopy(int uid) {
12646            return PackageManager.INSTALL_SUCCEEDED;
12647        }
12648
12649        protected boolean isFwdLocked() {
12650            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12651        }
12652
12653        protected boolean isExternalAsec() {
12654            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12655        }
12656
12657        protected boolean isEphemeral() {
12658            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12659        }
12660
12661        UserHandle getUser() {
12662            return user;
12663        }
12664    }
12665
12666    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
12667        if (!allCodePaths.isEmpty()) {
12668            if (instructionSets == null) {
12669                throw new IllegalStateException("instructionSet == null");
12670            }
12671            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12672            for (String codePath : allCodePaths) {
12673                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12674                    try {
12675                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12676                    } catch (InstallerException ignored) {
12677                    }
12678                }
12679            }
12680        }
12681    }
12682
12683    /**
12684     * Logic to handle installation of non-ASEC applications, including copying
12685     * and renaming logic.
12686     */
12687    class FileInstallArgs extends InstallArgs {
12688        private File codeFile;
12689        private File resourceFile;
12690
12691        // Example topology:
12692        // /data/app/com.example/base.apk
12693        // /data/app/com.example/split_foo.apk
12694        // /data/app/com.example/lib/arm/libfoo.so
12695        // /data/app/com.example/lib/arm64/libfoo.so
12696        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
12697
12698        /** New install */
12699        FileInstallArgs(InstallParams params) {
12700            super(params.origin, params.move, params.observer, params.installFlags,
12701                    params.installerPackageName, params.volumeUuid,
12702                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
12703                    params.grantedRuntimePermissions,
12704                    params.traceMethod, params.traceCookie, params.certificates);
12705            if (isFwdLocked()) {
12706                throw new IllegalArgumentException("Forward locking only supported in ASEC");
12707            }
12708        }
12709
12710        /** Existing install */
12711        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
12712            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
12713                    null, null, null, 0, null /*certificates*/);
12714            this.codeFile = (codePath != null) ? new File(codePath) : null;
12715            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
12716        }
12717
12718        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12719            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
12720            try {
12721                return doCopyApk(imcs, temp);
12722            } finally {
12723                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12724            }
12725        }
12726
12727        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12728            if (origin.staged) {
12729                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12730                codeFile = origin.file;
12731                resourceFile = origin.file;
12732                return PackageManager.INSTALL_SUCCEEDED;
12733            }
12734
12735            try {
12736                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12737                final File tempDir =
12738                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12739                codeFile = tempDir;
12740                resourceFile = tempDir;
12741            } catch (IOException e) {
12742                Slog.w(TAG, "Failed to create copy file: " + e);
12743                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12744            }
12745
12746            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12747                @Override
12748                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12749                    if (!FileUtils.isValidExtFilename(name)) {
12750                        throw new IllegalArgumentException("Invalid filename: " + name);
12751                    }
12752                    try {
12753                        final File file = new File(codeFile, name);
12754                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12755                                O_RDWR | O_CREAT, 0644);
12756                        Os.chmod(file.getAbsolutePath(), 0644);
12757                        return new ParcelFileDescriptor(fd);
12758                    } catch (ErrnoException e) {
12759                        throw new RemoteException("Failed to open: " + e.getMessage());
12760                    }
12761                }
12762            };
12763
12764            int ret = PackageManager.INSTALL_SUCCEEDED;
12765            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
12766            if (ret != PackageManager.INSTALL_SUCCEEDED) {
12767                Slog.e(TAG, "Failed to copy package");
12768                return ret;
12769            }
12770
12771            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
12772            NativeLibraryHelper.Handle handle = null;
12773            try {
12774                handle = NativeLibraryHelper.Handle.create(codeFile);
12775                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
12776                        abiOverride);
12777            } catch (IOException e) {
12778                Slog.e(TAG, "Copying native libraries failed", e);
12779                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12780            } finally {
12781                IoUtils.closeQuietly(handle);
12782            }
12783
12784            return ret;
12785        }
12786
12787        int doPreInstall(int status) {
12788            if (status != PackageManager.INSTALL_SUCCEEDED) {
12789                cleanUp();
12790            }
12791            return status;
12792        }
12793
12794        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12795            if (status != PackageManager.INSTALL_SUCCEEDED) {
12796                cleanUp();
12797                return false;
12798            }
12799
12800            final File targetDir = codeFile.getParentFile();
12801            final File beforeCodeFile = codeFile;
12802            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
12803
12804            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
12805            try {
12806                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
12807            } catch (ErrnoException e) {
12808                Slog.w(TAG, "Failed to rename", e);
12809                return false;
12810            }
12811
12812            if (!SELinux.restoreconRecursive(afterCodeFile)) {
12813                Slog.w(TAG, "Failed to restorecon");
12814                return false;
12815            }
12816
12817            // Reflect the rename internally
12818            codeFile = afterCodeFile;
12819            resourceFile = afterCodeFile;
12820
12821            // Reflect the rename in scanned details
12822            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12823            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12824                    afterCodeFile, pkg.baseCodePath));
12825            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12826                    afterCodeFile, pkg.splitCodePaths));
12827
12828            // Reflect the rename in app info
12829            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12830            pkg.setApplicationInfoCodePath(pkg.codePath);
12831            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12832            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12833            pkg.setApplicationInfoResourcePath(pkg.codePath);
12834            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12835            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12836
12837            return true;
12838        }
12839
12840        int doPostInstall(int status, int uid) {
12841            if (status != PackageManager.INSTALL_SUCCEEDED) {
12842                cleanUp();
12843            }
12844            return status;
12845        }
12846
12847        @Override
12848        String getCodePath() {
12849            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12850        }
12851
12852        @Override
12853        String getResourcePath() {
12854            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12855        }
12856
12857        private boolean cleanUp() {
12858            if (codeFile == null || !codeFile.exists()) {
12859                return false;
12860            }
12861
12862            removeCodePathLI(codeFile);
12863
12864            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
12865                resourceFile.delete();
12866            }
12867
12868            return true;
12869        }
12870
12871        void cleanUpResourcesLI() {
12872            // Try enumerating all code paths before deleting
12873            List<String> allCodePaths = Collections.EMPTY_LIST;
12874            if (codeFile != null && codeFile.exists()) {
12875                try {
12876                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12877                    allCodePaths = pkg.getAllCodePaths();
12878                } catch (PackageParserException e) {
12879                    // Ignored; we tried our best
12880                }
12881            }
12882
12883            cleanUp();
12884            removeDexFiles(allCodePaths, instructionSets);
12885        }
12886
12887        boolean doPostDeleteLI(boolean delete) {
12888            // XXX err, shouldn't we respect the delete flag?
12889            cleanUpResourcesLI();
12890            return true;
12891        }
12892    }
12893
12894    private boolean isAsecExternal(String cid) {
12895        final String asecPath = PackageHelper.getSdFilesystem(cid);
12896        return !asecPath.startsWith(mAsecInternalPath);
12897    }
12898
12899    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
12900            PackageManagerException {
12901        if (copyRet < 0) {
12902            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
12903                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
12904                throw new PackageManagerException(copyRet, message);
12905            }
12906        }
12907    }
12908
12909    /**
12910     * Extract the MountService "container ID" from the full code path of an
12911     * .apk.
12912     */
12913    static String cidFromCodePath(String fullCodePath) {
12914        int eidx = fullCodePath.lastIndexOf("/");
12915        String subStr1 = fullCodePath.substring(0, eidx);
12916        int sidx = subStr1.lastIndexOf("/");
12917        return subStr1.substring(sidx+1, eidx);
12918    }
12919
12920    /**
12921     * Logic to handle installation of ASEC applications, including copying and
12922     * renaming logic.
12923     */
12924    class AsecInstallArgs extends InstallArgs {
12925        static final String RES_FILE_NAME = "pkg.apk";
12926        static final String PUBLIC_RES_FILE_NAME = "res.zip";
12927
12928        String cid;
12929        String packagePath;
12930        String resourcePath;
12931
12932        /** New install */
12933        AsecInstallArgs(InstallParams params) {
12934            super(params.origin, params.move, params.observer, params.installFlags,
12935                    params.installerPackageName, params.volumeUuid,
12936                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12937                    params.grantedRuntimePermissions,
12938                    params.traceMethod, params.traceCookie, params.certificates);
12939        }
12940
12941        /** Existing install */
12942        AsecInstallArgs(String fullCodePath, String[] instructionSets,
12943                        boolean isExternal, boolean isForwardLocked) {
12944            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
12945              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12946                    instructionSets, null, null, null, 0, null /*certificates*/);
12947            // Hackily pretend we're still looking at a full code path
12948            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
12949                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
12950            }
12951
12952            // Extract cid from fullCodePath
12953            int eidx = fullCodePath.lastIndexOf("/");
12954            String subStr1 = fullCodePath.substring(0, eidx);
12955            int sidx = subStr1.lastIndexOf("/");
12956            cid = subStr1.substring(sidx+1, eidx);
12957            setMountPath(subStr1);
12958        }
12959
12960        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
12961            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
12962              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12963                    instructionSets, null, null, null, 0, null /*certificates*/);
12964            this.cid = cid;
12965            setMountPath(PackageHelper.getSdDir(cid));
12966        }
12967
12968        void createCopyFile() {
12969            cid = mInstallerService.allocateExternalStageCidLegacy();
12970        }
12971
12972        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12973            if (origin.staged && origin.cid != null) {
12974                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
12975                cid = origin.cid;
12976                setMountPath(PackageHelper.getSdDir(cid));
12977                return PackageManager.INSTALL_SUCCEEDED;
12978            }
12979
12980            if (temp) {
12981                createCopyFile();
12982            } else {
12983                /*
12984                 * Pre-emptively destroy the container since it's destroyed if
12985                 * copying fails due to it existing anyway.
12986                 */
12987                PackageHelper.destroySdDir(cid);
12988            }
12989
12990            final String newMountPath = imcs.copyPackageToContainer(
12991                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
12992                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
12993
12994            if (newMountPath != null) {
12995                setMountPath(newMountPath);
12996                return PackageManager.INSTALL_SUCCEEDED;
12997            } else {
12998                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12999            }
13000        }
13001
13002        @Override
13003        String getCodePath() {
13004            return packagePath;
13005        }
13006
13007        @Override
13008        String getResourcePath() {
13009            return resourcePath;
13010        }
13011
13012        int doPreInstall(int status) {
13013            if (status != PackageManager.INSTALL_SUCCEEDED) {
13014                // Destroy container
13015                PackageHelper.destroySdDir(cid);
13016            } else {
13017                boolean mounted = PackageHelper.isContainerMounted(cid);
13018                if (!mounted) {
13019                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13020                            Process.SYSTEM_UID);
13021                    if (newMountPath != null) {
13022                        setMountPath(newMountPath);
13023                    } else {
13024                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13025                    }
13026                }
13027            }
13028            return status;
13029        }
13030
13031        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13032            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13033            String newMountPath = null;
13034            if (PackageHelper.isContainerMounted(cid)) {
13035                // Unmount the container
13036                if (!PackageHelper.unMountSdDir(cid)) {
13037                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13038                    return false;
13039                }
13040            }
13041            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13042                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13043                        " which might be stale. Will try to clean up.");
13044                // Clean up the stale container and proceed to recreate.
13045                if (!PackageHelper.destroySdDir(newCacheId)) {
13046                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13047                    return false;
13048                }
13049                // Successfully cleaned up stale container. Try to rename again.
13050                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13051                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13052                            + " inspite of cleaning it up.");
13053                    return false;
13054                }
13055            }
13056            if (!PackageHelper.isContainerMounted(newCacheId)) {
13057                Slog.w(TAG, "Mounting container " + newCacheId);
13058                newMountPath = PackageHelper.mountSdDir(newCacheId,
13059                        getEncryptKey(), Process.SYSTEM_UID);
13060            } else {
13061                newMountPath = PackageHelper.getSdDir(newCacheId);
13062            }
13063            if (newMountPath == null) {
13064                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13065                return false;
13066            }
13067            Log.i(TAG, "Succesfully renamed " + cid +
13068                    " to " + newCacheId +
13069                    " at new path: " + newMountPath);
13070            cid = newCacheId;
13071
13072            final File beforeCodeFile = new File(packagePath);
13073            setMountPath(newMountPath);
13074            final File afterCodeFile = new File(packagePath);
13075
13076            // Reflect the rename in scanned details
13077            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13078            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13079                    afterCodeFile, pkg.baseCodePath));
13080            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13081                    afterCodeFile, pkg.splitCodePaths));
13082
13083            // Reflect the rename in app info
13084            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13085            pkg.setApplicationInfoCodePath(pkg.codePath);
13086            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13087            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13088            pkg.setApplicationInfoResourcePath(pkg.codePath);
13089            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13090            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13091
13092            return true;
13093        }
13094
13095        private void setMountPath(String mountPath) {
13096            final File mountFile = new File(mountPath);
13097
13098            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13099            if (monolithicFile.exists()) {
13100                packagePath = monolithicFile.getAbsolutePath();
13101                if (isFwdLocked()) {
13102                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13103                } else {
13104                    resourcePath = packagePath;
13105                }
13106            } else {
13107                packagePath = mountFile.getAbsolutePath();
13108                resourcePath = packagePath;
13109            }
13110        }
13111
13112        int doPostInstall(int status, int uid) {
13113            if (status != PackageManager.INSTALL_SUCCEEDED) {
13114                cleanUp();
13115            } else {
13116                final int groupOwner;
13117                final String protectedFile;
13118                if (isFwdLocked()) {
13119                    groupOwner = UserHandle.getSharedAppGid(uid);
13120                    protectedFile = RES_FILE_NAME;
13121                } else {
13122                    groupOwner = -1;
13123                    protectedFile = null;
13124                }
13125
13126                if (uid < Process.FIRST_APPLICATION_UID
13127                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13128                    Slog.e(TAG, "Failed to finalize " + cid);
13129                    PackageHelper.destroySdDir(cid);
13130                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13131                }
13132
13133                boolean mounted = PackageHelper.isContainerMounted(cid);
13134                if (!mounted) {
13135                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13136                }
13137            }
13138            return status;
13139        }
13140
13141        private void cleanUp() {
13142            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13143
13144            // Destroy secure container
13145            PackageHelper.destroySdDir(cid);
13146        }
13147
13148        private List<String> getAllCodePaths() {
13149            final File codeFile = new File(getCodePath());
13150            if (codeFile != null && codeFile.exists()) {
13151                try {
13152                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13153                    return pkg.getAllCodePaths();
13154                } catch (PackageParserException e) {
13155                    // Ignored; we tried our best
13156                }
13157            }
13158            return Collections.EMPTY_LIST;
13159        }
13160
13161        void cleanUpResourcesLI() {
13162            // Enumerate all code paths before deleting
13163            cleanUpResourcesLI(getAllCodePaths());
13164        }
13165
13166        private void cleanUpResourcesLI(List<String> allCodePaths) {
13167            cleanUp();
13168            removeDexFiles(allCodePaths, instructionSets);
13169        }
13170
13171        String getPackageName() {
13172            return getAsecPackageName(cid);
13173        }
13174
13175        boolean doPostDeleteLI(boolean delete) {
13176            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13177            final List<String> allCodePaths = getAllCodePaths();
13178            boolean mounted = PackageHelper.isContainerMounted(cid);
13179            if (mounted) {
13180                // Unmount first
13181                if (PackageHelper.unMountSdDir(cid)) {
13182                    mounted = false;
13183                }
13184            }
13185            if (!mounted && delete) {
13186                cleanUpResourcesLI(allCodePaths);
13187            }
13188            return !mounted;
13189        }
13190
13191        @Override
13192        int doPreCopy() {
13193            if (isFwdLocked()) {
13194                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13195                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13196                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13197                }
13198            }
13199
13200            return PackageManager.INSTALL_SUCCEEDED;
13201        }
13202
13203        @Override
13204        int doPostCopy(int uid) {
13205            if (isFwdLocked()) {
13206                if (uid < Process.FIRST_APPLICATION_UID
13207                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13208                                RES_FILE_NAME)) {
13209                    Slog.e(TAG, "Failed to finalize " + cid);
13210                    PackageHelper.destroySdDir(cid);
13211                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13212                }
13213            }
13214
13215            return PackageManager.INSTALL_SUCCEEDED;
13216        }
13217    }
13218
13219    /**
13220     * Logic to handle movement of existing installed applications.
13221     */
13222    class MoveInstallArgs extends InstallArgs {
13223        private File codeFile;
13224        private File resourceFile;
13225
13226        /** New install */
13227        MoveInstallArgs(InstallParams params) {
13228            super(params.origin, params.move, params.observer, params.installFlags,
13229                    params.installerPackageName, params.volumeUuid,
13230                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13231                    params.grantedRuntimePermissions,
13232                    params.traceMethod, params.traceCookie, params.certificates);
13233        }
13234
13235        int copyApk(IMediaContainerService imcs, boolean temp) {
13236            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13237                    + move.fromUuid + " to " + move.toUuid);
13238            synchronized (mInstaller) {
13239                try {
13240                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13241                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13242                } catch (InstallerException e) {
13243                    Slog.w(TAG, "Failed to move app", e);
13244                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13245                }
13246            }
13247
13248            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13249            resourceFile = codeFile;
13250            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13251
13252            return PackageManager.INSTALL_SUCCEEDED;
13253        }
13254
13255        int doPreInstall(int status) {
13256            if (status != PackageManager.INSTALL_SUCCEEDED) {
13257                cleanUp(move.toUuid);
13258            }
13259            return status;
13260        }
13261
13262        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13263            if (status != PackageManager.INSTALL_SUCCEEDED) {
13264                cleanUp(move.toUuid);
13265                return false;
13266            }
13267
13268            // Reflect the move in app info
13269            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13270            pkg.setApplicationInfoCodePath(pkg.codePath);
13271            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13272            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13273            pkg.setApplicationInfoResourcePath(pkg.codePath);
13274            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13275            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13276
13277            return true;
13278        }
13279
13280        int doPostInstall(int status, int uid) {
13281            if (status == PackageManager.INSTALL_SUCCEEDED) {
13282                cleanUp(move.fromUuid);
13283            } else {
13284                cleanUp(move.toUuid);
13285            }
13286            return status;
13287        }
13288
13289        @Override
13290        String getCodePath() {
13291            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13292        }
13293
13294        @Override
13295        String getResourcePath() {
13296            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13297        }
13298
13299        private boolean cleanUp(String volumeUuid) {
13300            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13301                    move.dataAppName);
13302            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13303            synchronized (mInstallLock) {
13304                // Clean up both app data and code
13305                removeDataDirsLI(volumeUuid, move.packageName);
13306                removeCodePathLI(codeFile);
13307            }
13308            return true;
13309        }
13310
13311        void cleanUpResourcesLI() {
13312            throw new UnsupportedOperationException();
13313        }
13314
13315        boolean doPostDeleteLI(boolean delete) {
13316            throw new UnsupportedOperationException();
13317        }
13318    }
13319
13320    static String getAsecPackageName(String packageCid) {
13321        int idx = packageCid.lastIndexOf("-");
13322        if (idx == -1) {
13323            return packageCid;
13324        }
13325        return packageCid.substring(0, idx);
13326    }
13327
13328    // Utility method used to create code paths based on package name and available index.
13329    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13330        String idxStr = "";
13331        int idx = 1;
13332        // Fall back to default value of idx=1 if prefix is not
13333        // part of oldCodePath
13334        if (oldCodePath != null) {
13335            String subStr = oldCodePath;
13336            // Drop the suffix right away
13337            if (suffix != null && subStr.endsWith(suffix)) {
13338                subStr = subStr.substring(0, subStr.length() - suffix.length());
13339            }
13340            // If oldCodePath already contains prefix find out the
13341            // ending index to either increment or decrement.
13342            int sidx = subStr.lastIndexOf(prefix);
13343            if (sidx != -1) {
13344                subStr = subStr.substring(sidx + prefix.length());
13345                if (subStr != null) {
13346                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13347                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13348                    }
13349                    try {
13350                        idx = Integer.parseInt(subStr);
13351                        if (idx <= 1) {
13352                            idx++;
13353                        } else {
13354                            idx--;
13355                        }
13356                    } catch(NumberFormatException e) {
13357                    }
13358                }
13359            }
13360        }
13361        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13362        return prefix + idxStr;
13363    }
13364
13365    private File getNextCodePath(File targetDir, String packageName) {
13366        int suffix = 1;
13367        File result;
13368        do {
13369            result = new File(targetDir, packageName + "-" + suffix);
13370            suffix++;
13371        } while (result.exists());
13372        return result;
13373    }
13374
13375    // Utility method that returns the relative package path with respect
13376    // to the installation directory. Like say for /data/data/com.test-1.apk
13377    // string com.test-1 is returned.
13378    static String deriveCodePathName(String codePath) {
13379        if (codePath == null) {
13380            return null;
13381        }
13382        final File codeFile = new File(codePath);
13383        final String name = codeFile.getName();
13384        if (codeFile.isDirectory()) {
13385            return name;
13386        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13387            final int lastDot = name.lastIndexOf('.');
13388            return name.substring(0, lastDot);
13389        } else {
13390            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13391            return null;
13392        }
13393    }
13394
13395    static class PackageInstalledInfo {
13396        String name;
13397        int uid;
13398        // The set of users that originally had this package installed.
13399        int[] origUsers;
13400        // The set of users that now have this package installed.
13401        int[] newUsers;
13402        PackageParser.Package pkg;
13403        int returnCode;
13404        String returnMsg;
13405        PackageRemovedInfo removedInfo;
13406        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13407
13408        public void setError(int code, String msg) {
13409            setReturnCode(code);
13410            setReturnMessage(msg);
13411            Slog.w(TAG, msg);
13412        }
13413
13414        public void setError(String msg, PackageParserException e) {
13415            setReturnCode(e.error);
13416            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13417            Slog.w(TAG, msg, e);
13418        }
13419
13420        public void setError(String msg, PackageManagerException e) {
13421            returnCode = e.error;
13422            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13423            Slog.w(TAG, msg, e);
13424        }
13425
13426        public void setReturnCode(int returnCode) {
13427            this.returnCode = returnCode;
13428            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13429            for (int i = 0; i < childCount; i++) {
13430                addedChildPackages.valueAt(i).returnCode = returnCode;
13431            }
13432        }
13433
13434        private void setReturnMessage(String returnMsg) {
13435            this.returnMsg = returnMsg;
13436            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13437            for (int i = 0; i < childCount; i++) {
13438                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13439            }
13440        }
13441
13442        // In some error cases we want to convey more info back to the observer
13443        String origPackage;
13444        String origPermission;
13445    }
13446
13447    /*
13448     * Install a non-existing package.
13449     */
13450    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
13451            UserHandle user, String installerPackageName, String volumeUuid,
13452            PackageInstalledInfo res) {
13453        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13454
13455        // Remember this for later, in case we need to rollback this install
13456        String pkgName = pkg.packageName;
13457
13458        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13459
13460        synchronized(mPackages) {
13461            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13462                // A package with the same name is already installed, though
13463                // it has been renamed to an older name.  The package we
13464                // are trying to install should be installed as an update to
13465                // the existing one, but that has not been requested, so bail.
13466                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13467                        + " without first uninstalling package running as "
13468                        + mSettings.mRenamedPackages.get(pkgName));
13469                return;
13470            }
13471            if (mPackages.containsKey(pkgName)) {
13472                // Don't allow installation over an existing package with the same name.
13473                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13474                        + " without first uninstalling.");
13475                return;
13476            }
13477        }
13478
13479        try {
13480            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
13481                    System.currentTimeMillis(), user);
13482
13483            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13484
13485            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13486                prepareAppDataAfterInstall(newPackage);
13487
13488            } else {
13489                // Remove package from internal structures, but keep around any
13490                // data that might have already existed
13491                deletePackageLI(pkgName, UserHandle.ALL, false, null,
13492                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13493            }
13494        } catch (PackageManagerException e) {
13495            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13496        }
13497
13498        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13499    }
13500
13501    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13502        // Can't rotate keys during boot or if sharedUser.
13503        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13504                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
13505            return false;
13506        }
13507        // app is using upgradeKeySets; make sure all are valid
13508        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13509        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
13510        for (int i = 0; i < upgradeKeySets.length; i++) {
13511            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
13512                Slog.wtf(TAG, "Package "
13513                         + (oldPs.name != null ? oldPs.name : "<null>")
13514                         + " contains upgrade-key-set reference to unknown key-set: "
13515                         + upgradeKeySets[i]
13516                         + " reverting to signatures check.");
13517                return false;
13518            }
13519        }
13520        return true;
13521    }
13522
13523    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
13524        // Upgrade keysets are being used.  Determine if new package has a superset of the
13525        // required keys.
13526        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
13527        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13528        for (int i = 0; i < upgradeKeySets.length; i++) {
13529            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
13530            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
13531                return true;
13532            }
13533        }
13534        return false;
13535    }
13536
13537    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
13538            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
13539        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
13540
13541        final PackageParser.Package oldPackage;
13542        final String pkgName = pkg.packageName;
13543        final int[] allUsers;
13544        final boolean weFroze;
13545
13546        // First find the old package info and check signatures
13547        synchronized(mPackages) {
13548            oldPackage = mPackages.get(pkgName);
13549            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
13550            if (isEphemeral && !oldIsEphemeral) {
13551                // can't downgrade from full to ephemeral
13552                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
13553                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13554                return;
13555            }
13556            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
13557            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13558            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13559                if (!checkUpgradeKeySetLP(ps, pkg)) {
13560                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13561                            "New package not signed by keys specified by upgrade-keysets: "
13562                                    + pkgName);
13563                    return;
13564                }
13565            } else {
13566                // default to original signature matching
13567                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
13568                        != PackageManager.SIGNATURE_MATCH) {
13569                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13570                            "New package has a different signature: " + pkgName);
13571                    return;
13572                }
13573            }
13574
13575            // In case of rollback, remember per-user/profile install state
13576            allUsers = sUserManager.getUserIds();
13577
13578            // Mark the app as frozen to prevent launching during the upgrade
13579            // process, and then kill all running instances
13580            if (!ps.frozen) {
13581                ps.frozen = true;
13582                weFroze = true;
13583            } else {
13584                weFroze = false;
13585            }
13586        }
13587
13588        try {
13589            replacePackageDirtyLI(pkg, oldPackage, parseFlags, scanFlags, user, allUsers,
13590                    installerPackageName, res);
13591        } finally {
13592            // Regardless of success or failure of upgrade steps above, always
13593            // unfreeze the package if we froze it
13594            if (weFroze) {
13595                unfreezePackage(pkgName);
13596            }
13597        }
13598    }
13599
13600    private void replacePackageDirtyLI(PackageParser.Package pkg, PackageParser.Package oldPackage,
13601            int parseFlags, int scanFlags, UserHandle user, int[] allUsers,
13602            String installerPackageName, PackageInstalledInfo res) {
13603        // Update what is removed
13604        res.removedInfo = new PackageRemovedInfo();
13605        res.removedInfo.uid = oldPackage.applicationInfo.uid;
13606        res.removedInfo.removedPackage = oldPackage.packageName;
13607        res.removedInfo.isUpdate = true;
13608        final int childCount = (oldPackage.childPackages != null)
13609                ? oldPackage.childPackages.size() : 0;
13610        for (int i = 0; i < childCount; i++) {
13611            boolean childPackageUpdated = false;
13612            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
13613            if (res.addedChildPackages != null) {
13614                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13615                if (childRes != null) {
13616                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
13617                    childRes.removedInfo.removedPackage = childPkg.packageName;
13618                    childRes.removedInfo.isUpdate = true;
13619                    childPackageUpdated = true;
13620                }
13621            }
13622            if (!childPackageUpdated) {
13623                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
13624                childRemovedRes.removedPackage = childPkg.packageName;
13625                childRemovedRes.isUpdate = false;
13626                childRemovedRes.dataRemoved = true;
13627                synchronized (mPackages) {
13628                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13629                    if (childPs != null) {
13630                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
13631                    }
13632                }
13633                if (res.removedInfo.removedChildPackages == null) {
13634                    res.removedInfo.removedChildPackages = new ArrayMap<>();
13635                }
13636                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
13637            }
13638        }
13639
13640        boolean sysPkg = (isSystemApp(oldPackage));
13641        if (sysPkg) {
13642            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13643                    user, allUsers, installerPackageName, res);
13644        } else {
13645            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13646                    user, allUsers, installerPackageName, res);
13647        }
13648    }
13649
13650    public List<String> getPreviousCodePaths(String packageName) {
13651        final PackageSetting ps = mSettings.mPackages.get(packageName);
13652        final List<String> result = new ArrayList<String>();
13653        if (ps != null && ps.oldCodePaths != null) {
13654            result.addAll(ps.oldCodePaths);
13655        }
13656        return result;
13657    }
13658
13659    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
13660            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13661            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13662        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
13663                + deletedPackage);
13664
13665        String pkgName = deletedPackage.packageName;
13666        boolean deletedPkg = true;
13667        boolean addedPkg = false;
13668        boolean updatedSettings = false;
13669        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
13670        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
13671                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
13672
13673        final long origUpdateTime = (pkg.mExtras != null)
13674                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
13675
13676        // First delete the existing package while retaining the data directory
13677        if (!deletePackageLI(pkgName, null, true, allUsers, deleteFlags,
13678                res.removedInfo, true, pkg)) {
13679            // If the existing package wasn't successfully deleted
13680            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
13681            deletedPkg = false;
13682        } else {
13683            // Successfully deleted the old package; proceed with replace.
13684
13685            // If deleted package lived in a container, give users a chance to
13686            // relinquish resources before killing.
13687            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
13688                if (DEBUG_INSTALL) {
13689                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
13690                }
13691                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
13692                final ArrayList<String> pkgList = new ArrayList<String>(1);
13693                pkgList.add(deletedPackage.applicationInfo.packageName);
13694                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
13695            }
13696
13697            deleteCodeCacheDirsLI(pkg);
13698            deleteProfilesLI(pkg, /*destroy*/ false);
13699
13700            try {
13701                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
13702                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
13703                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13704
13705                // Update the in-memory copy of the previous code paths.
13706                PackageSetting ps = mSettings.mPackages.get(pkgName);
13707                if (!killApp) {
13708                    if (ps.oldCodePaths == null) {
13709                        ps.oldCodePaths = new ArraySet<>();
13710                    }
13711                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
13712                    if (deletedPackage.splitCodePaths != null) {
13713                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
13714                    }
13715                } else {
13716                    ps.oldCodePaths = null;
13717                }
13718                if (ps.childPackageNames != null) {
13719                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
13720                        final String childPkgName = ps.childPackageNames.get(i);
13721                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
13722                        childPs.oldCodePaths = ps.oldCodePaths;
13723                    }
13724                }
13725                prepareAppDataAfterInstall(newPackage);
13726                addedPkg = true;
13727            } catch (PackageManagerException e) {
13728                res.setError("Package couldn't be installed in " + pkg.codePath, e);
13729            }
13730        }
13731
13732        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13733            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
13734
13735            // Revert all internal state mutations and added folders for the failed install
13736            if (addedPkg) {
13737                deletePackageLI(pkgName, null, true, allUsers, deleteFlags,
13738                        res.removedInfo, true, null);
13739            }
13740
13741            // Restore the old package
13742            if (deletedPkg) {
13743                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
13744                File restoreFile = new File(deletedPackage.codePath);
13745                // Parse old package
13746                boolean oldExternal = isExternal(deletedPackage);
13747                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
13748                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
13749                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
13750                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
13751                try {
13752                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
13753                            null);
13754                } catch (PackageManagerException e) {
13755                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
13756                            + e.getMessage());
13757                    return;
13758                }
13759
13760                synchronized (mPackages) {
13761                    // Ensure the installer package name up to date
13762                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13763
13764                    // Update permissions for restored package
13765                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13766
13767                    mSettings.writeLPr();
13768                }
13769
13770                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
13771            }
13772        } else {
13773            synchronized (mPackages) {
13774                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
13775                if (ps != null) {
13776                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
13777                    if (res.removedInfo.removedChildPackages != null) {
13778                        final int childCount = res.removedInfo.removedChildPackages.size();
13779                        // Iterate in reverse as we may modify the collection
13780                        for (int i = childCount - 1; i >= 0; i--) {
13781                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
13782                            if (res.addedChildPackages.containsKey(childPackageName)) {
13783                                res.removedInfo.removedChildPackages.removeAt(i);
13784                            } else {
13785                                PackageRemovedInfo childInfo = res.removedInfo
13786                                        .removedChildPackages.valueAt(i);
13787                                childInfo.removedForAllUsers = mPackages.get(
13788                                        childInfo.removedPackage) == null;
13789                            }
13790                        }
13791                    }
13792                }
13793            }
13794        }
13795    }
13796
13797    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
13798            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13799            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13800        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
13801                + ", old=" + deletedPackage);
13802
13803        final boolean disabledSystem;
13804
13805        // Set the system/privileged flags as needed
13806        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
13807        if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
13808                != 0) {
13809            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13810        }
13811
13812        // Kill package processes including services, providers, etc.
13813        killPackage(deletedPackage, "replace sys pkg");
13814
13815        // Remove existing system package
13816        removePackageLI(deletedPackage, true);
13817
13818        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
13819        if (!disabledSystem) {
13820            // We didn't need to disable the .apk as a current system package,
13821            // which means we are replacing another update that is already
13822            // installed.  We need to make sure to delete the older one's .apk.
13823            res.removedInfo.args = createInstallArgsForExisting(0,
13824                    deletedPackage.applicationInfo.getCodePath(),
13825                    deletedPackage.applicationInfo.getResourcePath(),
13826                    getAppDexInstructionSets(deletedPackage.applicationInfo));
13827        } else {
13828            res.removedInfo.args = null;
13829        }
13830
13831        // Successfully disabled the old package. Now proceed with re-installation
13832        deleteCodeCacheDirsLI(pkg);
13833        deleteProfilesLI(pkg, /*destroy*/ false);
13834
13835        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13836        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
13837                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
13838
13839        PackageParser.Package newPackage = null;
13840        try {
13841            // Add the package to the internal data structures
13842            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
13843
13844            // Set the update and install times
13845            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
13846            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
13847                    System.currentTimeMillis());
13848
13849            // Check for shared user id changes
13850            String invalidPackageName = getParentOrChildPackageChangedSharedUser(
13851                    deletedPackage, newPackage);
13852            if (invalidPackageName != null) {
13853                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13854                        "Forbidding shared user change from " + deletedPkgSetting.sharedUser
13855                                + " to " + invalidPackageName);
13856            }
13857
13858            // Update the package dynamic state if succeeded
13859            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13860                // Now that the install succeeded make sure we remove data
13861                // directories for any child package the update removed.
13862                final int deletedChildCount = (deletedPackage.childPackages != null)
13863                        ? deletedPackage.childPackages.size() : 0;
13864                final int newChildCount = (newPackage.childPackages != null)
13865                        ? newPackage.childPackages.size() : 0;
13866                for (int i = 0; i < deletedChildCount; i++) {
13867                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
13868                    boolean childPackageDeleted = true;
13869                    for (int j = 0; j < newChildCount; j++) {
13870                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
13871                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
13872                            childPackageDeleted = false;
13873                            break;
13874                        }
13875                    }
13876                    if (childPackageDeleted) {
13877                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
13878                                deletedChildPkg.packageName);
13879                        if (ps != null && res.removedInfo.removedChildPackages != null) {
13880                            PackageRemovedInfo removedChildRes = res.removedInfo
13881                                    .removedChildPackages.get(deletedChildPkg.packageName);
13882                            removePackageDataLI(ps, allUsers, removedChildRes, 0, false);
13883                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
13884                        }
13885                    }
13886                }
13887
13888                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13889                prepareAppDataAfterInstall(newPackage);
13890            }
13891        } catch (PackageManagerException e) {
13892            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
13893            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13894        }
13895
13896        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13897            // Re installation failed. Restore old information
13898            // Remove new pkg information
13899            if (newPackage != null) {
13900                removeInstalledPackageLI(newPackage, true);
13901            }
13902            // Add back the old system package
13903            try {
13904                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
13905            } catch (PackageManagerException e) {
13906                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
13907            }
13908
13909            synchronized (mPackages) {
13910                if (disabledSystem) {
13911                    enableSystemPackageLPw(deletedPackage);
13912                }
13913
13914                // Ensure the installer package name up to date
13915                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13916
13917                // Update permissions for restored package
13918                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13919
13920                mSettings.writeLPr();
13921            }
13922
13923            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
13924                    + " after failed upgrade");
13925        }
13926    }
13927
13928    /**
13929     * Checks whether the parent or any of the child packages have a change shared
13930     * user. For a package to be a valid update the shred users of the parent and
13931     * the children should match. We may later support changing child shared users.
13932     * @param oldPkg The updated package.
13933     * @param newPkg The update package.
13934     * @return The shared user that change between the versions.
13935     */
13936    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
13937            PackageParser.Package newPkg) {
13938        // Check parent shared user
13939        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
13940            return newPkg.packageName;
13941        }
13942        // Check child shared users
13943        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13944        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
13945        for (int i = 0; i < newChildCount; i++) {
13946            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
13947            // If this child was present, did it have the same shared user?
13948            for (int j = 0; j < oldChildCount; j++) {
13949                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
13950                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
13951                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
13952                    return newChildPkg.packageName;
13953                }
13954            }
13955        }
13956        return null;
13957    }
13958
13959    private void removeNativeBinariesLI(PackageSetting ps) {
13960        // Remove the lib path for the parent package
13961        if (ps != null) {
13962            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13963            // Remove the lib path for the child packages
13964            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
13965            for (int i = 0; i < childCount; i++) {
13966                PackageSetting childPs = null;
13967                synchronized (mPackages) {
13968                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
13969                }
13970                if (childPs != null) {
13971                    NativeLibraryHelper.removeNativeBinariesLI(childPs
13972                            .legacyNativeLibraryPathString);
13973                }
13974            }
13975        }
13976    }
13977
13978    private void enableSystemPackageLPw(PackageParser.Package pkg) {
13979        // Enable the parent package
13980        mSettings.enableSystemPackageLPw(pkg.packageName);
13981        // Enable the child packages
13982        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13983        for (int i = 0; i < childCount; i++) {
13984            PackageParser.Package childPkg = pkg.childPackages.get(i);
13985            mSettings.enableSystemPackageLPw(childPkg.packageName);
13986        }
13987    }
13988
13989    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
13990            PackageParser.Package newPkg) {
13991        // Disable the parent package (parent always replaced)
13992        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
13993        // Disable the child packages
13994        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13995        for (int i = 0; i < childCount; i++) {
13996            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
13997            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
13998            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
13999        }
14000        return disabled;
14001    }
14002
14003    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14004            String installerPackageName) {
14005        // Enable the parent package
14006        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14007        // Enable the child packages
14008        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14009        for (int i = 0; i < childCount; i++) {
14010            PackageParser.Package childPkg = pkg.childPackages.get(i);
14011            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14012        }
14013    }
14014
14015    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14016        // Collect all used permissions in the UID
14017        ArraySet<String> usedPermissions = new ArraySet<>();
14018        final int packageCount = su.packages.size();
14019        for (int i = 0; i < packageCount; i++) {
14020            PackageSetting ps = su.packages.valueAt(i);
14021            if (ps.pkg == null) {
14022                continue;
14023            }
14024            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14025            for (int j = 0; j < requestedPermCount; j++) {
14026                String permission = ps.pkg.requestedPermissions.get(j);
14027                BasePermission bp = mSettings.mPermissions.get(permission);
14028                if (bp != null) {
14029                    usedPermissions.add(permission);
14030                }
14031            }
14032        }
14033
14034        PermissionsState permissionsState = su.getPermissionsState();
14035        // Prune install permissions
14036        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14037        final int installPermCount = installPermStates.size();
14038        for (int i = installPermCount - 1; i >= 0;  i--) {
14039            PermissionState permissionState = installPermStates.get(i);
14040            if (!usedPermissions.contains(permissionState.getName())) {
14041                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14042                if (bp != null) {
14043                    permissionsState.revokeInstallPermission(bp);
14044                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14045                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14046                }
14047            }
14048        }
14049
14050        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14051
14052        // Prune runtime permissions
14053        for (int userId : allUserIds) {
14054            List<PermissionState> runtimePermStates = permissionsState
14055                    .getRuntimePermissionStates(userId);
14056            final int runtimePermCount = runtimePermStates.size();
14057            for (int i = runtimePermCount - 1; i >= 0; i--) {
14058                PermissionState permissionState = runtimePermStates.get(i);
14059                if (!usedPermissions.contains(permissionState.getName())) {
14060                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14061                    if (bp != null) {
14062                        permissionsState.revokeRuntimePermission(bp, userId);
14063                        permissionsState.updatePermissionFlags(bp, userId,
14064                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14065                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14066                                runtimePermissionChangedUserIds, userId);
14067                    }
14068                }
14069            }
14070        }
14071
14072        return runtimePermissionChangedUserIds;
14073    }
14074
14075    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14076            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14077        // Update the parent package setting
14078        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14079                res, user);
14080        // Update the child packages setting
14081        final int childCount = (newPackage.childPackages != null)
14082                ? newPackage.childPackages.size() : 0;
14083        for (int i = 0; i < childCount; i++) {
14084            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14085            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14086            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14087                    childRes.origUsers, childRes, user);
14088        }
14089    }
14090
14091    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14092            String installerPackageName, int[] allUsers, int[] installedForUsers,
14093            PackageInstalledInfo res, UserHandle user) {
14094        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14095
14096        String pkgName = newPackage.packageName;
14097        synchronized (mPackages) {
14098            //write settings. the installStatus will be incomplete at this stage.
14099            //note that the new package setting would have already been
14100            //added to mPackages. It hasn't been persisted yet.
14101            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14102            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14103            mSettings.writeLPr();
14104            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14105        }
14106
14107        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14108        synchronized (mPackages) {
14109            updatePermissionsLPw(newPackage.packageName, newPackage,
14110                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14111                            ? UPDATE_PERMISSIONS_ALL : 0));
14112            // For system-bundled packages, we assume that installing an upgraded version
14113            // of the package implies that the user actually wants to run that new code,
14114            // so we enable the package.
14115            PackageSetting ps = mSettings.mPackages.get(pkgName);
14116            final int userId = user.getIdentifier();
14117            if (ps != null) {
14118                if (isSystemApp(newPackage)) {
14119                    if (DEBUG_INSTALL) {
14120                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14121                    }
14122                    // Enable system package for requested users
14123                    if (res.origUsers != null) {
14124                        for (int origUserId : res.origUsers) {
14125                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14126                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14127                                        origUserId, installerPackageName);
14128                            }
14129                        }
14130                    }
14131                    // Also convey the prior install/uninstall state
14132                    if (allUsers != null && installedForUsers != null) {
14133                        for (int currentUserId : allUsers) {
14134                            final boolean installed = ArrayUtils.contains(
14135                                    installedForUsers, currentUserId);
14136                            if (DEBUG_INSTALL) {
14137                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14138                            }
14139                            ps.setInstalled(installed, currentUserId);
14140                        }
14141                        // these install state changes will be persisted in the
14142                        // upcoming call to mSettings.writeLPr().
14143                    }
14144                }
14145                // It's implied that when a user requests installation, they want the app to be
14146                // installed and enabled.
14147                if (userId != UserHandle.USER_ALL) {
14148                    ps.setInstalled(true, userId);
14149                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14150                }
14151            }
14152            res.name = pkgName;
14153            res.uid = newPackage.applicationInfo.uid;
14154            res.pkg = newPackage;
14155            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14156            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14157            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14158            //to update install status
14159            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14160            mSettings.writeLPr();
14161            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14162        }
14163
14164        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14165    }
14166
14167    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14168        try {
14169            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14170            installPackageLI(args, res);
14171        } finally {
14172            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14173        }
14174    }
14175
14176    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14177        final int installFlags = args.installFlags;
14178        final String installerPackageName = args.installerPackageName;
14179        final String volumeUuid = args.volumeUuid;
14180        final File tmpPackageFile = new File(args.getCodePath());
14181        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14182        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14183                || (args.volumeUuid != null));
14184        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14185        boolean replace = false;
14186        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14187        if (args.move != null) {
14188            // moving a complete application; perform an initial scan on the new install location
14189            scanFlags |= SCAN_INITIAL;
14190        }
14191        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14192            scanFlags |= SCAN_DONT_KILL_APP;
14193        }
14194
14195        // Result object to be returned
14196        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14197
14198        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14199
14200        // Sanity check
14201        if (ephemeral && (forwardLocked || onExternal)) {
14202            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14203                    + " external=" + onExternal);
14204            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14205            return;
14206        }
14207
14208        // Retrieve PackageSettings and parse package
14209        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14210                | PackageParser.PARSE_ENFORCE_CODE
14211                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14212                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14213                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
14214        PackageParser pp = new PackageParser();
14215        pp.setSeparateProcesses(mSeparateProcesses);
14216        pp.setDisplayMetrics(mMetrics);
14217
14218        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14219        final PackageParser.Package pkg;
14220        try {
14221            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14222        } catch (PackageParserException e) {
14223            res.setError("Failed parse during installPackageLI", e);
14224            return;
14225        } finally {
14226            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14227        }
14228
14229        // If we are installing a clustered package add results for the children
14230        if (pkg.childPackages != null) {
14231            synchronized (mPackages) {
14232                final int childCount = pkg.childPackages.size();
14233                for (int i = 0; i < childCount; i++) {
14234                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14235                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14236                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14237                    childRes.pkg = childPkg;
14238                    childRes.name = childPkg.packageName;
14239                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14240                    if (childPs != null) {
14241                        childRes.origUsers = childPs.queryInstalledUsers(
14242                                sUserManager.getUserIds(), true);
14243                    }
14244                    if ((mPackages.containsKey(childPkg.packageName))) {
14245                        childRes.removedInfo = new PackageRemovedInfo();
14246                        childRes.removedInfo.removedPackage = childPkg.packageName;
14247                    }
14248                    if (res.addedChildPackages == null) {
14249                        res.addedChildPackages = new ArrayMap<>();
14250                    }
14251                    res.addedChildPackages.put(childPkg.packageName, childRes);
14252                }
14253            }
14254        }
14255
14256        // If package doesn't declare API override, mark that we have an install
14257        // time CPU ABI override.
14258        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14259            pkg.cpuAbiOverride = args.abiOverride;
14260        }
14261
14262        String pkgName = res.name = pkg.packageName;
14263        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14264            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14265                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14266                return;
14267            }
14268        }
14269
14270        try {
14271            // either use what we've been given or parse directly from the APK
14272            if (args.certificates != null) {
14273                try {
14274                    PackageParser.populateCertificates(pkg, args.certificates);
14275                } catch (PackageParserException e) {
14276                    // there was something wrong with the certificates we were given;
14277                    // try to pull them from the APK
14278                    PackageParser.collectCertificates(pkg, parseFlags);
14279                }
14280            } else {
14281                PackageParser.collectCertificates(pkg, parseFlags);
14282            }
14283        } catch (PackageParserException e) {
14284            res.setError("Failed collect during installPackageLI", e);
14285            return;
14286        }
14287
14288        // Get rid of all references to package scan path via parser.
14289        pp = null;
14290        String oldCodePath = null;
14291        boolean systemApp = false;
14292        synchronized (mPackages) {
14293            // Check if installing already existing package
14294            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14295                String oldName = mSettings.mRenamedPackages.get(pkgName);
14296                if (pkg.mOriginalPackages != null
14297                        && pkg.mOriginalPackages.contains(oldName)
14298                        && mPackages.containsKey(oldName)) {
14299                    // This package is derived from an original package,
14300                    // and this device has been updating from that original
14301                    // name.  We must continue using the original name, so
14302                    // rename the new package here.
14303                    pkg.setPackageName(oldName);
14304                    pkgName = pkg.packageName;
14305                    replace = true;
14306                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14307                            + oldName + " pkgName=" + pkgName);
14308                } else if (mPackages.containsKey(pkgName)) {
14309                    // This package, under its official name, already exists
14310                    // on the device; we should replace it.
14311                    replace = true;
14312                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14313                }
14314
14315                // Child packages are installed through the parent package
14316                if (pkg.parentPackage != null) {
14317                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14318                            "Package " + pkg.packageName + " is child of package "
14319                                    + pkg.parentPackage.parentPackage + ". Child packages "
14320                                    + "can be updated only through the parent package.");
14321                    return;
14322                }
14323
14324                if (replace) {
14325                    // Prevent apps opting out from runtime permissions
14326                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14327                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14328                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14329                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14330                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14331                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14332                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14333                                        + " doesn't support runtime permissions but the old"
14334                                        + " target SDK " + oldTargetSdk + " does.");
14335                        return;
14336                    }
14337
14338                    // Prevent installing of child packages
14339                    if (oldPackage.parentPackage != null) {
14340                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14341                                "Package " + pkg.packageName + " is child of package "
14342                                        + oldPackage.parentPackage + ". Child packages "
14343                                        + "can be updated only through the parent package.");
14344                        return;
14345                    }
14346                }
14347            }
14348
14349            PackageSetting ps = mSettings.mPackages.get(pkgName);
14350            if (ps != null) {
14351                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14352
14353                // Quick sanity check that we're signed correctly if updating;
14354                // we'll check this again later when scanning, but we want to
14355                // bail early here before tripping over redefined permissions.
14356                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14357                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14358                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14359                                + pkg.packageName + " upgrade keys do not match the "
14360                                + "previously installed version");
14361                        return;
14362                    }
14363                } else {
14364                    try {
14365                        verifySignaturesLP(ps, pkg);
14366                    } catch (PackageManagerException e) {
14367                        res.setError(e.error, e.getMessage());
14368                        return;
14369                    }
14370                }
14371
14372                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14373                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14374                    systemApp = (ps.pkg.applicationInfo.flags &
14375                            ApplicationInfo.FLAG_SYSTEM) != 0;
14376                }
14377                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14378            }
14379
14380            // Check whether the newly-scanned package wants to define an already-defined perm
14381            int N = pkg.permissions.size();
14382            for (int i = N-1; i >= 0; i--) {
14383                PackageParser.Permission perm = pkg.permissions.get(i);
14384                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14385                if (bp != null) {
14386                    // If the defining package is signed with our cert, it's okay.  This
14387                    // also includes the "updating the same package" case, of course.
14388                    // "updating same package" could also involve key-rotation.
14389                    final boolean sigsOk;
14390                    if (bp.sourcePackage.equals(pkg.packageName)
14391                            && (bp.packageSetting instanceof PackageSetting)
14392                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14393                                    scanFlags))) {
14394                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14395                    } else {
14396                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14397                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14398                    }
14399                    if (!sigsOk) {
14400                        // If the owning package is the system itself, we log but allow
14401                        // install to proceed; we fail the install on all other permission
14402                        // redefinitions.
14403                        if (!bp.sourcePackage.equals("android")) {
14404                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14405                                    + pkg.packageName + " attempting to redeclare permission "
14406                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14407                            res.origPermission = perm.info.name;
14408                            res.origPackage = bp.sourcePackage;
14409                            return;
14410                        } else {
14411                            Slog.w(TAG, "Package " + pkg.packageName
14412                                    + " attempting to redeclare system permission "
14413                                    + perm.info.name + "; ignoring new declaration");
14414                            pkg.permissions.remove(i);
14415                        }
14416                    }
14417                }
14418            }
14419        }
14420
14421        if (systemApp) {
14422            if (onExternal) {
14423                // Abort update; system app can't be replaced with app on sdcard
14424                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14425                        "Cannot install updates to system apps on sdcard");
14426                return;
14427            } else if (ephemeral) {
14428                // Abort update; system app can't be replaced with an ephemeral app
14429                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14430                        "Cannot update a system app with an ephemeral app");
14431                return;
14432            }
14433        }
14434
14435        if (args.move != null) {
14436            // We did an in-place move, so dex is ready to roll
14437            scanFlags |= SCAN_NO_DEX;
14438            scanFlags |= SCAN_MOVE;
14439
14440            synchronized (mPackages) {
14441                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14442                if (ps == null) {
14443                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
14444                            "Missing settings for moved package " + pkgName);
14445                }
14446
14447                // We moved the entire application as-is, so bring over the
14448                // previously derived ABI information.
14449                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
14450                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
14451            }
14452
14453        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
14454            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
14455            scanFlags |= SCAN_NO_DEX;
14456
14457            try {
14458                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
14459                    args.abiOverride : pkg.cpuAbiOverride);
14460                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
14461                        true /* extract libs */);
14462            } catch (PackageManagerException pme) {
14463                Slog.e(TAG, "Error deriving application ABI", pme);
14464                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
14465                return;
14466            }
14467
14468
14469            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
14470            // Do not run PackageDexOptimizer through the local performDexOpt
14471            // method because `pkg` is not in `mPackages` yet.
14472            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
14473                    false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL));
14474            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14475            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
14476                String msg = "Extracking package failed for " + pkgName;
14477                res.setError(INSTALL_FAILED_DEXOPT, msg);
14478                return;
14479            }
14480        }
14481
14482        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
14483            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
14484            return;
14485        }
14486
14487        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
14488
14489        if (replace) {
14490            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
14491                    installerPackageName, res);
14492        } else {
14493            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
14494                    args.user, installerPackageName, volumeUuid, res);
14495        }
14496        synchronized (mPackages) {
14497            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14498            if (ps != null) {
14499                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14500            }
14501
14502            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14503            for (int i = 0; i < childCount; i++) {
14504                PackageParser.Package childPkg = pkg.childPackages.get(i);
14505                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14506                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14507                if (childPs != null) {
14508                    childRes.newUsers = childPs.queryInstalledUsers(
14509                            sUserManager.getUserIds(), true);
14510                }
14511            }
14512        }
14513    }
14514
14515    private void startIntentFilterVerifications(int userId, boolean replacing,
14516            PackageParser.Package pkg) {
14517        if (mIntentFilterVerifierComponent == null) {
14518            Slog.w(TAG, "No IntentFilter verification will not be done as "
14519                    + "there is no IntentFilterVerifier available!");
14520            return;
14521        }
14522
14523        final int verifierUid = getPackageUid(
14524                mIntentFilterVerifierComponent.getPackageName(),
14525                MATCH_DEBUG_TRIAGED_MISSING,
14526                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
14527
14528        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14529        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
14530        mHandler.sendMessage(msg);
14531
14532        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14533        for (int i = 0; i < childCount; i++) {
14534            PackageParser.Package childPkg = pkg.childPackages.get(i);
14535            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14536            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
14537            mHandler.sendMessage(msg);
14538        }
14539    }
14540
14541    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
14542            PackageParser.Package pkg) {
14543        int size = pkg.activities.size();
14544        if (size == 0) {
14545            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14546                    "No activity, so no need to verify any IntentFilter!");
14547            return;
14548        }
14549
14550        final boolean hasDomainURLs = hasDomainURLs(pkg);
14551        if (!hasDomainURLs) {
14552            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14553                    "No domain URLs, so no need to verify any IntentFilter!");
14554            return;
14555        }
14556
14557        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
14558                + " if any IntentFilter from the " + size
14559                + " Activities needs verification ...");
14560
14561        int count = 0;
14562        final String packageName = pkg.packageName;
14563
14564        synchronized (mPackages) {
14565            // If this is a new install and we see that we've already run verification for this
14566            // package, we have nothing to do: it means the state was restored from backup.
14567            if (!replacing) {
14568                IntentFilterVerificationInfo ivi =
14569                        mSettings.getIntentFilterVerificationLPr(packageName);
14570                if (ivi != null) {
14571                    if (DEBUG_DOMAIN_VERIFICATION) {
14572                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
14573                                + ivi.getStatusString());
14574                    }
14575                    return;
14576                }
14577            }
14578
14579            // If any filters need to be verified, then all need to be.
14580            boolean needToVerify = false;
14581            for (PackageParser.Activity a : pkg.activities) {
14582                for (ActivityIntentInfo filter : a.intents) {
14583                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
14584                        if (DEBUG_DOMAIN_VERIFICATION) {
14585                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
14586                        }
14587                        needToVerify = true;
14588                        break;
14589                    }
14590                }
14591            }
14592
14593            if (needToVerify) {
14594                final int verificationId = mIntentFilterVerificationToken++;
14595                for (PackageParser.Activity a : pkg.activities) {
14596                    for (ActivityIntentInfo filter : a.intents) {
14597                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
14598                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14599                                    "Verification needed for IntentFilter:" + filter.toString());
14600                            mIntentFilterVerifier.addOneIntentFilterVerification(
14601                                    verifierUid, userId, verificationId, filter, packageName);
14602                            count++;
14603                        }
14604                    }
14605                }
14606            }
14607        }
14608
14609        if (count > 0) {
14610            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
14611                    + " IntentFilter verification" + (count > 1 ? "s" : "")
14612                    +  " for userId:" + userId);
14613            mIntentFilterVerifier.startVerifications(userId);
14614        } else {
14615            if (DEBUG_DOMAIN_VERIFICATION) {
14616                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
14617            }
14618        }
14619    }
14620
14621    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
14622        final ComponentName cn  = filter.activity.getComponentName();
14623        final String packageName = cn.getPackageName();
14624
14625        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
14626                packageName);
14627        if (ivi == null) {
14628            return true;
14629        }
14630        int status = ivi.getStatus();
14631        switch (status) {
14632            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
14633            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
14634                return true;
14635
14636            default:
14637                // Nothing to do
14638                return false;
14639        }
14640    }
14641
14642    private static boolean isMultiArch(ApplicationInfo info) {
14643        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
14644    }
14645
14646    private static boolean isExternal(PackageParser.Package pkg) {
14647        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14648    }
14649
14650    private static boolean isExternal(PackageSetting ps) {
14651        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14652    }
14653
14654    private static boolean isEphemeral(PackageParser.Package pkg) {
14655        return pkg.applicationInfo.isEphemeralApp();
14656    }
14657
14658    private static boolean isEphemeral(PackageSetting ps) {
14659        return ps.pkg != null && isEphemeral(ps.pkg);
14660    }
14661
14662    private static boolean isSystemApp(PackageParser.Package pkg) {
14663        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
14664    }
14665
14666    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
14667        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14668    }
14669
14670    private static boolean hasDomainURLs(PackageParser.Package pkg) {
14671        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
14672    }
14673
14674    private static boolean isSystemApp(PackageSetting ps) {
14675        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
14676    }
14677
14678    private static boolean isUpdatedSystemApp(PackageSetting ps) {
14679        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
14680    }
14681
14682    private int packageFlagsToInstallFlags(PackageSetting ps) {
14683        int installFlags = 0;
14684        if (isEphemeral(ps)) {
14685            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14686        }
14687        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
14688            // This existing package was an external ASEC install when we have
14689            // the external flag without a UUID
14690            installFlags |= PackageManager.INSTALL_EXTERNAL;
14691        }
14692        if (ps.isForwardLocked()) {
14693            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
14694        }
14695        return installFlags;
14696    }
14697
14698    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
14699        if (isExternal(pkg)) {
14700            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14701                return StorageManager.UUID_PRIMARY_PHYSICAL;
14702            } else {
14703                return pkg.volumeUuid;
14704            }
14705        } else {
14706            return StorageManager.UUID_PRIVATE_INTERNAL;
14707        }
14708    }
14709
14710    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
14711        if (isExternal(pkg)) {
14712            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14713                return mSettings.getExternalVersion();
14714            } else {
14715                return mSettings.findOrCreateVersion(pkg.volumeUuid);
14716            }
14717        } else {
14718            return mSettings.getInternalVersion();
14719        }
14720    }
14721
14722    private void deleteTempPackageFiles() {
14723        final FilenameFilter filter = new FilenameFilter() {
14724            public boolean accept(File dir, String name) {
14725                return name.startsWith("vmdl") && name.endsWith(".tmp");
14726            }
14727        };
14728        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
14729            file.delete();
14730        }
14731    }
14732
14733    @Override
14734    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
14735            int flags) {
14736        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
14737                flags);
14738    }
14739
14740    @Override
14741    public void deletePackage(final String packageName,
14742            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
14743        mContext.enforceCallingOrSelfPermission(
14744                android.Manifest.permission.DELETE_PACKAGES, null);
14745        Preconditions.checkNotNull(packageName);
14746        Preconditions.checkNotNull(observer);
14747        final int uid = Binder.getCallingUid();
14748        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
14749        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
14750        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
14751            mContext.enforceCallingOrSelfPermission(
14752                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14753                    "deletePackage for user " + userId);
14754        }
14755
14756        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
14757            try {
14758                observer.onPackageDeleted(packageName,
14759                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
14760            } catch (RemoteException re) {
14761            }
14762            return;
14763        }
14764
14765        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
14766            try {
14767                observer.onPackageDeleted(packageName,
14768                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
14769            } catch (RemoteException re) {
14770            }
14771            return;
14772        }
14773
14774        if (DEBUG_REMOVE) {
14775            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
14776                    + " deleteAllUsers: " + deleteAllUsers );
14777        }
14778        // Queue up an async operation since the package deletion may take a little while.
14779        mHandler.post(new Runnable() {
14780            public void run() {
14781                mHandler.removeCallbacks(this);
14782                int returnCode;
14783                if (!deleteAllUsers) {
14784                    returnCode = deletePackageX(packageName, userId, flags);
14785                } else {
14786                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
14787                    // If nobody is blocking uninstall, proceed with delete for all users
14788                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
14789                        returnCode = deletePackageX(packageName, userId, flags);
14790                    } else {
14791                        // Otherwise uninstall individually for users with blockUninstalls=false
14792                        final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS;
14793                        for (int userId : users) {
14794                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
14795                                returnCode = deletePackageX(packageName, userId, userFlags);
14796                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
14797                                    Slog.w(TAG, "Package delete failed for user " + userId
14798                                            + ", returnCode " + returnCode);
14799                                }
14800                            }
14801                        }
14802                        // The app has only been marked uninstalled for certain users.
14803                        // We still need to report that delete was blocked
14804                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
14805                    }
14806                }
14807                try {
14808                    observer.onPackageDeleted(packageName, returnCode, null);
14809                } catch (RemoteException e) {
14810                    Log.i(TAG, "Observer no longer exists.");
14811                } //end catch
14812            } //end run
14813        });
14814    }
14815
14816    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
14817        int[] result = EMPTY_INT_ARRAY;
14818        for (int userId : userIds) {
14819            if (getBlockUninstallForUser(packageName, userId)) {
14820                result = ArrayUtils.appendInt(result, userId);
14821            }
14822        }
14823        return result;
14824    }
14825
14826    @Override
14827    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
14828        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
14829    }
14830
14831    private boolean isPackageDeviceAdmin(String packageName, int userId) {
14832        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14833                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14834        try {
14835            if (dpm != null) {
14836                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
14837                        /* callingUserOnly =*/ false);
14838                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
14839                        : deviceOwnerComponentName.getPackageName();
14840                // Does the package contains the device owner?
14841                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
14842                // this check is probably not needed, since DO should be registered as a device
14843                // admin on some user too. (Original bug for this: b/17657954)
14844                if (packageName.equals(deviceOwnerPackageName)) {
14845                    return true;
14846                }
14847                // Does it contain a device admin for any user?
14848                int[] users;
14849                if (userId == UserHandle.USER_ALL) {
14850                    users = sUserManager.getUserIds();
14851                } else {
14852                    users = new int[]{userId};
14853                }
14854                for (int i = 0; i < users.length; ++i) {
14855                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
14856                        return true;
14857                    }
14858                }
14859            }
14860        } catch (RemoteException e) {
14861        }
14862        return false;
14863    }
14864
14865    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
14866        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
14867    }
14868
14869    /**
14870     *  This method is an internal method that could be get invoked either
14871     *  to delete an installed package or to clean up a failed installation.
14872     *  After deleting an installed package, a broadcast is sent to notify any
14873     *  listeners that the package has been installed. For cleaning up a failed
14874     *  installation, the broadcast is not necessary since the package's
14875     *  installation wouldn't have sent the initial broadcast either
14876     *  The key steps in deleting a package are
14877     *  deleting the package information in internal structures like mPackages,
14878     *  deleting the packages base directories through installd
14879     *  updating mSettings to reflect current status
14880     *  persisting settings for later use
14881     *  sending a broadcast if necessary
14882     */
14883    private int deletePackageX(String packageName, int userId, int flags) {
14884        final PackageRemovedInfo info = new PackageRemovedInfo();
14885        final boolean res;
14886
14887        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
14888                ? UserHandle.ALL : new UserHandle(userId);
14889
14890        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
14891            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
14892            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
14893        }
14894
14895        PackageSetting uninstalledPs = null;
14896
14897        // for the uninstall-updates case and restricted profiles, remember the per-
14898        // user handle installed state
14899        int[] allUsers;
14900        synchronized (mPackages) {
14901            uninstalledPs = mSettings.mPackages.get(packageName);
14902            if (uninstalledPs == null) {
14903                Slog.w(TAG, "Not removing non-existent package " + packageName);
14904                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14905            }
14906            allUsers = sUserManager.getUserIds();
14907            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
14908        }
14909
14910        synchronized (mInstallLock) {
14911            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
14912            res = deletePackageLI(packageName, removeForUser, true, allUsers,
14913                    flags | REMOVE_CHATTY, info, true, null);
14914            synchronized (mPackages) {
14915                if (res) {
14916                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
14917                }
14918            }
14919        }
14920
14921        if (res) {
14922            final boolean killApp = (flags & PackageManager.INSTALL_DONT_KILL_APP) == 0;
14923            info.sendPackageRemovedBroadcasts(killApp);
14924            info.sendSystemPackageUpdatedBroadcasts();
14925            info.sendSystemPackageAppearedBroadcasts();
14926        }
14927        // Force a gc here.
14928        Runtime.getRuntime().gc();
14929        // Delete the resources here after sending the broadcast to let
14930        // other processes clean up before deleting resources.
14931        if (info.args != null) {
14932            synchronized (mInstallLock) {
14933                info.args.doPostDeleteLI(true);
14934            }
14935        }
14936
14937        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14938    }
14939
14940    class PackageRemovedInfo {
14941        String removedPackage;
14942        int uid = -1;
14943        int removedAppId = -1;
14944        int[] origUsers;
14945        int[] removedUsers = null;
14946        boolean isRemovedPackageSystemUpdate = false;
14947        boolean isUpdate;
14948        boolean dataRemoved;
14949        boolean removedForAllUsers;
14950        // Clean up resources deleted packages.
14951        InstallArgs args = null;
14952        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
14953        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
14954
14955        void sendPackageRemovedBroadcasts(boolean killApp) {
14956            sendPackageRemovedBroadcastInternal(killApp);
14957            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
14958            for (int i = 0; i < childCount; i++) {
14959                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14960                childInfo.sendPackageRemovedBroadcastInternal(killApp);
14961            }
14962        }
14963
14964        void sendSystemPackageUpdatedBroadcasts() {
14965            if (isRemovedPackageSystemUpdate) {
14966                sendSystemPackageUpdatedBroadcastsInternal();
14967                final int childCount = (removedChildPackages != null)
14968                        ? removedChildPackages.size() : 0;
14969                for (int i = 0; i < childCount; i++) {
14970                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14971                    if (childInfo.isRemovedPackageSystemUpdate) {
14972                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
14973                    }
14974                }
14975            }
14976        }
14977
14978        void sendSystemPackageAppearedBroadcasts() {
14979            final int packageCount = (appearedChildPackages != null)
14980                    ? appearedChildPackages.size() : 0;
14981            for (int i = 0; i < packageCount; i++) {
14982                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
14983                for (int userId : installedInfo.newUsers) {
14984                    sendPackageAddedForUser(installedInfo.name, true,
14985                            UserHandle.getAppId(installedInfo.uid), userId);
14986                }
14987            }
14988        }
14989
14990        private void sendSystemPackageUpdatedBroadcastsInternal() {
14991            Bundle extras = new Bundle(2);
14992            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
14993            extras.putBoolean(Intent.EXTRA_REPLACING, true);
14994            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
14995                    extras, 0, null, null, null);
14996            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
14997                    extras, 0, null, null, null);
14998            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
14999                    null, 0, removedPackage, null, null);
15000        }
15001
15002        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15003            Bundle extras = new Bundle(2);
15004            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15005            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15006            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15007            if (isUpdate || isRemovedPackageSystemUpdate) {
15008                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15009            }
15010            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15011            if (removedPackage != null) {
15012                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15013                        extras, 0, null, null, removedUsers);
15014                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15015                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15016                            removedPackage, extras, 0, null, null, removedUsers);
15017                }
15018            }
15019            if (removedAppId >= 0) {
15020                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15021                        removedUsers);
15022            }
15023        }
15024    }
15025
15026    /*
15027     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15028     * flag is not set, the data directory is removed as well.
15029     * make sure this flag is set for partially installed apps. If not its meaningless to
15030     * delete a partially installed application.
15031     */
15032    private void removePackageDataLI(PackageSetting ps, int[] allUserHandles,
15033            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15034        String packageName = ps.name;
15035        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15036        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
15037        // Retrieve object to delete permissions for shared user later on
15038        final PackageSetting deletedPs;
15039        // reader
15040        synchronized (mPackages) {
15041            deletedPs = mSettings.mPackages.get(packageName);
15042            if (outInfo != null) {
15043                outInfo.removedPackage = packageName;
15044                outInfo.removedUsers = deletedPs != null
15045                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15046                        : null;
15047            }
15048        }
15049        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15050            removeDataDirsLI(ps.volumeUuid, packageName);
15051            if (outInfo != null) {
15052                outInfo.dataRemoved = true;
15053            }
15054            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15055        }
15056        // writer
15057        synchronized (mPackages) {
15058            if (deletedPs != null) {
15059                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15060                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15061                    clearDefaultBrowserIfNeeded(packageName);
15062                    if (outInfo != null) {
15063                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15064                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15065                    }
15066                    updatePermissionsLPw(deletedPs.name, null, 0);
15067                    if (deletedPs.sharedUser != null) {
15068                        // Remove permissions associated with package. Since runtime
15069                        // permissions are per user we have to kill the removed package
15070                        // or packages running under the shared user of the removed
15071                        // package if revoking the permissions requested only by the removed
15072                        // package is successful and this causes a change in gids.
15073                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15074                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15075                                    userId);
15076                            if (userIdToKill == UserHandle.USER_ALL
15077                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15078                                // If gids changed for this user, kill all affected packages.
15079                                mHandler.post(new Runnable() {
15080                                    @Override
15081                                    public void run() {
15082                                        // This has to happen with no lock held.
15083                                        killApplication(deletedPs.name, deletedPs.appId,
15084                                                KILL_APP_REASON_GIDS_CHANGED);
15085                                    }
15086                                });
15087                                break;
15088                            }
15089                        }
15090                    }
15091                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15092                }
15093                // make sure to preserve per-user disabled state if this removal was just
15094                // a downgrade of a system app to the factory package
15095                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15096                    if (DEBUG_REMOVE) {
15097                        Slog.d(TAG, "Propagating install state across downgrade");
15098                    }
15099                    for (int userId : allUserHandles) {
15100                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15101                        if (DEBUG_REMOVE) {
15102                            Slog.d(TAG, "    user " + userId + " => " + installed);
15103                        }
15104                        ps.setInstalled(installed, userId);
15105                    }
15106                }
15107            }
15108            // can downgrade to reader
15109            if (writeSettings) {
15110                // Save settings now
15111                mSettings.writeLPr();
15112            }
15113        }
15114        if (outInfo != null) {
15115            // A user ID was deleted here. Go through all users and remove it
15116            // from KeyStore.
15117            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15118        }
15119    }
15120
15121    static boolean locationIsPrivileged(File path) {
15122        try {
15123            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15124                    .getCanonicalPath();
15125            return path.getCanonicalPath().startsWith(privilegedAppDir);
15126        } catch (IOException e) {
15127            Slog.e(TAG, "Unable to access code path " + path);
15128        }
15129        return false;
15130    }
15131
15132    /*
15133     * Tries to delete system package.
15134     */
15135    private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg,
15136            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15137            boolean writeSettings) {
15138        if (deletedPs.parentPackageName != null) {
15139            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15140            return false;
15141        }
15142
15143        final boolean applyUserRestrictions
15144                = (allUserHandles != null) && (outInfo.origUsers != null);
15145        final PackageSetting disabledPs;
15146        // Confirm if the system package has been updated
15147        // An updated system app can be deleted. This will also have to restore
15148        // the system pkg from system partition
15149        // reader
15150        synchronized (mPackages) {
15151            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15152        }
15153
15154        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15155                + " disabledPs=" + disabledPs);
15156
15157        if (disabledPs == null) {
15158            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15159            return false;
15160        } else if (DEBUG_REMOVE) {
15161            Slog.d(TAG, "Deleting system pkg from data partition");
15162        }
15163
15164        if (DEBUG_REMOVE) {
15165            if (applyUserRestrictions) {
15166                Slog.d(TAG, "Remembering install states:");
15167                for (int userId : allUserHandles) {
15168                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15169                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15170                }
15171            }
15172        }
15173
15174        // Delete the updated package
15175        outInfo.isRemovedPackageSystemUpdate = true;
15176        if (outInfo.removedChildPackages != null) {
15177            final int childCount = (deletedPs.childPackageNames != null)
15178                    ? deletedPs.childPackageNames.size() : 0;
15179            for (int i = 0; i < childCount; i++) {
15180                String childPackageName = deletedPs.childPackageNames.get(i);
15181                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15182                        .contains(childPackageName)) {
15183                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15184                            childPackageName);
15185                    if (childInfo != null) {
15186                        childInfo.isRemovedPackageSystemUpdate = true;
15187                    }
15188                }
15189            }
15190        }
15191
15192        if (disabledPs.versionCode < deletedPs.versionCode) {
15193            // Delete data for downgrades
15194            flags &= ~PackageManager.DELETE_KEEP_DATA;
15195        } else {
15196            // Preserve data by setting flag
15197            flags |= PackageManager.DELETE_KEEP_DATA;
15198        }
15199
15200        boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles,
15201                outInfo, writeSettings, disabledPs.pkg);
15202        if (!ret) {
15203            return false;
15204        }
15205
15206        // writer
15207        synchronized (mPackages) {
15208            // Reinstate the old system package
15209            enableSystemPackageLPw(disabledPs.pkg);
15210            // Remove any native libraries from the upgraded package.
15211            removeNativeBinariesLI(deletedPs);
15212        }
15213
15214        // Install the system package
15215        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15216        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
15217        if (locationIsPrivileged(disabledPs.codePath)) {
15218            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15219        }
15220
15221        final PackageParser.Package newPkg;
15222        try {
15223            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15224        } catch (PackageManagerException e) {
15225            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15226                    + e.getMessage());
15227            return false;
15228        }
15229
15230        prepareAppDataAfterInstall(newPkg);
15231
15232        // writer
15233        synchronized (mPackages) {
15234            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15235
15236            // Propagate the permissions state as we do not want to drop on the floor
15237            // runtime permissions. The update permissions method below will take
15238            // care of removing obsolete permissions and grant install permissions.
15239            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15240            updatePermissionsLPw(newPkg.packageName, newPkg,
15241                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15242
15243            if (applyUserRestrictions) {
15244                if (DEBUG_REMOVE) {
15245                    Slog.d(TAG, "Propagating install state across reinstall");
15246                }
15247                for (int userId : allUserHandles) {
15248                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15249                    if (DEBUG_REMOVE) {
15250                        Slog.d(TAG, "    user " + userId + " => " + installed);
15251                    }
15252                    ps.setInstalled(installed, userId);
15253
15254                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15255                }
15256                // Regardless of writeSettings we need to ensure that this restriction
15257                // state propagation is persisted
15258                mSettings.writeAllUsersPackageRestrictionsLPr();
15259            }
15260            // can downgrade to reader here
15261            if (writeSettings) {
15262                mSettings.writeLPr();
15263            }
15264        }
15265        return true;
15266    }
15267
15268    private boolean deleteInstalledPackageLI(PackageSetting ps,
15269            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15270            PackageRemovedInfo outInfo, boolean writeSettings,
15271            PackageParser.Package replacingPackage) {
15272        synchronized (mPackages) {
15273            if (outInfo != null) {
15274                outInfo.uid = ps.appId;
15275            }
15276
15277            if (outInfo != null && outInfo.removedChildPackages != null) {
15278                final int childCount = (ps.childPackageNames != null)
15279                        ? ps.childPackageNames.size() : 0;
15280                for (int i = 0; i < childCount; i++) {
15281                    String childPackageName = ps.childPackageNames.get(i);
15282                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15283                    if (childPs == null) {
15284                        return false;
15285                    }
15286                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15287                            childPackageName);
15288                    if (childInfo != null) {
15289                        childInfo.uid = childPs.appId;
15290                    }
15291                }
15292            }
15293        }
15294
15295        // Delete package data from internal structures and also remove data if flag is set
15296        removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings);
15297
15298        // Delete the child packages data
15299        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15300        for (int i = 0; i < childCount; i++) {
15301            PackageSetting childPs;
15302            synchronized (mPackages) {
15303                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15304            }
15305            if (childPs != null) {
15306                PackageRemovedInfo childOutInfo = (outInfo != null
15307                        && outInfo.removedChildPackages != null)
15308                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15309                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15310                        && (replacingPackage != null
15311                        && !replacingPackage.hasChildPackage(childPs.name))
15312                        ? flags & ~DELETE_KEEP_DATA : flags;
15313                removePackageDataLI(childPs, allUserHandles, childOutInfo,
15314                        deleteFlags, writeSettings);
15315            }
15316        }
15317
15318        // Delete application code and resources only for parent packages
15319        if (ps.parentPackageName == null) {
15320            if (deleteCodeAndResources && (outInfo != null)) {
15321                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15322                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15323                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15324            }
15325        }
15326
15327        return true;
15328    }
15329
15330    @Override
15331    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15332            int userId) {
15333        mContext.enforceCallingOrSelfPermission(
15334                android.Manifest.permission.DELETE_PACKAGES, null);
15335        synchronized (mPackages) {
15336            PackageSetting ps = mSettings.mPackages.get(packageName);
15337            if (ps == null) {
15338                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15339                return false;
15340            }
15341            if (!ps.getInstalled(userId)) {
15342                // Can't block uninstall for an app that is not installed or enabled.
15343                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15344                return false;
15345            }
15346            ps.setBlockUninstall(blockUninstall, userId);
15347            mSettings.writePackageRestrictionsLPr(userId);
15348        }
15349        return true;
15350    }
15351
15352    @Override
15353    public boolean getBlockUninstallForUser(String packageName, int userId) {
15354        synchronized (mPackages) {
15355            PackageSetting ps = mSettings.mPackages.get(packageName);
15356            if (ps == null) {
15357                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15358                return false;
15359            }
15360            return ps.getBlockUninstall(userId);
15361        }
15362    }
15363
15364    @Override
15365    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15366        int callingUid = Binder.getCallingUid();
15367        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15368            throw new SecurityException(
15369                    "setRequiredForSystemUser can only be run by the system or root");
15370        }
15371        synchronized (mPackages) {
15372            PackageSetting ps = mSettings.mPackages.get(packageName);
15373            if (ps == null) {
15374                Log.w(TAG, "Package doesn't exist: " + packageName);
15375                return false;
15376            }
15377            if (systemUserApp) {
15378                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15379            } else {
15380                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15381            }
15382            mSettings.writeLPr();
15383        }
15384        return true;
15385    }
15386
15387    /*
15388     * This method handles package deletion in general
15389     */
15390    private boolean deletePackageLI(String packageName, UserHandle user,
15391            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
15392            PackageRemovedInfo outInfo, boolean writeSettings,
15393            PackageParser.Package replacingPackage) {
15394        if (packageName == null) {
15395            Slog.w(TAG, "Attempt to delete null packageName.");
15396            return false;
15397        }
15398
15399        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
15400
15401        PackageSetting ps;
15402
15403        synchronized (mPackages) {
15404            ps = mSettings.mPackages.get(packageName);
15405            if (ps == null) {
15406                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15407                return false;
15408            }
15409
15410            if (ps.parentPackageName != null && (!isSystemApp(ps)
15411                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
15412                if (DEBUG_REMOVE) {
15413                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
15414                            + ((user == null) ? UserHandle.USER_ALL : user));
15415                }
15416                final int removedUserId = (user != null) ? user.getIdentifier()
15417                        : UserHandle.USER_ALL;
15418                if (!clearPackageStateForUser(ps, removedUserId, outInfo)) {
15419                    return false;
15420                }
15421                markPackageUninstalledForUserLPw(ps, user);
15422                scheduleWritePackageRestrictionsLocked(user);
15423                return true;
15424            }
15425        }
15426
15427        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
15428                && user.getIdentifier() != UserHandle.USER_ALL)) {
15429            // The caller is asking that the package only be deleted for a single
15430            // user.  To do this, we just mark its uninstalled state and delete
15431            // its data. If this is a system app, we only allow this to happen if
15432            // they have set the special DELETE_SYSTEM_APP which requests different
15433            // semantics than normal for uninstalling system apps.
15434            markPackageUninstalledForUserLPw(ps, user);
15435
15436            if (!isSystemApp(ps)) {
15437                // Do not uninstall the APK if an app should be cached
15438                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
15439                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
15440                    // Other user still have this package installed, so all
15441                    // we need to do is clear this user's data and save that
15442                    // it is uninstalled.
15443                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
15444                    if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
15445                        return false;
15446                    }
15447                    scheduleWritePackageRestrictionsLocked(user);
15448                    return true;
15449                } else {
15450                    // We need to set it back to 'installed' so the uninstall
15451                    // broadcasts will be sent correctly.
15452                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
15453                    ps.setInstalled(true, user.getIdentifier());
15454                }
15455            } else {
15456                // This is a system app, so we assume that the
15457                // other users still have this package installed, so all
15458                // we need to do is clear this user's data and save that
15459                // it is uninstalled.
15460                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
15461                if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
15462                    return false;
15463                }
15464                scheduleWritePackageRestrictionsLocked(user);
15465                return true;
15466            }
15467        }
15468
15469        // If we are deleting a composite package for all users, keep track
15470        // of result for each child.
15471        if (ps.childPackageNames != null && outInfo != null) {
15472            synchronized (mPackages) {
15473                final int childCount = ps.childPackageNames.size();
15474                outInfo.removedChildPackages = new ArrayMap<>(childCount);
15475                for (int i = 0; i < childCount; i++) {
15476                    String childPackageName = ps.childPackageNames.get(i);
15477                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
15478                    childInfo.removedPackage = childPackageName;
15479                    outInfo.removedChildPackages.put(childPackageName, childInfo);
15480                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15481                    if (childPs != null) {
15482                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
15483                    }
15484                }
15485            }
15486        }
15487
15488        boolean ret = false;
15489        if (isSystemApp(ps)) {
15490            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
15491            // When an updated system application is deleted we delete the existing resources
15492            // as well and fall back to existing code in system partition
15493            ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
15494        } else {
15495            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
15496            // Kill application pre-emptively especially for apps on sd.
15497            final boolean killApp = (flags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15498            if (killApp) {
15499                killApplication(packageName, ps.appId, "uninstall pkg");
15500            }
15501            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles,
15502                    outInfo, writeSettings, replacingPackage);
15503        }
15504
15505        // Take a note whether we deleted the package for all users
15506        if (outInfo != null) {
15507            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15508            if (outInfo.removedChildPackages != null) {
15509                synchronized (mPackages) {
15510                    final int childCount = outInfo.removedChildPackages.size();
15511                    for (int i = 0; i < childCount; i++) {
15512                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
15513                        if (childInfo != null) {
15514                            childInfo.removedForAllUsers = mPackages.get(
15515                                    childInfo.removedPackage) == null;
15516                        }
15517                    }
15518                }
15519            }
15520            // If we uninstalled an update to a system app there may be some
15521            // child packages that appeared as they are declared in the system
15522            // app but were not declared in the update.
15523            if (isSystemApp(ps)) {
15524                synchronized (mPackages) {
15525                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
15526                    final int childCount = (updatedPs.childPackageNames != null)
15527                            ? updatedPs.childPackageNames.size() : 0;
15528                    for (int i = 0; i < childCount; i++) {
15529                        String childPackageName = updatedPs.childPackageNames.get(i);
15530                        if (outInfo.removedChildPackages == null
15531                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
15532                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15533                            if (childPs == null) {
15534                                continue;
15535                            }
15536                            PackageInstalledInfo installRes = new PackageInstalledInfo();
15537                            installRes.name = childPackageName;
15538                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
15539                            installRes.pkg = mPackages.get(childPackageName);
15540                            installRes.uid = childPs.pkg.applicationInfo.uid;
15541                            if (outInfo.appearedChildPackages == null) {
15542                                outInfo.appearedChildPackages = new ArrayMap<>();
15543                            }
15544                            outInfo.appearedChildPackages.put(childPackageName, installRes);
15545                        }
15546                    }
15547                }
15548            }
15549        }
15550
15551        return ret;
15552    }
15553
15554    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
15555        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
15556                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
15557        for (int nextUserId : userIds) {
15558            if (DEBUG_REMOVE) {
15559                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
15560            }
15561            ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT,
15562                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
15563                    false /*hidden*/, false /*suspended*/, null, null, null,
15564                    false /*blockUninstall*/,
15565                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
15566        }
15567    }
15568
15569    private boolean clearPackageStateForUser(PackageSetting ps, int userId,
15570            PackageRemovedInfo outInfo) {
15571        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
15572                : new int[] {userId};
15573        for (int nextUserId : userIds) {
15574            if (DEBUG_REMOVE) {
15575                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
15576                        + nextUserId);
15577            }
15578            final int flags =  StorageManager.FLAG_STORAGE_CE|  StorageManager.FLAG_STORAGE_DE;
15579            try {
15580                mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags);
15581            } catch (InstallerException e) {
15582                Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e);
15583                return false;
15584            }
15585            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
15586            schedulePackageCleaning(ps.name, nextUserId, false);
15587            synchronized (mPackages) {
15588                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
15589                    scheduleWritePackageRestrictionsLocked(nextUserId);
15590                }
15591                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
15592            }
15593        }
15594
15595        if (outInfo != null) {
15596            outInfo.removedPackage = ps.name;
15597            outInfo.removedAppId = ps.appId;
15598            outInfo.removedUsers = userIds;
15599        }
15600
15601        return true;
15602    }
15603
15604    private final class ClearStorageConnection implements ServiceConnection {
15605        IMediaContainerService mContainerService;
15606
15607        @Override
15608        public void onServiceConnected(ComponentName name, IBinder service) {
15609            synchronized (this) {
15610                mContainerService = IMediaContainerService.Stub.asInterface(service);
15611                notifyAll();
15612            }
15613        }
15614
15615        @Override
15616        public void onServiceDisconnected(ComponentName name) {
15617        }
15618    }
15619
15620    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
15621        final boolean mounted;
15622        if (Environment.isExternalStorageEmulated()) {
15623            mounted = true;
15624        } else {
15625            final String status = Environment.getExternalStorageState();
15626
15627            mounted = status.equals(Environment.MEDIA_MOUNTED)
15628                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
15629        }
15630
15631        if (!mounted) {
15632            return;
15633        }
15634
15635        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
15636        int[] users;
15637        if (userId == UserHandle.USER_ALL) {
15638            users = sUserManager.getUserIds();
15639        } else {
15640            users = new int[] { userId };
15641        }
15642        final ClearStorageConnection conn = new ClearStorageConnection();
15643        if (mContext.bindServiceAsUser(
15644                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
15645            try {
15646                for (int curUser : users) {
15647                    long timeout = SystemClock.uptimeMillis() + 5000;
15648                    synchronized (conn) {
15649                        long now = SystemClock.uptimeMillis();
15650                        while (conn.mContainerService == null && now < timeout) {
15651                            try {
15652                                conn.wait(timeout - now);
15653                            } catch (InterruptedException e) {
15654                            }
15655                        }
15656                    }
15657                    if (conn.mContainerService == null) {
15658                        return;
15659                    }
15660
15661                    final UserEnvironment userEnv = new UserEnvironment(curUser);
15662                    clearDirectory(conn.mContainerService,
15663                            userEnv.buildExternalStorageAppCacheDirs(packageName));
15664                    if (allData) {
15665                        clearDirectory(conn.mContainerService,
15666                                userEnv.buildExternalStorageAppDataDirs(packageName));
15667                        clearDirectory(conn.mContainerService,
15668                                userEnv.buildExternalStorageAppMediaDirs(packageName));
15669                    }
15670                }
15671            } finally {
15672                mContext.unbindService(conn);
15673            }
15674        }
15675    }
15676
15677    @Override
15678    public void clearApplicationProfileData(String packageName) {
15679        enforceSystemOrRoot("Only the system can clear all profile data");
15680        try {
15681            mInstaller.clearAppProfiles(packageName);
15682        } catch (InstallerException ex) {
15683            Log.e(TAG, "Could not clear profile data of package " + packageName);
15684        }
15685    }
15686
15687    @Override
15688    public void clearApplicationUserData(final String packageName,
15689            final IPackageDataObserver observer, final int userId) {
15690        mContext.enforceCallingOrSelfPermission(
15691                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
15692
15693        enforceCrossUserPermission(Binder.getCallingUid(), userId,
15694                true /* requireFullPermission */, false /* checkShell */, "clear application data");
15695
15696        final DevicePolicyManagerInternal dpmi = LocalServices
15697                .getService(DevicePolicyManagerInternal.class);
15698        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
15699            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
15700        }
15701        // Queue up an async operation since the package deletion may take a little while.
15702        mHandler.post(new Runnable() {
15703            public void run() {
15704                mHandler.removeCallbacks(this);
15705                final boolean succeeded;
15706                synchronized (mInstallLock) {
15707                    succeeded = clearApplicationUserDataLI(packageName, userId);
15708                }
15709                clearExternalStorageDataSync(packageName, userId, true);
15710                if (succeeded) {
15711                    // invoke DeviceStorageMonitor's update method to clear any notifications
15712                    DeviceStorageMonitorInternal dsm = LocalServices
15713                            .getService(DeviceStorageMonitorInternal.class);
15714                    if (dsm != null) {
15715                        dsm.checkMemory();
15716                    }
15717                }
15718                if(observer != null) {
15719                    try {
15720                        observer.onRemoveCompleted(packageName, succeeded);
15721                    } catch (RemoteException e) {
15722                        Log.i(TAG, "Observer no longer exists.");
15723                    }
15724                } //end if observer
15725            } //end run
15726        });
15727    }
15728
15729    private boolean clearApplicationUserDataLI(String packageName, int userId) {
15730        if (packageName == null) {
15731            Slog.w(TAG, "Attempt to delete null packageName.");
15732            return false;
15733        }
15734
15735        // Try finding details about the requested package
15736        PackageParser.Package pkg;
15737        synchronized (mPackages) {
15738            pkg = mPackages.get(packageName);
15739            if (pkg == null) {
15740                final PackageSetting ps = mSettings.mPackages.get(packageName);
15741                if (ps != null) {
15742                    pkg = ps.pkg;
15743                }
15744            }
15745
15746            if (pkg == null) {
15747                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15748                return false;
15749            }
15750
15751            PackageSetting ps = (PackageSetting) pkg.mExtras;
15752            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15753        }
15754
15755        // Always delete data directories for package, even if we found no other
15756        // record of app. This helps users recover from UID mismatches without
15757        // resorting to a full data wipe.
15758        // TODO: triage flags as part of 26466827
15759        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15760        try {
15761            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
15762        } catch (InstallerException e) {
15763            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
15764            return false;
15765        }
15766
15767        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15768        removeKeystoreDataIfNeeded(userId, appId);
15769
15770        // Create a native library symlink only if we have native libraries
15771        // and if the native libraries are 32 bit libraries. We do not provide
15772        // this symlink for 64 bit libraries.
15773        if (pkg.applicationInfo.primaryCpuAbi != null &&
15774                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
15775            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
15776            try {
15777                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
15778                        nativeLibPath, userId);
15779            } catch (InstallerException e) {
15780                Slog.w(TAG, "Failed linking native library dir", e);
15781                return false;
15782            }
15783        }
15784
15785        return true;
15786    }
15787
15788    /**
15789     * Reverts user permission state changes (permissions and flags) in
15790     * all packages for a given user.
15791     *
15792     * @param userId The device user for which to do a reset.
15793     */
15794    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
15795        final int packageCount = mPackages.size();
15796        for (int i = 0; i < packageCount; i++) {
15797            PackageParser.Package pkg = mPackages.valueAt(i);
15798            PackageSetting ps = (PackageSetting) pkg.mExtras;
15799            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15800        }
15801    }
15802
15803    /**
15804     * Reverts user permission state changes (permissions and flags).
15805     *
15806     * @param ps The package for which to reset.
15807     * @param userId The device user for which to do a reset.
15808     */
15809    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
15810            final PackageSetting ps, final int userId) {
15811        if (ps.pkg == null) {
15812            return;
15813        }
15814
15815        // These are flags that can change base on user actions.
15816        final int userSettableMask = FLAG_PERMISSION_USER_SET
15817                | FLAG_PERMISSION_USER_FIXED
15818                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
15819                | FLAG_PERMISSION_REVIEW_REQUIRED;
15820
15821        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
15822                | FLAG_PERMISSION_POLICY_FIXED;
15823
15824        boolean writeInstallPermissions = false;
15825        boolean writeRuntimePermissions = false;
15826
15827        final int permissionCount = ps.pkg.requestedPermissions.size();
15828        for (int i = 0; i < permissionCount; i++) {
15829            String permission = ps.pkg.requestedPermissions.get(i);
15830
15831            BasePermission bp = mSettings.mPermissions.get(permission);
15832            if (bp == null) {
15833                continue;
15834            }
15835
15836            // If shared user we just reset the state to which only this app contributed.
15837            if (ps.sharedUser != null) {
15838                boolean used = false;
15839                final int packageCount = ps.sharedUser.packages.size();
15840                for (int j = 0; j < packageCount; j++) {
15841                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
15842                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
15843                            && pkg.pkg.requestedPermissions.contains(permission)) {
15844                        used = true;
15845                        break;
15846                    }
15847                }
15848                if (used) {
15849                    continue;
15850                }
15851            }
15852
15853            PermissionsState permissionsState = ps.getPermissionsState();
15854
15855            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
15856
15857            // Always clear the user settable flags.
15858            final boolean hasInstallState = permissionsState.getInstallPermissionState(
15859                    bp.name) != null;
15860            // If permission review is enabled and this is a legacy app, mark the
15861            // permission as requiring a review as this is the initial state.
15862            int flags = 0;
15863            if (Build.PERMISSIONS_REVIEW_REQUIRED
15864                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
15865                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
15866            }
15867            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
15868                if (hasInstallState) {
15869                    writeInstallPermissions = true;
15870                } else {
15871                    writeRuntimePermissions = true;
15872                }
15873            }
15874
15875            // Below is only runtime permission handling.
15876            if (!bp.isRuntime()) {
15877                continue;
15878            }
15879
15880            // Never clobber system or policy.
15881            if ((oldFlags & policyOrSystemFlags) != 0) {
15882                continue;
15883            }
15884
15885            // If this permission was granted by default, make sure it is.
15886            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
15887                if (permissionsState.grantRuntimePermission(bp, userId)
15888                        != PERMISSION_OPERATION_FAILURE) {
15889                    writeRuntimePermissions = true;
15890                }
15891            // If permission review is enabled the permissions for a legacy apps
15892            // are represented as constantly granted runtime ones, so don't revoke.
15893            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
15894                // Otherwise, reset the permission.
15895                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
15896                switch (revokeResult) {
15897                    case PERMISSION_OPERATION_SUCCESS:
15898                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
15899                        writeRuntimePermissions = true;
15900                        final int appId = ps.appId;
15901                        mHandler.post(new Runnable() {
15902                            @Override
15903                            public void run() {
15904                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
15905                            }
15906                        });
15907                    } break;
15908                }
15909            }
15910        }
15911
15912        // Synchronously write as we are taking permissions away.
15913        if (writeRuntimePermissions) {
15914            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
15915        }
15916
15917        // Synchronously write as we are taking permissions away.
15918        if (writeInstallPermissions) {
15919            mSettings.writeLPr();
15920        }
15921    }
15922
15923    /**
15924     * Remove entries from the keystore daemon. Will only remove it if the
15925     * {@code appId} is valid.
15926     */
15927    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
15928        if (appId < 0) {
15929            return;
15930        }
15931
15932        final KeyStore keyStore = KeyStore.getInstance();
15933        if (keyStore != null) {
15934            if (userId == UserHandle.USER_ALL) {
15935                for (final int individual : sUserManager.getUserIds()) {
15936                    keyStore.clearUid(UserHandle.getUid(individual, appId));
15937                }
15938            } else {
15939                keyStore.clearUid(UserHandle.getUid(userId, appId));
15940            }
15941        } else {
15942            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
15943        }
15944    }
15945
15946    @Override
15947    public void deleteApplicationCacheFiles(final String packageName,
15948            final IPackageDataObserver observer) {
15949        mContext.enforceCallingOrSelfPermission(
15950                android.Manifest.permission.DELETE_CACHE_FILES, null);
15951        // Queue up an async operation since the package deletion may take a little while.
15952        final int userId = UserHandle.getCallingUserId();
15953        mHandler.post(new Runnable() {
15954            public void run() {
15955                mHandler.removeCallbacks(this);
15956                final boolean succeded;
15957                synchronized (mInstallLock) {
15958                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
15959                }
15960                clearExternalStorageDataSync(packageName, userId, false);
15961                if (observer != null) {
15962                    try {
15963                        observer.onRemoveCompleted(packageName, succeded);
15964                    } catch (RemoteException e) {
15965                        Log.i(TAG, "Observer no longer exists.");
15966                    }
15967                } //end if observer
15968            } //end run
15969        });
15970    }
15971
15972    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
15973        if (packageName == null) {
15974            Slog.w(TAG, "Attempt to delete null packageName.");
15975            return false;
15976        }
15977        PackageParser.Package p;
15978        synchronized (mPackages) {
15979            p = mPackages.get(packageName);
15980        }
15981        if (p == null) {
15982            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15983            return false;
15984        }
15985        final ApplicationInfo applicationInfo = p.applicationInfo;
15986        if (applicationInfo == null) {
15987            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15988            return false;
15989        }
15990        // TODO: triage flags as part of 26466827
15991        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15992        try {
15993            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
15994                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
15995        } catch (InstallerException e) {
15996            Slog.w(TAG, "Couldn't remove cache files for package "
15997                    + packageName + " u" + userId, e);
15998            return false;
15999        }
16000        return true;
16001    }
16002
16003    @Override
16004    public void getPackageSizeInfo(final String packageName, int userHandle,
16005            final IPackageStatsObserver observer) {
16006        mContext.enforceCallingOrSelfPermission(
16007                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16008        if (packageName == null) {
16009            throw new IllegalArgumentException("Attempt to get size of null packageName");
16010        }
16011
16012        PackageStats stats = new PackageStats(packageName, userHandle);
16013
16014        /*
16015         * Queue up an async operation since the package measurement may take a
16016         * little while.
16017         */
16018        Message msg = mHandler.obtainMessage(INIT_COPY);
16019        msg.obj = new MeasureParams(stats, observer);
16020        mHandler.sendMessage(msg);
16021    }
16022
16023    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
16024            PackageStats pStats) {
16025        if (packageName == null) {
16026            Slog.w(TAG, "Attempt to get size of null packageName.");
16027            return false;
16028        }
16029        PackageParser.Package p;
16030        boolean dataOnly = false;
16031        String libDirRoot = null;
16032        String asecPath = null;
16033        PackageSetting ps = null;
16034        synchronized (mPackages) {
16035            p = mPackages.get(packageName);
16036            ps = mSettings.mPackages.get(packageName);
16037            if(p == null) {
16038                dataOnly = true;
16039                if((ps == null) || (ps.pkg == null)) {
16040                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
16041                    return false;
16042                }
16043                p = ps.pkg;
16044            }
16045            if (ps != null) {
16046                libDirRoot = ps.legacyNativeLibraryPathString;
16047            }
16048            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
16049                final long token = Binder.clearCallingIdentity();
16050                try {
16051                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
16052                    if (secureContainerId != null) {
16053                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
16054                    }
16055                } finally {
16056                    Binder.restoreCallingIdentity(token);
16057                }
16058            }
16059        }
16060        String publicSrcDir = null;
16061        if(!dataOnly) {
16062            final ApplicationInfo applicationInfo = p.applicationInfo;
16063            if (applicationInfo == null) {
16064                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
16065                return false;
16066            }
16067            if (p.isForwardLocked()) {
16068                publicSrcDir = applicationInfo.getBaseResourcePath();
16069            }
16070        }
16071        // TODO: extend to measure size of split APKs
16072        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
16073        // not just the first level.
16074        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
16075        // just the primary.
16076        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
16077
16078        String apkPath;
16079        File packageDir = new File(p.codePath);
16080
16081        if (packageDir.isDirectory() && p.canHaveOatDir()) {
16082            apkPath = packageDir.getAbsolutePath();
16083            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
16084            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
16085                libDirRoot = null;
16086            }
16087        } else {
16088            apkPath = p.baseCodePath;
16089        }
16090
16091        // TODO: triage flags as part of 26466827
16092        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
16093        try {
16094            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
16095                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
16096        } catch (InstallerException e) {
16097            return false;
16098        }
16099
16100        // Fix-up for forward-locked applications in ASEC containers.
16101        if (!isExternal(p)) {
16102            pStats.codeSize += pStats.externalCodeSize;
16103            pStats.externalCodeSize = 0L;
16104        }
16105
16106        return true;
16107    }
16108
16109    private int getUidTargetSdkVersionLockedLPr(int uid) {
16110        Object obj = mSettings.getUserIdLPr(uid);
16111        if (obj instanceof SharedUserSetting) {
16112            final SharedUserSetting sus = (SharedUserSetting) obj;
16113            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16114            final Iterator<PackageSetting> it = sus.packages.iterator();
16115            while (it.hasNext()) {
16116                final PackageSetting ps = it.next();
16117                if (ps.pkg != null) {
16118                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16119                    if (v < vers) vers = v;
16120                }
16121            }
16122            return vers;
16123        } else if (obj instanceof PackageSetting) {
16124            final PackageSetting ps = (PackageSetting) obj;
16125            if (ps.pkg != null) {
16126                return ps.pkg.applicationInfo.targetSdkVersion;
16127            }
16128        }
16129        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16130    }
16131
16132    @Override
16133    public void addPreferredActivity(IntentFilter filter, int match,
16134            ComponentName[] set, ComponentName activity, int userId) {
16135        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16136                "Adding preferred");
16137    }
16138
16139    private void addPreferredActivityInternal(IntentFilter filter, int match,
16140            ComponentName[] set, ComponentName activity, boolean always, int userId,
16141            String opname) {
16142        // writer
16143        int callingUid = Binder.getCallingUid();
16144        enforceCrossUserPermission(callingUid, userId,
16145                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16146        if (filter.countActions() == 0) {
16147            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16148            return;
16149        }
16150        synchronized (mPackages) {
16151            if (mContext.checkCallingOrSelfPermission(
16152                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16153                    != PackageManager.PERMISSION_GRANTED) {
16154                if (getUidTargetSdkVersionLockedLPr(callingUid)
16155                        < Build.VERSION_CODES.FROYO) {
16156                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16157                            + callingUid);
16158                    return;
16159                }
16160                mContext.enforceCallingOrSelfPermission(
16161                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16162            }
16163
16164            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16165            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16166                    + userId + ":");
16167            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16168            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16169            scheduleWritePackageRestrictionsLocked(userId);
16170        }
16171    }
16172
16173    @Override
16174    public void replacePreferredActivity(IntentFilter filter, int match,
16175            ComponentName[] set, ComponentName activity, int userId) {
16176        if (filter.countActions() != 1) {
16177            throw new IllegalArgumentException(
16178                    "replacePreferredActivity expects filter to have only 1 action.");
16179        }
16180        if (filter.countDataAuthorities() != 0
16181                || filter.countDataPaths() != 0
16182                || filter.countDataSchemes() > 1
16183                || filter.countDataTypes() != 0) {
16184            throw new IllegalArgumentException(
16185                    "replacePreferredActivity expects filter to have no data authorities, " +
16186                    "paths, or types; and at most one scheme.");
16187        }
16188
16189        final int callingUid = Binder.getCallingUid();
16190        enforceCrossUserPermission(callingUid, userId,
16191                true /* requireFullPermission */, false /* checkShell */,
16192                "replace preferred activity");
16193        synchronized (mPackages) {
16194            if (mContext.checkCallingOrSelfPermission(
16195                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16196                    != PackageManager.PERMISSION_GRANTED) {
16197                if (getUidTargetSdkVersionLockedLPr(callingUid)
16198                        < Build.VERSION_CODES.FROYO) {
16199                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16200                            + Binder.getCallingUid());
16201                    return;
16202                }
16203                mContext.enforceCallingOrSelfPermission(
16204                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16205            }
16206
16207            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16208            if (pir != null) {
16209                // Get all of the existing entries that exactly match this filter.
16210                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16211                if (existing != null && existing.size() == 1) {
16212                    PreferredActivity cur = existing.get(0);
16213                    if (DEBUG_PREFERRED) {
16214                        Slog.i(TAG, "Checking replace of preferred:");
16215                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16216                        if (!cur.mPref.mAlways) {
16217                            Slog.i(TAG, "  -- CUR; not mAlways!");
16218                        } else {
16219                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16220                            Slog.i(TAG, "  -- CUR: mSet="
16221                                    + Arrays.toString(cur.mPref.mSetComponents));
16222                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16223                            Slog.i(TAG, "  -- NEW: mMatch="
16224                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16225                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16226                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16227                        }
16228                    }
16229                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16230                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16231                            && cur.mPref.sameSet(set)) {
16232                        // Setting the preferred activity to what it happens to be already
16233                        if (DEBUG_PREFERRED) {
16234                            Slog.i(TAG, "Replacing with same preferred activity "
16235                                    + cur.mPref.mShortComponent + " for user "
16236                                    + userId + ":");
16237                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16238                        }
16239                        return;
16240                    }
16241                }
16242
16243                if (existing != null) {
16244                    if (DEBUG_PREFERRED) {
16245                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16246                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16247                    }
16248                    for (int i = 0; i < existing.size(); i++) {
16249                        PreferredActivity pa = existing.get(i);
16250                        if (DEBUG_PREFERRED) {
16251                            Slog.i(TAG, "Removing existing preferred activity "
16252                                    + pa.mPref.mComponent + ":");
16253                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16254                        }
16255                        pir.removeFilter(pa);
16256                    }
16257                }
16258            }
16259            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16260                    "Replacing preferred");
16261        }
16262    }
16263
16264    @Override
16265    public void clearPackagePreferredActivities(String packageName) {
16266        final int uid = Binder.getCallingUid();
16267        // writer
16268        synchronized (mPackages) {
16269            PackageParser.Package pkg = mPackages.get(packageName);
16270            if (pkg == null || pkg.applicationInfo.uid != uid) {
16271                if (mContext.checkCallingOrSelfPermission(
16272                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16273                        != PackageManager.PERMISSION_GRANTED) {
16274                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16275                            < Build.VERSION_CODES.FROYO) {
16276                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16277                                + Binder.getCallingUid());
16278                        return;
16279                    }
16280                    mContext.enforceCallingOrSelfPermission(
16281                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16282                }
16283            }
16284
16285            int user = UserHandle.getCallingUserId();
16286            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16287                scheduleWritePackageRestrictionsLocked(user);
16288            }
16289        }
16290    }
16291
16292    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16293    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16294        ArrayList<PreferredActivity> removed = null;
16295        boolean changed = false;
16296        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16297            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16298            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16299            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16300                continue;
16301            }
16302            Iterator<PreferredActivity> it = pir.filterIterator();
16303            while (it.hasNext()) {
16304                PreferredActivity pa = it.next();
16305                // Mark entry for removal only if it matches the package name
16306                // and the entry is of type "always".
16307                if (packageName == null ||
16308                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16309                                && pa.mPref.mAlways)) {
16310                    if (removed == null) {
16311                        removed = new ArrayList<PreferredActivity>();
16312                    }
16313                    removed.add(pa);
16314                }
16315            }
16316            if (removed != null) {
16317                for (int j=0; j<removed.size(); j++) {
16318                    PreferredActivity pa = removed.get(j);
16319                    pir.removeFilter(pa);
16320                }
16321                changed = true;
16322            }
16323        }
16324        return changed;
16325    }
16326
16327    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16328    private void clearIntentFilterVerificationsLPw(int userId) {
16329        final int packageCount = mPackages.size();
16330        for (int i = 0; i < packageCount; i++) {
16331            PackageParser.Package pkg = mPackages.valueAt(i);
16332            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16333        }
16334    }
16335
16336    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16337    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16338        if (userId == UserHandle.USER_ALL) {
16339            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16340                    sUserManager.getUserIds())) {
16341                for (int oneUserId : sUserManager.getUserIds()) {
16342                    scheduleWritePackageRestrictionsLocked(oneUserId);
16343                }
16344            }
16345        } else {
16346            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16347                scheduleWritePackageRestrictionsLocked(userId);
16348            }
16349        }
16350    }
16351
16352    void clearDefaultBrowserIfNeeded(String packageName) {
16353        for (int oneUserId : sUserManager.getUserIds()) {
16354            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16355            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16356            if (packageName.equals(defaultBrowserPackageName)) {
16357                setDefaultBrowserPackageName(null, oneUserId);
16358            }
16359        }
16360    }
16361
16362    @Override
16363    public void resetApplicationPreferences(int userId) {
16364        mContext.enforceCallingOrSelfPermission(
16365                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16366        // writer
16367        synchronized (mPackages) {
16368            final long identity = Binder.clearCallingIdentity();
16369            try {
16370                clearPackagePreferredActivitiesLPw(null, userId);
16371                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16372                // TODO: We have to reset the default SMS and Phone. This requires
16373                // significant refactoring to keep all default apps in the package
16374                // manager (cleaner but more work) or have the services provide
16375                // callbacks to the package manager to request a default app reset.
16376                applyFactoryDefaultBrowserLPw(userId);
16377                clearIntentFilterVerificationsLPw(userId);
16378                primeDomainVerificationsLPw(userId);
16379                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16380                scheduleWritePackageRestrictionsLocked(userId);
16381            } finally {
16382                Binder.restoreCallingIdentity(identity);
16383            }
16384        }
16385    }
16386
16387    @Override
16388    public int getPreferredActivities(List<IntentFilter> outFilters,
16389            List<ComponentName> outActivities, String packageName) {
16390
16391        int num = 0;
16392        final int userId = UserHandle.getCallingUserId();
16393        // reader
16394        synchronized (mPackages) {
16395            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16396            if (pir != null) {
16397                final Iterator<PreferredActivity> it = pir.filterIterator();
16398                while (it.hasNext()) {
16399                    final PreferredActivity pa = it.next();
16400                    if (packageName == null
16401                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16402                                    && pa.mPref.mAlways)) {
16403                        if (outFilters != null) {
16404                            outFilters.add(new IntentFilter(pa));
16405                        }
16406                        if (outActivities != null) {
16407                            outActivities.add(pa.mPref.mComponent);
16408                        }
16409                    }
16410                }
16411            }
16412        }
16413
16414        return num;
16415    }
16416
16417    @Override
16418    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16419            int userId) {
16420        int callingUid = Binder.getCallingUid();
16421        if (callingUid != Process.SYSTEM_UID) {
16422            throw new SecurityException(
16423                    "addPersistentPreferredActivity can only be run by the system");
16424        }
16425        if (filter.countActions() == 0) {
16426            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16427            return;
16428        }
16429        synchronized (mPackages) {
16430            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16431                    ":");
16432            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16433            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16434                    new PersistentPreferredActivity(filter, activity));
16435            scheduleWritePackageRestrictionsLocked(userId);
16436        }
16437    }
16438
16439    @Override
16440    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16441        int callingUid = Binder.getCallingUid();
16442        if (callingUid != Process.SYSTEM_UID) {
16443            throw new SecurityException(
16444                    "clearPackagePersistentPreferredActivities can only be run by the system");
16445        }
16446        ArrayList<PersistentPreferredActivity> removed = null;
16447        boolean changed = false;
16448        synchronized (mPackages) {
16449            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
16450                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
16451                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
16452                        .valueAt(i);
16453                if (userId != thisUserId) {
16454                    continue;
16455                }
16456                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
16457                while (it.hasNext()) {
16458                    PersistentPreferredActivity ppa = it.next();
16459                    // Mark entry for removal only if it matches the package name.
16460                    if (ppa.mComponent.getPackageName().equals(packageName)) {
16461                        if (removed == null) {
16462                            removed = new ArrayList<PersistentPreferredActivity>();
16463                        }
16464                        removed.add(ppa);
16465                    }
16466                }
16467                if (removed != null) {
16468                    for (int j=0; j<removed.size(); j++) {
16469                        PersistentPreferredActivity ppa = removed.get(j);
16470                        ppir.removeFilter(ppa);
16471                    }
16472                    changed = true;
16473                }
16474            }
16475
16476            if (changed) {
16477                scheduleWritePackageRestrictionsLocked(userId);
16478            }
16479        }
16480    }
16481
16482    /**
16483     * Common machinery for picking apart a restored XML blob and passing
16484     * it to a caller-supplied functor to be applied to the running system.
16485     */
16486    private void restoreFromXml(XmlPullParser parser, int userId,
16487            String expectedStartTag, BlobXmlRestorer functor)
16488            throws IOException, XmlPullParserException {
16489        int type;
16490        while ((type = parser.next()) != XmlPullParser.START_TAG
16491                && type != XmlPullParser.END_DOCUMENT) {
16492        }
16493        if (type != XmlPullParser.START_TAG) {
16494            // oops didn't find a start tag?!
16495            if (DEBUG_BACKUP) {
16496                Slog.e(TAG, "Didn't find start tag during restore");
16497            }
16498            return;
16499        }
16500Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
16501        // this is supposed to be TAG_PREFERRED_BACKUP
16502        if (!expectedStartTag.equals(parser.getName())) {
16503            if (DEBUG_BACKUP) {
16504                Slog.e(TAG, "Found unexpected tag " + parser.getName());
16505            }
16506            return;
16507        }
16508
16509        // skip interfering stuff, then we're aligned with the backing implementation
16510        while ((type = parser.next()) == XmlPullParser.TEXT) { }
16511Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
16512        functor.apply(parser, userId);
16513    }
16514
16515    private interface BlobXmlRestorer {
16516        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
16517    }
16518
16519    /**
16520     * Non-Binder method, support for the backup/restore mechanism: write the
16521     * full set of preferred activities in its canonical XML format.  Returns the
16522     * XML output as a byte array, or null if there is none.
16523     */
16524    @Override
16525    public byte[] getPreferredActivityBackup(int userId) {
16526        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16527            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
16528        }
16529
16530        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16531        try {
16532            final XmlSerializer serializer = new FastXmlSerializer();
16533            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16534            serializer.startDocument(null, true);
16535            serializer.startTag(null, TAG_PREFERRED_BACKUP);
16536
16537            synchronized (mPackages) {
16538                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
16539            }
16540
16541            serializer.endTag(null, TAG_PREFERRED_BACKUP);
16542            serializer.endDocument();
16543            serializer.flush();
16544        } catch (Exception e) {
16545            if (DEBUG_BACKUP) {
16546                Slog.e(TAG, "Unable to write preferred activities for backup", e);
16547            }
16548            return null;
16549        }
16550
16551        return dataStream.toByteArray();
16552    }
16553
16554    @Override
16555    public void restorePreferredActivities(byte[] backup, int userId) {
16556        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16557            throw new SecurityException("Only the system may call restorePreferredActivities()");
16558        }
16559
16560        try {
16561            final XmlPullParser parser = Xml.newPullParser();
16562            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16563            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
16564                    new BlobXmlRestorer() {
16565                        @Override
16566                        public void apply(XmlPullParser parser, int userId)
16567                                throws XmlPullParserException, IOException {
16568                            synchronized (mPackages) {
16569                                mSettings.readPreferredActivitiesLPw(parser, userId);
16570                            }
16571                        }
16572                    } );
16573        } catch (Exception e) {
16574            if (DEBUG_BACKUP) {
16575                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16576            }
16577        }
16578    }
16579
16580    /**
16581     * Non-Binder method, support for the backup/restore mechanism: write the
16582     * default browser (etc) settings in its canonical XML format.  Returns the default
16583     * browser XML representation as a byte array, or null if there is none.
16584     */
16585    @Override
16586    public byte[] getDefaultAppsBackup(int userId) {
16587        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16588            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
16589        }
16590
16591        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16592        try {
16593            final XmlSerializer serializer = new FastXmlSerializer();
16594            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16595            serializer.startDocument(null, true);
16596            serializer.startTag(null, TAG_DEFAULT_APPS);
16597
16598            synchronized (mPackages) {
16599                mSettings.writeDefaultAppsLPr(serializer, userId);
16600            }
16601
16602            serializer.endTag(null, TAG_DEFAULT_APPS);
16603            serializer.endDocument();
16604            serializer.flush();
16605        } catch (Exception e) {
16606            if (DEBUG_BACKUP) {
16607                Slog.e(TAG, "Unable to write default apps for backup", e);
16608            }
16609            return null;
16610        }
16611
16612        return dataStream.toByteArray();
16613    }
16614
16615    @Override
16616    public void restoreDefaultApps(byte[] backup, int userId) {
16617        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16618            throw new SecurityException("Only the system may call restoreDefaultApps()");
16619        }
16620
16621        try {
16622            final XmlPullParser parser = Xml.newPullParser();
16623            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16624            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
16625                    new BlobXmlRestorer() {
16626                        @Override
16627                        public void apply(XmlPullParser parser, int userId)
16628                                throws XmlPullParserException, IOException {
16629                            synchronized (mPackages) {
16630                                mSettings.readDefaultAppsLPw(parser, userId);
16631                            }
16632                        }
16633                    } );
16634        } catch (Exception e) {
16635            if (DEBUG_BACKUP) {
16636                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
16637            }
16638        }
16639    }
16640
16641    @Override
16642    public byte[] getIntentFilterVerificationBackup(int userId) {
16643        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16644            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
16645        }
16646
16647        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16648        try {
16649            final XmlSerializer serializer = new FastXmlSerializer();
16650            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16651            serializer.startDocument(null, true);
16652            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
16653
16654            synchronized (mPackages) {
16655                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
16656            }
16657
16658            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
16659            serializer.endDocument();
16660            serializer.flush();
16661        } catch (Exception e) {
16662            if (DEBUG_BACKUP) {
16663                Slog.e(TAG, "Unable to write default apps for backup", e);
16664            }
16665            return null;
16666        }
16667
16668        return dataStream.toByteArray();
16669    }
16670
16671    @Override
16672    public void restoreIntentFilterVerification(byte[] backup, int userId) {
16673        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16674            throw new SecurityException("Only the system may call restorePreferredActivities()");
16675        }
16676
16677        try {
16678            final XmlPullParser parser = Xml.newPullParser();
16679            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16680            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
16681                    new BlobXmlRestorer() {
16682                        @Override
16683                        public void apply(XmlPullParser parser, int userId)
16684                                throws XmlPullParserException, IOException {
16685                            synchronized (mPackages) {
16686                                mSettings.readAllDomainVerificationsLPr(parser, userId);
16687                                mSettings.writeLPr();
16688                            }
16689                        }
16690                    } );
16691        } catch (Exception e) {
16692            if (DEBUG_BACKUP) {
16693                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16694            }
16695        }
16696    }
16697
16698    @Override
16699    public byte[] getPermissionGrantBackup(int userId) {
16700        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16701            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
16702        }
16703
16704        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16705        try {
16706            final XmlSerializer serializer = new FastXmlSerializer();
16707            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16708            serializer.startDocument(null, true);
16709            serializer.startTag(null, TAG_PERMISSION_BACKUP);
16710
16711            synchronized (mPackages) {
16712                serializeRuntimePermissionGrantsLPr(serializer, userId);
16713            }
16714
16715            serializer.endTag(null, TAG_PERMISSION_BACKUP);
16716            serializer.endDocument();
16717            serializer.flush();
16718        } catch (Exception e) {
16719            if (DEBUG_BACKUP) {
16720                Slog.e(TAG, "Unable to write default apps for backup", e);
16721            }
16722            return null;
16723        }
16724
16725        return dataStream.toByteArray();
16726    }
16727
16728    @Override
16729    public void restorePermissionGrants(byte[] backup, int userId) {
16730        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16731            throw new SecurityException("Only the system may call restorePermissionGrants()");
16732        }
16733
16734        try {
16735            final XmlPullParser parser = Xml.newPullParser();
16736            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16737            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
16738                    new BlobXmlRestorer() {
16739                        @Override
16740                        public void apply(XmlPullParser parser, int userId)
16741                                throws XmlPullParserException, IOException {
16742                            synchronized (mPackages) {
16743                                processRestoredPermissionGrantsLPr(parser, userId);
16744                            }
16745                        }
16746                    } );
16747        } catch (Exception e) {
16748            if (DEBUG_BACKUP) {
16749                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16750            }
16751        }
16752    }
16753
16754    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
16755            throws IOException {
16756        serializer.startTag(null, TAG_ALL_GRANTS);
16757
16758        final int N = mSettings.mPackages.size();
16759        for (int i = 0; i < N; i++) {
16760            final PackageSetting ps = mSettings.mPackages.valueAt(i);
16761            boolean pkgGrantsKnown = false;
16762
16763            PermissionsState packagePerms = ps.getPermissionsState();
16764
16765            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
16766                final int grantFlags = state.getFlags();
16767                // only look at grants that are not system/policy fixed
16768                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
16769                    final boolean isGranted = state.isGranted();
16770                    // And only back up the user-twiddled state bits
16771                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
16772                        final String packageName = mSettings.mPackages.keyAt(i);
16773                        if (!pkgGrantsKnown) {
16774                            serializer.startTag(null, TAG_GRANT);
16775                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
16776                            pkgGrantsKnown = true;
16777                        }
16778
16779                        final boolean userSet =
16780                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
16781                        final boolean userFixed =
16782                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
16783                        final boolean revoke =
16784                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
16785
16786                        serializer.startTag(null, TAG_PERMISSION);
16787                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
16788                        if (isGranted) {
16789                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
16790                        }
16791                        if (userSet) {
16792                            serializer.attribute(null, ATTR_USER_SET, "true");
16793                        }
16794                        if (userFixed) {
16795                            serializer.attribute(null, ATTR_USER_FIXED, "true");
16796                        }
16797                        if (revoke) {
16798                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
16799                        }
16800                        serializer.endTag(null, TAG_PERMISSION);
16801                    }
16802                }
16803            }
16804
16805            if (pkgGrantsKnown) {
16806                serializer.endTag(null, TAG_GRANT);
16807            }
16808        }
16809
16810        serializer.endTag(null, TAG_ALL_GRANTS);
16811    }
16812
16813    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
16814            throws XmlPullParserException, IOException {
16815        String pkgName = null;
16816        int outerDepth = parser.getDepth();
16817        int type;
16818        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
16819                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
16820            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
16821                continue;
16822            }
16823
16824            final String tagName = parser.getName();
16825            if (tagName.equals(TAG_GRANT)) {
16826                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
16827                if (DEBUG_BACKUP) {
16828                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
16829                }
16830            } else if (tagName.equals(TAG_PERMISSION)) {
16831
16832                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
16833                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
16834
16835                int newFlagSet = 0;
16836                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
16837                    newFlagSet |= FLAG_PERMISSION_USER_SET;
16838                }
16839                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
16840                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
16841                }
16842                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
16843                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
16844                }
16845                if (DEBUG_BACKUP) {
16846                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
16847                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
16848                }
16849                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16850                if (ps != null) {
16851                    // Already installed so we apply the grant immediately
16852                    if (DEBUG_BACKUP) {
16853                        Slog.v(TAG, "        + already installed; applying");
16854                    }
16855                    PermissionsState perms = ps.getPermissionsState();
16856                    BasePermission bp = mSettings.mPermissions.get(permName);
16857                    if (bp != null) {
16858                        if (isGranted) {
16859                            perms.grantRuntimePermission(bp, userId);
16860                        }
16861                        if (newFlagSet != 0) {
16862                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
16863                        }
16864                    }
16865                } else {
16866                    // Need to wait for post-restore install to apply the grant
16867                    if (DEBUG_BACKUP) {
16868                        Slog.v(TAG, "        - not yet installed; saving for later");
16869                    }
16870                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
16871                            isGranted, newFlagSet, userId);
16872                }
16873            } else {
16874                PackageManagerService.reportSettingsProblem(Log.WARN,
16875                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
16876                XmlUtils.skipCurrentTag(parser);
16877            }
16878        }
16879
16880        scheduleWriteSettingsLocked();
16881        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16882    }
16883
16884    @Override
16885    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
16886            int sourceUserId, int targetUserId, int flags) {
16887        mContext.enforceCallingOrSelfPermission(
16888                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16889        int callingUid = Binder.getCallingUid();
16890        enforceOwnerRights(ownerPackage, callingUid);
16891        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16892        if (intentFilter.countActions() == 0) {
16893            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
16894            return;
16895        }
16896        synchronized (mPackages) {
16897            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
16898                    ownerPackage, targetUserId, flags);
16899            CrossProfileIntentResolver resolver =
16900                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16901            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
16902            // We have all those whose filter is equal. Now checking if the rest is equal as well.
16903            if (existing != null) {
16904                int size = existing.size();
16905                for (int i = 0; i < size; i++) {
16906                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
16907                        return;
16908                    }
16909                }
16910            }
16911            resolver.addFilter(newFilter);
16912            scheduleWritePackageRestrictionsLocked(sourceUserId);
16913        }
16914    }
16915
16916    @Override
16917    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
16918        mContext.enforceCallingOrSelfPermission(
16919                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16920        int callingUid = Binder.getCallingUid();
16921        enforceOwnerRights(ownerPackage, callingUid);
16922        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16923        synchronized (mPackages) {
16924            CrossProfileIntentResolver resolver =
16925                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16926            ArraySet<CrossProfileIntentFilter> set =
16927                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
16928            for (CrossProfileIntentFilter filter : set) {
16929                if (filter.getOwnerPackage().equals(ownerPackage)) {
16930                    resolver.removeFilter(filter);
16931                }
16932            }
16933            scheduleWritePackageRestrictionsLocked(sourceUserId);
16934        }
16935    }
16936
16937    // Enforcing that callingUid is owning pkg on userId
16938    private void enforceOwnerRights(String pkg, int callingUid) {
16939        // The system owns everything.
16940        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
16941            return;
16942        }
16943        int callingUserId = UserHandle.getUserId(callingUid);
16944        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
16945        if (pi == null) {
16946            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
16947                    + callingUserId);
16948        }
16949        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
16950            throw new SecurityException("Calling uid " + callingUid
16951                    + " does not own package " + pkg);
16952        }
16953    }
16954
16955    @Override
16956    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
16957        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
16958    }
16959
16960    private Intent getHomeIntent() {
16961        Intent intent = new Intent(Intent.ACTION_MAIN);
16962        intent.addCategory(Intent.CATEGORY_HOME);
16963        return intent;
16964    }
16965
16966    private IntentFilter getHomeFilter() {
16967        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
16968        filter.addCategory(Intent.CATEGORY_HOME);
16969        filter.addCategory(Intent.CATEGORY_DEFAULT);
16970        return filter;
16971    }
16972
16973    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
16974            int userId) {
16975        Intent intent  = getHomeIntent();
16976        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
16977                PackageManager.GET_META_DATA, userId);
16978        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
16979                true, false, false, userId);
16980
16981        allHomeCandidates.clear();
16982        if (list != null) {
16983            for (ResolveInfo ri : list) {
16984                allHomeCandidates.add(ri);
16985            }
16986        }
16987        return (preferred == null || preferred.activityInfo == null)
16988                ? null
16989                : new ComponentName(preferred.activityInfo.packageName,
16990                        preferred.activityInfo.name);
16991    }
16992
16993    @Override
16994    public void setHomeActivity(ComponentName comp, int userId) {
16995        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
16996        getHomeActivitiesAsUser(homeActivities, userId);
16997
16998        boolean found = false;
16999
17000        final int size = homeActivities.size();
17001        final ComponentName[] set = new ComponentName[size];
17002        for (int i = 0; i < size; i++) {
17003            final ResolveInfo candidate = homeActivities.get(i);
17004            final ActivityInfo info = candidate.activityInfo;
17005            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17006            set[i] = activityName;
17007            if (!found && activityName.equals(comp)) {
17008                found = true;
17009            }
17010        }
17011        if (!found) {
17012            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17013                    + userId);
17014        }
17015        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17016                set, comp, userId);
17017    }
17018
17019    private @Nullable String getSetupWizardPackageName() {
17020        final Intent intent = new Intent(Intent.ACTION_MAIN);
17021        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17022
17023        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17024                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17025                        | MATCH_DISABLED_COMPONENTS,
17026                UserHandle.myUserId());
17027        if (matches.size() == 1) {
17028            return matches.get(0).getComponentInfo().packageName;
17029        } else {
17030            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17031                    + ": matches=" + matches);
17032            return null;
17033        }
17034    }
17035
17036    @Override
17037    public void setApplicationEnabledSetting(String appPackageName,
17038            int newState, int flags, int userId, String callingPackage) {
17039        if (!sUserManager.exists(userId)) return;
17040        if (callingPackage == null) {
17041            callingPackage = Integer.toString(Binder.getCallingUid());
17042        }
17043        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17044    }
17045
17046    @Override
17047    public void setComponentEnabledSetting(ComponentName componentName,
17048            int newState, int flags, int userId) {
17049        if (!sUserManager.exists(userId)) return;
17050        setEnabledSetting(componentName.getPackageName(),
17051                componentName.getClassName(), newState, flags, userId, null);
17052    }
17053
17054    private void setEnabledSetting(final String packageName, String className, int newState,
17055            final int flags, int userId, String callingPackage) {
17056        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17057              || newState == COMPONENT_ENABLED_STATE_ENABLED
17058              || newState == COMPONENT_ENABLED_STATE_DISABLED
17059              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17060              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17061            throw new IllegalArgumentException("Invalid new component state: "
17062                    + newState);
17063        }
17064        PackageSetting pkgSetting;
17065        final int uid = Binder.getCallingUid();
17066        final int permission = mContext.checkCallingOrSelfPermission(
17067                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17068        enforceCrossUserPermission(uid, userId,
17069                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17070        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17071        boolean sendNow = false;
17072        boolean isApp = (className == null);
17073        String componentName = isApp ? packageName : className;
17074        int packageUid = -1;
17075        ArrayList<String> components;
17076
17077        // writer
17078        synchronized (mPackages) {
17079            pkgSetting = mSettings.mPackages.get(packageName);
17080            if (pkgSetting == null) {
17081                if (className == null) {
17082                    throw new IllegalArgumentException("Unknown package: " + packageName);
17083                }
17084                throw new IllegalArgumentException(
17085                        "Unknown component: " + packageName + "/" + className);
17086            }
17087            // Allow root and verify that userId is not being specified by a different user
17088            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
17089                throw new SecurityException(
17090                        "Permission Denial: attempt to change component state from pid="
17091                        + Binder.getCallingPid()
17092                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17093            }
17094            if (className == null) {
17095                // We're dealing with an application/package level state change
17096                if (pkgSetting.getEnabled(userId) == newState) {
17097                    // Nothing to do
17098                    return;
17099                }
17100                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17101                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17102                    // Don't care about who enables an app.
17103                    callingPackage = null;
17104                }
17105                pkgSetting.setEnabled(newState, userId, callingPackage);
17106                // pkgSetting.pkg.mSetEnabled = newState;
17107            } else {
17108                // We're dealing with a component level state change
17109                // First, verify that this is a valid class name.
17110                PackageParser.Package pkg = pkgSetting.pkg;
17111                if (pkg == null || !pkg.hasComponentClassName(className)) {
17112                    if (pkg != null &&
17113                            pkg.applicationInfo.targetSdkVersion >=
17114                                    Build.VERSION_CODES.JELLY_BEAN) {
17115                        throw new IllegalArgumentException("Component class " + className
17116                                + " does not exist in " + packageName);
17117                    } else {
17118                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17119                                + className + " does not exist in " + packageName);
17120                    }
17121                }
17122                switch (newState) {
17123                case COMPONENT_ENABLED_STATE_ENABLED:
17124                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17125                        return;
17126                    }
17127                    break;
17128                case COMPONENT_ENABLED_STATE_DISABLED:
17129                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17130                        return;
17131                    }
17132                    break;
17133                case COMPONENT_ENABLED_STATE_DEFAULT:
17134                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17135                        return;
17136                    }
17137                    break;
17138                default:
17139                    Slog.e(TAG, "Invalid new component state: " + newState);
17140                    return;
17141                }
17142            }
17143            scheduleWritePackageRestrictionsLocked(userId);
17144            components = mPendingBroadcasts.get(userId, packageName);
17145            final boolean newPackage = components == null;
17146            if (newPackage) {
17147                components = new ArrayList<String>();
17148            }
17149            if (!components.contains(componentName)) {
17150                components.add(componentName);
17151            }
17152            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17153                sendNow = true;
17154                // Purge entry from pending broadcast list if another one exists already
17155                // since we are sending one right away.
17156                mPendingBroadcasts.remove(userId, packageName);
17157            } else {
17158                if (newPackage) {
17159                    mPendingBroadcasts.put(userId, packageName, components);
17160                }
17161                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17162                    // Schedule a message
17163                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17164                }
17165            }
17166        }
17167
17168        long callingId = Binder.clearCallingIdentity();
17169        try {
17170            if (sendNow) {
17171                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17172                sendPackageChangedBroadcast(packageName,
17173                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17174            }
17175        } finally {
17176            Binder.restoreCallingIdentity(callingId);
17177        }
17178    }
17179
17180    @Override
17181    public void flushPackageRestrictionsAsUser(int userId) {
17182        if (!sUserManager.exists(userId)) {
17183            return;
17184        }
17185        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17186                false /* checkShell */, "flushPackageRestrictions");
17187        synchronized (mPackages) {
17188            mSettings.writePackageRestrictionsLPr(userId);
17189            mDirtyUsers.remove(userId);
17190            if (mDirtyUsers.isEmpty()) {
17191                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17192            }
17193        }
17194    }
17195
17196    private void sendPackageChangedBroadcast(String packageName,
17197            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17198        if (DEBUG_INSTALL)
17199            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17200                    + componentNames);
17201        Bundle extras = new Bundle(4);
17202        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17203        String nameList[] = new String[componentNames.size()];
17204        componentNames.toArray(nameList);
17205        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17206        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17207        extras.putInt(Intent.EXTRA_UID, packageUid);
17208        // If this is not reporting a change of the overall package, then only send it
17209        // to registered receivers.  We don't want to launch a swath of apps for every
17210        // little component state change.
17211        final int flags = !componentNames.contains(packageName)
17212                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17213        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17214                new int[] {UserHandle.getUserId(packageUid)});
17215    }
17216
17217    @Override
17218    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17219        if (!sUserManager.exists(userId)) return;
17220        final int uid = Binder.getCallingUid();
17221        final int permission = mContext.checkCallingOrSelfPermission(
17222                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17223        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17224        enforceCrossUserPermission(uid, userId,
17225                true /* requireFullPermission */, true /* checkShell */, "stop package");
17226        // writer
17227        synchronized (mPackages) {
17228            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17229                    allowedByPermission, uid, userId)) {
17230                scheduleWritePackageRestrictionsLocked(userId);
17231            }
17232        }
17233    }
17234
17235    @Override
17236    public String getInstallerPackageName(String packageName) {
17237        // reader
17238        synchronized (mPackages) {
17239            return mSettings.getInstallerPackageNameLPr(packageName);
17240        }
17241    }
17242
17243    @Override
17244    public int getApplicationEnabledSetting(String packageName, int userId) {
17245        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17246        int uid = Binder.getCallingUid();
17247        enforceCrossUserPermission(uid, userId,
17248                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17249        // reader
17250        synchronized (mPackages) {
17251            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17252        }
17253    }
17254
17255    @Override
17256    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17257        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17258        int uid = Binder.getCallingUid();
17259        enforceCrossUserPermission(uid, userId,
17260                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17261        // reader
17262        synchronized (mPackages) {
17263            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17264        }
17265    }
17266
17267    @Override
17268    public void enterSafeMode() {
17269        enforceSystemOrRoot("Only the system can request entering safe mode");
17270
17271        if (!mSystemReady) {
17272            mSafeMode = true;
17273        }
17274    }
17275
17276    @Override
17277    public void systemReady() {
17278        mSystemReady = true;
17279
17280        // Read the compatibilty setting when the system is ready.
17281        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17282                mContext.getContentResolver(),
17283                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17284        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17285        if (DEBUG_SETTINGS) {
17286            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17287        }
17288
17289        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17290
17291        synchronized (mPackages) {
17292            // Verify that all of the preferred activity components actually
17293            // exist.  It is possible for applications to be updated and at
17294            // that point remove a previously declared activity component that
17295            // had been set as a preferred activity.  We try to clean this up
17296            // the next time we encounter that preferred activity, but it is
17297            // possible for the user flow to never be able to return to that
17298            // situation so here we do a sanity check to make sure we haven't
17299            // left any junk around.
17300            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17301            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17302                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17303                removed.clear();
17304                for (PreferredActivity pa : pir.filterSet()) {
17305                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17306                        removed.add(pa);
17307                    }
17308                }
17309                if (removed.size() > 0) {
17310                    for (int r=0; r<removed.size(); r++) {
17311                        PreferredActivity pa = removed.get(r);
17312                        Slog.w(TAG, "Removing dangling preferred activity: "
17313                                + pa.mPref.mComponent);
17314                        pir.removeFilter(pa);
17315                    }
17316                    mSettings.writePackageRestrictionsLPr(
17317                            mSettings.mPreferredActivities.keyAt(i));
17318                }
17319            }
17320
17321            for (int userId : UserManagerService.getInstance().getUserIds()) {
17322                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17323                    grantPermissionsUserIds = ArrayUtils.appendInt(
17324                            grantPermissionsUserIds, userId);
17325                }
17326            }
17327        }
17328        sUserManager.systemReady();
17329
17330        // If we upgraded grant all default permissions before kicking off.
17331        for (int userId : grantPermissionsUserIds) {
17332            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17333        }
17334
17335        // Kick off any messages waiting for system ready
17336        if (mPostSystemReadyMessages != null) {
17337            for (Message msg : mPostSystemReadyMessages) {
17338                msg.sendToTarget();
17339            }
17340            mPostSystemReadyMessages = null;
17341        }
17342
17343        // Watch for external volumes that come and go over time
17344        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17345        storage.registerListener(mStorageListener);
17346
17347        mInstallerService.systemReady();
17348        mPackageDexOptimizer.systemReady();
17349
17350        MountServiceInternal mountServiceInternal = LocalServices.getService(
17351                MountServiceInternal.class);
17352        mountServiceInternal.addExternalStoragePolicy(
17353                new MountServiceInternal.ExternalStorageMountPolicy() {
17354            @Override
17355            public int getMountMode(int uid, String packageName) {
17356                if (Process.isIsolated(uid)) {
17357                    return Zygote.MOUNT_EXTERNAL_NONE;
17358                }
17359                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17360                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17361                }
17362                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17363                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17364                }
17365                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17366                    return Zygote.MOUNT_EXTERNAL_READ;
17367                }
17368                return Zygote.MOUNT_EXTERNAL_WRITE;
17369            }
17370
17371            @Override
17372            public boolean hasExternalStorage(int uid, String packageName) {
17373                return true;
17374            }
17375        });
17376    }
17377
17378    @Override
17379    public boolean isSafeMode() {
17380        return mSafeMode;
17381    }
17382
17383    @Override
17384    public boolean hasSystemUidErrors() {
17385        return mHasSystemUidErrors;
17386    }
17387
17388    static String arrayToString(int[] array) {
17389        StringBuffer buf = new StringBuffer(128);
17390        buf.append('[');
17391        if (array != null) {
17392            for (int i=0; i<array.length; i++) {
17393                if (i > 0) buf.append(", ");
17394                buf.append(array[i]);
17395            }
17396        }
17397        buf.append(']');
17398        return buf.toString();
17399    }
17400
17401    static class DumpState {
17402        public static final int DUMP_LIBS = 1 << 0;
17403        public static final int DUMP_FEATURES = 1 << 1;
17404        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
17405        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
17406        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
17407        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
17408        public static final int DUMP_PERMISSIONS = 1 << 6;
17409        public static final int DUMP_PACKAGES = 1 << 7;
17410        public static final int DUMP_SHARED_USERS = 1 << 8;
17411        public static final int DUMP_MESSAGES = 1 << 9;
17412        public static final int DUMP_PROVIDERS = 1 << 10;
17413        public static final int DUMP_VERIFIERS = 1 << 11;
17414        public static final int DUMP_PREFERRED = 1 << 12;
17415        public static final int DUMP_PREFERRED_XML = 1 << 13;
17416        public static final int DUMP_KEYSETS = 1 << 14;
17417        public static final int DUMP_VERSION = 1 << 15;
17418        public static final int DUMP_INSTALLS = 1 << 16;
17419        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
17420        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
17421
17422        public static final int OPTION_SHOW_FILTERS = 1 << 0;
17423
17424        private int mTypes;
17425
17426        private int mOptions;
17427
17428        private boolean mTitlePrinted;
17429
17430        private SharedUserSetting mSharedUser;
17431
17432        public boolean isDumping(int type) {
17433            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
17434                return true;
17435            }
17436
17437            return (mTypes & type) != 0;
17438        }
17439
17440        public void setDump(int type) {
17441            mTypes |= type;
17442        }
17443
17444        public boolean isOptionEnabled(int option) {
17445            return (mOptions & option) != 0;
17446        }
17447
17448        public void setOptionEnabled(int option) {
17449            mOptions |= option;
17450        }
17451
17452        public boolean onTitlePrinted() {
17453            final boolean printed = mTitlePrinted;
17454            mTitlePrinted = true;
17455            return printed;
17456        }
17457
17458        public boolean getTitlePrinted() {
17459            return mTitlePrinted;
17460        }
17461
17462        public void setTitlePrinted(boolean enabled) {
17463            mTitlePrinted = enabled;
17464        }
17465
17466        public SharedUserSetting getSharedUser() {
17467            return mSharedUser;
17468        }
17469
17470        public void setSharedUser(SharedUserSetting user) {
17471            mSharedUser = user;
17472        }
17473    }
17474
17475    @Override
17476    public void onShellCommand(FileDescriptor in, FileDescriptor out,
17477            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
17478        (new PackageManagerShellCommand(this)).exec(
17479                this, in, out, err, args, resultReceiver);
17480    }
17481
17482    @Override
17483    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
17484        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
17485                != PackageManager.PERMISSION_GRANTED) {
17486            pw.println("Permission Denial: can't dump ActivityManager from from pid="
17487                    + Binder.getCallingPid()
17488                    + ", uid=" + Binder.getCallingUid()
17489                    + " without permission "
17490                    + android.Manifest.permission.DUMP);
17491            return;
17492        }
17493
17494        DumpState dumpState = new DumpState();
17495        boolean fullPreferred = false;
17496        boolean checkin = false;
17497
17498        String packageName = null;
17499        ArraySet<String> permissionNames = null;
17500
17501        int opti = 0;
17502        while (opti < args.length) {
17503            String opt = args[opti];
17504            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
17505                break;
17506            }
17507            opti++;
17508
17509            if ("-a".equals(opt)) {
17510                // Right now we only know how to print all.
17511            } else if ("-h".equals(opt)) {
17512                pw.println("Package manager dump options:");
17513                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
17514                pw.println("    --checkin: dump for a checkin");
17515                pw.println("    -f: print details of intent filters");
17516                pw.println("    -h: print this help");
17517                pw.println("  cmd may be one of:");
17518                pw.println("    l[ibraries]: list known shared libraries");
17519                pw.println("    f[eatures]: list device features");
17520                pw.println("    k[eysets]: print known keysets");
17521                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
17522                pw.println("    perm[issions]: dump permissions");
17523                pw.println("    permission [name ...]: dump declaration and use of given permission");
17524                pw.println("    pref[erred]: print preferred package settings");
17525                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
17526                pw.println("    prov[iders]: dump content providers");
17527                pw.println("    p[ackages]: dump installed packages");
17528                pw.println("    s[hared-users]: dump shared user IDs");
17529                pw.println("    m[essages]: print collected runtime messages");
17530                pw.println("    v[erifiers]: print package verifier info");
17531                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
17532                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
17533                pw.println("    version: print database version info");
17534                pw.println("    write: write current settings now");
17535                pw.println("    installs: details about install sessions");
17536                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
17537                pw.println("    <package.name>: info about given package");
17538                return;
17539            } else if ("--checkin".equals(opt)) {
17540                checkin = true;
17541            } else if ("-f".equals(opt)) {
17542                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17543            } else {
17544                pw.println("Unknown argument: " + opt + "; use -h for help");
17545            }
17546        }
17547
17548        // Is the caller requesting to dump a particular piece of data?
17549        if (opti < args.length) {
17550            String cmd = args[opti];
17551            opti++;
17552            // Is this a package name?
17553            if ("android".equals(cmd) || cmd.contains(".")) {
17554                packageName = cmd;
17555                // When dumping a single package, we always dump all of its
17556                // filter information since the amount of data will be reasonable.
17557                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17558            } else if ("check-permission".equals(cmd)) {
17559                if (opti >= args.length) {
17560                    pw.println("Error: check-permission missing permission argument");
17561                    return;
17562                }
17563                String perm = args[opti];
17564                opti++;
17565                if (opti >= args.length) {
17566                    pw.println("Error: check-permission missing package argument");
17567                    return;
17568                }
17569                String pkg = args[opti];
17570                opti++;
17571                int user = UserHandle.getUserId(Binder.getCallingUid());
17572                if (opti < args.length) {
17573                    try {
17574                        user = Integer.parseInt(args[opti]);
17575                    } catch (NumberFormatException e) {
17576                        pw.println("Error: check-permission user argument is not a number: "
17577                                + args[opti]);
17578                        return;
17579                    }
17580                }
17581                pw.println(checkPermission(perm, pkg, user));
17582                return;
17583            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
17584                dumpState.setDump(DumpState.DUMP_LIBS);
17585            } else if ("f".equals(cmd) || "features".equals(cmd)) {
17586                dumpState.setDump(DumpState.DUMP_FEATURES);
17587            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
17588                if (opti >= args.length) {
17589                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
17590                            | DumpState.DUMP_SERVICE_RESOLVERS
17591                            | DumpState.DUMP_RECEIVER_RESOLVERS
17592                            | DumpState.DUMP_CONTENT_RESOLVERS);
17593                } else {
17594                    while (opti < args.length) {
17595                        String name = args[opti];
17596                        if ("a".equals(name) || "activity".equals(name)) {
17597                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
17598                        } else if ("s".equals(name) || "service".equals(name)) {
17599                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
17600                        } else if ("r".equals(name) || "receiver".equals(name)) {
17601                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
17602                        } else if ("c".equals(name) || "content".equals(name)) {
17603                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
17604                        } else {
17605                            pw.println("Error: unknown resolver table type: " + name);
17606                            return;
17607                        }
17608                        opti++;
17609                    }
17610                }
17611            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
17612                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
17613            } else if ("permission".equals(cmd)) {
17614                if (opti >= args.length) {
17615                    pw.println("Error: permission requires permission name");
17616                    return;
17617                }
17618                permissionNames = new ArraySet<>();
17619                while (opti < args.length) {
17620                    permissionNames.add(args[opti]);
17621                    opti++;
17622                }
17623                dumpState.setDump(DumpState.DUMP_PERMISSIONS
17624                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
17625            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
17626                dumpState.setDump(DumpState.DUMP_PREFERRED);
17627            } else if ("preferred-xml".equals(cmd)) {
17628                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
17629                if (opti < args.length && "--full".equals(args[opti])) {
17630                    fullPreferred = true;
17631                    opti++;
17632                }
17633            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
17634                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
17635            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
17636                dumpState.setDump(DumpState.DUMP_PACKAGES);
17637            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
17638                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
17639            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
17640                dumpState.setDump(DumpState.DUMP_PROVIDERS);
17641            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
17642                dumpState.setDump(DumpState.DUMP_MESSAGES);
17643            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
17644                dumpState.setDump(DumpState.DUMP_VERIFIERS);
17645            } else if ("i".equals(cmd) || "ifv".equals(cmd)
17646                    || "intent-filter-verifiers".equals(cmd)) {
17647                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
17648            } else if ("version".equals(cmd)) {
17649                dumpState.setDump(DumpState.DUMP_VERSION);
17650            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
17651                dumpState.setDump(DumpState.DUMP_KEYSETS);
17652            } else if ("installs".equals(cmd)) {
17653                dumpState.setDump(DumpState.DUMP_INSTALLS);
17654            } else if ("write".equals(cmd)) {
17655                synchronized (mPackages) {
17656                    mSettings.writeLPr();
17657                    pw.println("Settings written.");
17658                    return;
17659                }
17660            }
17661        }
17662
17663        if (checkin) {
17664            pw.println("vers,1");
17665        }
17666
17667        // reader
17668        synchronized (mPackages) {
17669            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
17670                if (!checkin) {
17671                    if (dumpState.onTitlePrinted())
17672                        pw.println();
17673                    pw.println("Database versions:");
17674                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
17675                }
17676            }
17677
17678            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
17679                if (!checkin) {
17680                    if (dumpState.onTitlePrinted())
17681                        pw.println();
17682                    pw.println("Verifiers:");
17683                    pw.print("  Required: ");
17684                    pw.print(mRequiredVerifierPackage);
17685                    pw.print(" (uid=");
17686                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17687                            UserHandle.USER_SYSTEM));
17688                    pw.println(")");
17689                } else if (mRequiredVerifierPackage != null) {
17690                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
17691                    pw.print(",");
17692                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17693                            UserHandle.USER_SYSTEM));
17694                }
17695            }
17696
17697            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
17698                    packageName == null) {
17699                if (mIntentFilterVerifierComponent != null) {
17700                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
17701                    if (!checkin) {
17702                        if (dumpState.onTitlePrinted())
17703                            pw.println();
17704                        pw.println("Intent Filter Verifier:");
17705                        pw.print("  Using: ");
17706                        pw.print(verifierPackageName);
17707                        pw.print(" (uid=");
17708                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17709                                UserHandle.USER_SYSTEM));
17710                        pw.println(")");
17711                    } else if (verifierPackageName != null) {
17712                        pw.print("ifv,"); pw.print(verifierPackageName);
17713                        pw.print(",");
17714                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17715                                UserHandle.USER_SYSTEM));
17716                    }
17717                } else {
17718                    pw.println();
17719                    pw.println("No Intent Filter Verifier available!");
17720                }
17721            }
17722
17723            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
17724                boolean printedHeader = false;
17725                final Iterator<String> it = mSharedLibraries.keySet().iterator();
17726                while (it.hasNext()) {
17727                    String name = it.next();
17728                    SharedLibraryEntry ent = mSharedLibraries.get(name);
17729                    if (!checkin) {
17730                        if (!printedHeader) {
17731                            if (dumpState.onTitlePrinted())
17732                                pw.println();
17733                            pw.println("Libraries:");
17734                            printedHeader = true;
17735                        }
17736                        pw.print("  ");
17737                    } else {
17738                        pw.print("lib,");
17739                    }
17740                    pw.print(name);
17741                    if (!checkin) {
17742                        pw.print(" -> ");
17743                    }
17744                    if (ent.path != null) {
17745                        if (!checkin) {
17746                            pw.print("(jar) ");
17747                            pw.print(ent.path);
17748                        } else {
17749                            pw.print(",jar,");
17750                            pw.print(ent.path);
17751                        }
17752                    } else {
17753                        if (!checkin) {
17754                            pw.print("(apk) ");
17755                            pw.print(ent.apk);
17756                        } else {
17757                            pw.print(",apk,");
17758                            pw.print(ent.apk);
17759                        }
17760                    }
17761                    pw.println();
17762                }
17763            }
17764
17765            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
17766                if (dumpState.onTitlePrinted())
17767                    pw.println();
17768                if (!checkin) {
17769                    pw.println("Features:");
17770                }
17771
17772                for (FeatureInfo feat : mAvailableFeatures.values()) {
17773                    if (checkin) {
17774                        pw.print("feat,");
17775                        pw.print(feat.name);
17776                        pw.print(",");
17777                        pw.println(feat.version);
17778                    } else {
17779                        pw.print("  ");
17780                        pw.print(feat.name);
17781                        if (feat.version > 0) {
17782                            pw.print(" version=");
17783                            pw.print(feat.version);
17784                        }
17785                        pw.println();
17786                    }
17787                }
17788            }
17789
17790            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
17791                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
17792                        : "Activity Resolver Table:", "  ", packageName,
17793                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17794                    dumpState.setTitlePrinted(true);
17795                }
17796            }
17797            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
17798                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
17799                        : "Receiver Resolver Table:", "  ", packageName,
17800                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17801                    dumpState.setTitlePrinted(true);
17802                }
17803            }
17804            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
17805                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
17806                        : "Service Resolver Table:", "  ", packageName,
17807                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17808                    dumpState.setTitlePrinted(true);
17809                }
17810            }
17811            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
17812                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
17813                        : "Provider Resolver Table:", "  ", packageName,
17814                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17815                    dumpState.setTitlePrinted(true);
17816                }
17817            }
17818
17819            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
17820                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17821                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17822                    int user = mSettings.mPreferredActivities.keyAt(i);
17823                    if (pir.dump(pw,
17824                            dumpState.getTitlePrinted()
17825                                ? "\nPreferred Activities User " + user + ":"
17826                                : "Preferred Activities User " + user + ":", "  ",
17827                            packageName, true, false)) {
17828                        dumpState.setTitlePrinted(true);
17829                    }
17830                }
17831            }
17832
17833            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
17834                pw.flush();
17835                FileOutputStream fout = new FileOutputStream(fd);
17836                BufferedOutputStream str = new BufferedOutputStream(fout);
17837                XmlSerializer serializer = new FastXmlSerializer();
17838                try {
17839                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
17840                    serializer.startDocument(null, true);
17841                    serializer.setFeature(
17842                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
17843                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
17844                    serializer.endDocument();
17845                    serializer.flush();
17846                } catch (IllegalArgumentException e) {
17847                    pw.println("Failed writing: " + e);
17848                } catch (IllegalStateException e) {
17849                    pw.println("Failed writing: " + e);
17850                } catch (IOException e) {
17851                    pw.println("Failed writing: " + e);
17852                }
17853            }
17854
17855            if (!checkin
17856                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
17857                    && packageName == null) {
17858                pw.println();
17859                int count = mSettings.mPackages.size();
17860                if (count == 0) {
17861                    pw.println("No applications!");
17862                    pw.println();
17863                } else {
17864                    final String prefix = "  ";
17865                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
17866                    if (allPackageSettings.size() == 0) {
17867                        pw.println("No domain preferred apps!");
17868                        pw.println();
17869                    } else {
17870                        pw.println("App verification status:");
17871                        pw.println();
17872                        count = 0;
17873                        for (PackageSetting ps : allPackageSettings) {
17874                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
17875                            if (ivi == null || ivi.getPackageName() == null) continue;
17876                            pw.println(prefix + "Package: " + ivi.getPackageName());
17877                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
17878                            pw.println(prefix + "Status:  " + ivi.getStatusString());
17879                            pw.println();
17880                            count++;
17881                        }
17882                        if (count == 0) {
17883                            pw.println(prefix + "No app verification established.");
17884                            pw.println();
17885                        }
17886                        for (int userId : sUserManager.getUserIds()) {
17887                            pw.println("App linkages for user " + userId + ":");
17888                            pw.println();
17889                            count = 0;
17890                            for (PackageSetting ps : allPackageSettings) {
17891                                final long status = ps.getDomainVerificationStatusForUser(userId);
17892                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
17893                                    continue;
17894                                }
17895                                pw.println(prefix + "Package: " + ps.name);
17896                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
17897                                String statusStr = IntentFilterVerificationInfo.
17898                                        getStatusStringFromValue(status);
17899                                pw.println(prefix + "Status:  " + statusStr);
17900                                pw.println();
17901                                count++;
17902                            }
17903                            if (count == 0) {
17904                                pw.println(prefix + "No configured app linkages.");
17905                                pw.println();
17906                            }
17907                        }
17908                    }
17909                }
17910            }
17911
17912            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
17913                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
17914                if (packageName == null && permissionNames == null) {
17915                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
17916                        if (iperm == 0) {
17917                            if (dumpState.onTitlePrinted())
17918                                pw.println();
17919                            pw.println("AppOp Permissions:");
17920                        }
17921                        pw.print("  AppOp Permission ");
17922                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
17923                        pw.println(":");
17924                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
17925                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
17926                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
17927                        }
17928                    }
17929                }
17930            }
17931
17932            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
17933                boolean printedSomething = false;
17934                for (PackageParser.Provider p : mProviders.mProviders.values()) {
17935                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17936                        continue;
17937                    }
17938                    if (!printedSomething) {
17939                        if (dumpState.onTitlePrinted())
17940                            pw.println();
17941                        pw.println("Registered ContentProviders:");
17942                        printedSomething = true;
17943                    }
17944                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
17945                    pw.print("    "); pw.println(p.toString());
17946                }
17947                printedSomething = false;
17948                for (Map.Entry<String, PackageParser.Provider> entry :
17949                        mProvidersByAuthority.entrySet()) {
17950                    PackageParser.Provider p = entry.getValue();
17951                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17952                        continue;
17953                    }
17954                    if (!printedSomething) {
17955                        if (dumpState.onTitlePrinted())
17956                            pw.println();
17957                        pw.println("ContentProvider Authorities:");
17958                        printedSomething = true;
17959                    }
17960                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
17961                    pw.print("    "); pw.println(p.toString());
17962                    if (p.info != null && p.info.applicationInfo != null) {
17963                        final String appInfo = p.info.applicationInfo.toString();
17964                        pw.print("      applicationInfo="); pw.println(appInfo);
17965                    }
17966                }
17967            }
17968
17969            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
17970                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
17971            }
17972
17973            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
17974                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
17975            }
17976
17977            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
17978                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
17979            }
17980
17981            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
17982                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
17983            }
17984
17985            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
17986                // XXX should handle packageName != null by dumping only install data that
17987                // the given package is involved with.
17988                if (dumpState.onTitlePrinted()) pw.println();
17989                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
17990            }
17991
17992            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
17993                if (dumpState.onTitlePrinted()) pw.println();
17994                mSettings.dumpReadMessagesLPr(pw, dumpState);
17995
17996                pw.println();
17997                pw.println("Package warning messages:");
17998                BufferedReader in = null;
17999                String line = null;
18000                try {
18001                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18002                    while ((line = in.readLine()) != null) {
18003                        if (line.contains("ignored: updated version")) continue;
18004                        pw.println(line);
18005                    }
18006                } catch (IOException ignored) {
18007                } finally {
18008                    IoUtils.closeQuietly(in);
18009                }
18010            }
18011
18012            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18013                BufferedReader in = null;
18014                String line = null;
18015                try {
18016                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18017                    while ((line = in.readLine()) != null) {
18018                        if (line.contains("ignored: updated version")) continue;
18019                        pw.print("msg,");
18020                        pw.println(line);
18021                    }
18022                } catch (IOException ignored) {
18023                } finally {
18024                    IoUtils.closeQuietly(in);
18025                }
18026            }
18027        }
18028    }
18029
18030    private String dumpDomainString(String packageName) {
18031        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18032                .getList();
18033        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18034
18035        ArraySet<String> result = new ArraySet<>();
18036        if (iviList.size() > 0) {
18037            for (IntentFilterVerificationInfo ivi : iviList) {
18038                for (String host : ivi.getDomains()) {
18039                    result.add(host);
18040                }
18041            }
18042        }
18043        if (filters != null && filters.size() > 0) {
18044            for (IntentFilter filter : filters) {
18045                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18046                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18047                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18048                    result.addAll(filter.getHostsList());
18049                }
18050            }
18051        }
18052
18053        StringBuilder sb = new StringBuilder(result.size() * 16);
18054        for (String domain : result) {
18055            if (sb.length() > 0) sb.append(" ");
18056            sb.append(domain);
18057        }
18058        return sb.toString();
18059    }
18060
18061    // ------- apps on sdcard specific code -------
18062    static final boolean DEBUG_SD_INSTALL = false;
18063
18064    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18065
18066    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18067
18068    private boolean mMediaMounted = false;
18069
18070    static String getEncryptKey() {
18071        try {
18072            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18073                    SD_ENCRYPTION_KEYSTORE_NAME);
18074            if (sdEncKey == null) {
18075                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18076                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18077                if (sdEncKey == null) {
18078                    Slog.e(TAG, "Failed to create encryption keys");
18079                    return null;
18080                }
18081            }
18082            return sdEncKey;
18083        } catch (NoSuchAlgorithmException nsae) {
18084            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18085            return null;
18086        } catch (IOException ioe) {
18087            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18088            return null;
18089        }
18090    }
18091
18092    /*
18093     * Update media status on PackageManager.
18094     */
18095    @Override
18096    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18097        int callingUid = Binder.getCallingUid();
18098        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18099            throw new SecurityException("Media status can only be updated by the system");
18100        }
18101        // reader; this apparently protects mMediaMounted, but should probably
18102        // be a different lock in that case.
18103        synchronized (mPackages) {
18104            Log.i(TAG, "Updating external media status from "
18105                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18106                    + (mediaStatus ? "mounted" : "unmounted"));
18107            if (DEBUG_SD_INSTALL)
18108                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18109                        + ", mMediaMounted=" + mMediaMounted);
18110            if (mediaStatus == mMediaMounted) {
18111                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18112                        : 0, -1);
18113                mHandler.sendMessage(msg);
18114                return;
18115            }
18116            mMediaMounted = mediaStatus;
18117        }
18118        // Queue up an async operation since the package installation may take a
18119        // little while.
18120        mHandler.post(new Runnable() {
18121            public void run() {
18122                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18123            }
18124        });
18125    }
18126
18127    /**
18128     * Called by MountService when the initial ASECs to scan are available.
18129     * Should block until all the ASEC containers are finished being scanned.
18130     */
18131    public void scanAvailableAsecs() {
18132        updateExternalMediaStatusInner(true, false, false);
18133    }
18134
18135    /*
18136     * Collect information of applications on external media, map them against
18137     * existing containers and update information based on current mount status.
18138     * Please note that we always have to report status if reportStatus has been
18139     * set to true especially when unloading packages.
18140     */
18141    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18142            boolean externalStorage) {
18143        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18144        int[] uidArr = EmptyArray.INT;
18145
18146        final String[] list = PackageHelper.getSecureContainerList();
18147        if (ArrayUtils.isEmpty(list)) {
18148            Log.i(TAG, "No secure containers found");
18149        } else {
18150            // Process list of secure containers and categorize them
18151            // as active or stale based on their package internal state.
18152
18153            // reader
18154            synchronized (mPackages) {
18155                for (String cid : list) {
18156                    // Leave stages untouched for now; installer service owns them
18157                    if (PackageInstallerService.isStageName(cid)) continue;
18158
18159                    if (DEBUG_SD_INSTALL)
18160                        Log.i(TAG, "Processing container " + cid);
18161                    String pkgName = getAsecPackageName(cid);
18162                    if (pkgName == null) {
18163                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18164                        continue;
18165                    }
18166                    if (DEBUG_SD_INSTALL)
18167                        Log.i(TAG, "Looking for pkg : " + pkgName);
18168
18169                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18170                    if (ps == null) {
18171                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18172                        continue;
18173                    }
18174
18175                    /*
18176                     * Skip packages that are not external if we're unmounting
18177                     * external storage.
18178                     */
18179                    if (externalStorage && !isMounted && !isExternal(ps)) {
18180                        continue;
18181                    }
18182
18183                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18184                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18185                    // The package status is changed only if the code path
18186                    // matches between settings and the container id.
18187                    if (ps.codePathString != null
18188                            && ps.codePathString.startsWith(args.getCodePath())) {
18189                        if (DEBUG_SD_INSTALL) {
18190                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18191                                    + " at code path: " + ps.codePathString);
18192                        }
18193
18194                        // We do have a valid package installed on sdcard
18195                        processCids.put(args, ps.codePathString);
18196                        final int uid = ps.appId;
18197                        if (uid != -1) {
18198                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18199                        }
18200                    } else {
18201                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18202                                + ps.codePathString);
18203                    }
18204                }
18205            }
18206
18207            Arrays.sort(uidArr);
18208        }
18209
18210        // Process packages with valid entries.
18211        if (isMounted) {
18212            if (DEBUG_SD_INSTALL)
18213                Log.i(TAG, "Loading packages");
18214            loadMediaPackages(processCids, uidArr, externalStorage);
18215            startCleaningPackages();
18216            mInstallerService.onSecureContainersAvailable();
18217        } else {
18218            if (DEBUG_SD_INSTALL)
18219                Log.i(TAG, "Unloading packages");
18220            unloadMediaPackages(processCids, uidArr, reportStatus);
18221        }
18222    }
18223
18224    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18225            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18226        final int size = infos.size();
18227        final String[] packageNames = new String[size];
18228        final int[] packageUids = new int[size];
18229        for (int i = 0; i < size; i++) {
18230            final ApplicationInfo info = infos.get(i);
18231            packageNames[i] = info.packageName;
18232            packageUids[i] = info.uid;
18233        }
18234        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18235                finishedReceiver);
18236    }
18237
18238    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18239            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18240        sendResourcesChangedBroadcast(mediaStatus, replacing,
18241                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18242    }
18243
18244    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18245            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18246        int size = pkgList.length;
18247        if (size > 0) {
18248            // Send broadcasts here
18249            Bundle extras = new Bundle();
18250            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18251            if (uidArr != null) {
18252                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18253            }
18254            if (replacing) {
18255                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18256            }
18257            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18258                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18259            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18260        }
18261    }
18262
18263   /*
18264     * Look at potentially valid container ids from processCids If package
18265     * information doesn't match the one on record or package scanning fails,
18266     * the cid is added to list of removeCids. We currently don't delete stale
18267     * containers.
18268     */
18269    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18270            boolean externalStorage) {
18271        ArrayList<String> pkgList = new ArrayList<String>();
18272        Set<AsecInstallArgs> keys = processCids.keySet();
18273
18274        for (AsecInstallArgs args : keys) {
18275            String codePath = processCids.get(args);
18276            if (DEBUG_SD_INSTALL)
18277                Log.i(TAG, "Loading container : " + args.cid);
18278            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
18279            try {
18280                // Make sure there are no container errors first.
18281                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
18282                    Slog.e(TAG, "Failed to mount cid : " + args.cid
18283                            + " when installing from sdcard");
18284                    continue;
18285                }
18286                // Check code path here.
18287                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
18288                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
18289                            + " does not match one in settings " + codePath);
18290                    continue;
18291                }
18292                // Parse package
18293                int parseFlags = mDefParseFlags;
18294                if (args.isExternalAsec()) {
18295                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
18296                }
18297                if (args.isFwdLocked()) {
18298                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
18299                }
18300
18301                synchronized (mInstallLock) {
18302                    PackageParser.Package pkg = null;
18303                    try {
18304                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
18305                    } catch (PackageManagerException e) {
18306                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
18307                    }
18308                    // Scan the package
18309                    if (pkg != null) {
18310                        /*
18311                         * TODO why is the lock being held? doPostInstall is
18312                         * called in other places without the lock. This needs
18313                         * to be straightened out.
18314                         */
18315                        // writer
18316                        synchronized (mPackages) {
18317                            retCode = PackageManager.INSTALL_SUCCEEDED;
18318                            pkgList.add(pkg.packageName);
18319                            // Post process args
18320                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
18321                                    pkg.applicationInfo.uid);
18322                        }
18323                    } else {
18324                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
18325                    }
18326                }
18327
18328            } finally {
18329                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
18330                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
18331                }
18332            }
18333        }
18334        // writer
18335        synchronized (mPackages) {
18336            // If the platform SDK has changed since the last time we booted,
18337            // we need to re-grant app permission to catch any new ones that
18338            // appear. This is really a hack, and means that apps can in some
18339            // cases get permissions that the user didn't initially explicitly
18340            // allow... it would be nice to have some better way to handle
18341            // this situation.
18342            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
18343                    : mSettings.getInternalVersion();
18344            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
18345                    : StorageManager.UUID_PRIVATE_INTERNAL;
18346
18347            int updateFlags = UPDATE_PERMISSIONS_ALL;
18348            if (ver.sdkVersion != mSdkVersion) {
18349                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18350                        + mSdkVersion + "; regranting permissions for external");
18351                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18352            }
18353            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18354
18355            // Yay, everything is now upgraded
18356            ver.forceCurrent();
18357
18358            // can downgrade to reader
18359            // Persist settings
18360            mSettings.writeLPr();
18361        }
18362        // Send a broadcast to let everyone know we are done processing
18363        if (pkgList.size() > 0) {
18364            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
18365        }
18366    }
18367
18368   /*
18369     * Utility method to unload a list of specified containers
18370     */
18371    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
18372        // Just unmount all valid containers.
18373        for (AsecInstallArgs arg : cidArgs) {
18374            synchronized (mInstallLock) {
18375                arg.doPostDeleteLI(false);
18376           }
18377       }
18378   }
18379
18380    /*
18381     * Unload packages mounted on external media. This involves deleting package
18382     * data from internal structures, sending broadcasts about disabled packages,
18383     * gc'ing to free up references, unmounting all secure containers
18384     * corresponding to packages on external media, and posting a
18385     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
18386     * that we always have to post this message if status has been requested no
18387     * matter what.
18388     */
18389    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
18390            final boolean reportStatus) {
18391        if (DEBUG_SD_INSTALL)
18392            Log.i(TAG, "unloading media packages");
18393        ArrayList<String> pkgList = new ArrayList<String>();
18394        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
18395        final Set<AsecInstallArgs> keys = processCids.keySet();
18396        for (AsecInstallArgs args : keys) {
18397            String pkgName = args.getPackageName();
18398            if (DEBUG_SD_INSTALL)
18399                Log.i(TAG, "Trying to unload pkg : " + pkgName);
18400            // Delete package internally
18401            PackageRemovedInfo outInfo = new PackageRemovedInfo();
18402            synchronized (mInstallLock) {
18403                boolean res = deletePackageLI(pkgName, null, false, null,
18404                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null);
18405                if (res) {
18406                    pkgList.add(pkgName);
18407                } else {
18408                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
18409                    failedList.add(args);
18410                }
18411            }
18412        }
18413
18414        // reader
18415        synchronized (mPackages) {
18416            // We didn't update the settings after removing each package;
18417            // write them now for all packages.
18418            mSettings.writeLPr();
18419        }
18420
18421        // We have to absolutely send UPDATED_MEDIA_STATUS only
18422        // after confirming that all the receivers processed the ordered
18423        // broadcast when packages get disabled, force a gc to clean things up.
18424        // and unload all the containers.
18425        if (pkgList.size() > 0) {
18426            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
18427                    new IIntentReceiver.Stub() {
18428                public void performReceive(Intent intent, int resultCode, String data,
18429                        Bundle extras, boolean ordered, boolean sticky,
18430                        int sendingUser) throws RemoteException {
18431                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
18432                            reportStatus ? 1 : 0, 1, keys);
18433                    mHandler.sendMessage(msg);
18434                }
18435            });
18436        } else {
18437            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
18438                    keys);
18439            mHandler.sendMessage(msg);
18440        }
18441    }
18442
18443    private void loadPrivatePackages(final VolumeInfo vol) {
18444        mHandler.post(new Runnable() {
18445            @Override
18446            public void run() {
18447                loadPrivatePackagesInner(vol);
18448            }
18449        });
18450    }
18451
18452    private void loadPrivatePackagesInner(VolumeInfo vol) {
18453        final String volumeUuid = vol.fsUuid;
18454        if (TextUtils.isEmpty(volumeUuid)) {
18455            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
18456            return;
18457        }
18458
18459        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
18460        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
18461
18462        final VersionInfo ver;
18463        final List<PackageSetting> packages;
18464        synchronized (mPackages) {
18465            ver = mSettings.findOrCreateVersion(volumeUuid);
18466            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18467        }
18468
18469        // TODO: introduce a new concept similar to "frozen" to prevent these
18470        // apps from being launched until after data has been fully reconciled
18471        for (PackageSetting ps : packages) {
18472            synchronized (mInstallLock) {
18473                final PackageParser.Package pkg;
18474                try {
18475                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
18476                    loaded.add(pkg.applicationInfo);
18477
18478                } catch (PackageManagerException e) {
18479                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
18480                }
18481
18482                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
18483                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
18484                }
18485            }
18486        }
18487
18488        // Reconcile app data for all started/unlocked users
18489        final StorageManager sm = mContext.getSystemService(StorageManager.class);
18490        final UserManager um = mContext.getSystemService(UserManager.class);
18491        for (UserInfo user : um.getUsers()) {
18492            final int flags;
18493            if (um.isUserUnlocked(user.id)) {
18494                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18495            } else if (um.isUserRunning(user.id)) {
18496                flags = StorageManager.FLAG_STORAGE_DE;
18497            } else {
18498                continue;
18499            }
18500
18501            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
18502            reconcileAppsData(volumeUuid, user.id, flags);
18503        }
18504
18505        synchronized (mPackages) {
18506            int updateFlags = UPDATE_PERMISSIONS_ALL;
18507            if (ver.sdkVersion != mSdkVersion) {
18508                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18509                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
18510                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18511            }
18512            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18513
18514            // Yay, everything is now upgraded
18515            ver.forceCurrent();
18516
18517            mSettings.writeLPr();
18518        }
18519
18520        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
18521        sendResourcesChangedBroadcast(true, false, loaded, null);
18522    }
18523
18524    private void unloadPrivatePackages(final VolumeInfo vol) {
18525        mHandler.post(new Runnable() {
18526            @Override
18527            public void run() {
18528                unloadPrivatePackagesInner(vol);
18529            }
18530        });
18531    }
18532
18533    private void unloadPrivatePackagesInner(VolumeInfo vol) {
18534        final String volumeUuid = vol.fsUuid;
18535        if (TextUtils.isEmpty(volumeUuid)) {
18536            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
18537            return;
18538        }
18539
18540        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
18541        synchronized (mInstallLock) {
18542        synchronized (mPackages) {
18543            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
18544            for (PackageSetting ps : packages) {
18545                if (ps.pkg == null) continue;
18546
18547                final ApplicationInfo info = ps.pkg.applicationInfo;
18548                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
18549                if (deletePackageLI(ps.name, null, false, null,
18550                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) {
18551                    unloaded.add(info);
18552                } else {
18553                    Slog.w(TAG, "Failed to unload " + ps.codePath);
18554                }
18555            }
18556
18557            mSettings.writeLPr();
18558        }
18559        }
18560
18561        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
18562        sendResourcesChangedBroadcast(false, false, unloaded, null);
18563    }
18564
18565    /**
18566     * Examine all users present on given mounted volume, and destroy data
18567     * belonging to users that are no longer valid, or whose user ID has been
18568     * recycled.
18569     */
18570    private void reconcileUsers(String volumeUuid) {
18571        // TODO: also reconcile DE directories
18572        final File[] files = FileUtils
18573                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid));
18574        for (File file : files) {
18575            if (!file.isDirectory()) continue;
18576
18577            final int userId;
18578            final UserInfo info;
18579            try {
18580                userId = Integer.parseInt(file.getName());
18581                info = sUserManager.getUserInfo(userId);
18582            } catch (NumberFormatException e) {
18583                Slog.w(TAG, "Invalid user directory " + file);
18584                continue;
18585            }
18586
18587            boolean destroyUser = false;
18588            if (info == null) {
18589                logCriticalInfo(Log.WARN, "Destroying user directory " + file
18590                        + " because no matching user was found");
18591                destroyUser = true;
18592            } else {
18593                try {
18594                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
18595                } catch (IOException e) {
18596                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
18597                            + " because we failed to enforce serial number: " + e);
18598                    destroyUser = true;
18599                }
18600            }
18601
18602            if (destroyUser) {
18603                synchronized (mInstallLock) {
18604                    try {
18605                        mInstaller.removeUserDataDirs(volumeUuid, userId);
18606                    } catch (InstallerException e) {
18607                        Slog.w(TAG, "Failed to clean up user dirs", e);
18608                    }
18609                }
18610            }
18611        }
18612    }
18613
18614    private void assertPackageKnown(String volumeUuid, String packageName)
18615            throws PackageManagerException {
18616        synchronized (mPackages) {
18617            final PackageSetting ps = mSettings.mPackages.get(packageName);
18618            if (ps == null) {
18619                throw new PackageManagerException("Package " + packageName + " is unknown");
18620            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18621                throw new PackageManagerException(
18622                        "Package " + packageName + " found on unknown volume " + volumeUuid
18623                                + "; expected volume " + ps.volumeUuid);
18624            }
18625        }
18626    }
18627
18628    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
18629            throws PackageManagerException {
18630        synchronized (mPackages) {
18631            final PackageSetting ps = mSettings.mPackages.get(packageName);
18632            if (ps == null) {
18633                throw new PackageManagerException("Package " + packageName + " is unknown");
18634            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18635                throw new PackageManagerException(
18636                        "Package " + packageName + " found on unknown volume " + volumeUuid
18637                                + "; expected volume " + ps.volumeUuid);
18638            } else if (!ps.getInstalled(userId)) {
18639                throw new PackageManagerException(
18640                        "Package " + packageName + " not installed for user " + userId);
18641            }
18642        }
18643    }
18644
18645    /**
18646     * Examine all apps present on given mounted volume, and destroy apps that
18647     * aren't expected, either due to uninstallation or reinstallation on
18648     * another volume.
18649     */
18650    private void reconcileApps(String volumeUuid) {
18651        final File[] files = FileUtils
18652                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
18653        for (File file : files) {
18654            final boolean isPackage = (isApkFile(file) || file.isDirectory())
18655                    && !PackageInstallerService.isStageName(file.getName());
18656            if (!isPackage) {
18657                // Ignore entries which are not packages
18658                continue;
18659            }
18660
18661            try {
18662                final PackageLite pkg = PackageParser.parsePackageLite(file,
18663                        PackageParser.PARSE_MUST_BE_APK);
18664                assertPackageKnown(volumeUuid, pkg.packageName);
18665
18666            } catch (PackageParserException | PackageManagerException e) {
18667                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18668                synchronized (mInstallLock) {
18669                    removeCodePathLI(file);
18670                }
18671            }
18672        }
18673    }
18674
18675    /**
18676     * Reconcile all app data for the given user.
18677     * <p>
18678     * Verifies that directories exist and that ownership and labeling is
18679     * correct for all installed apps on all mounted volumes.
18680     */
18681    void reconcileAppsData(int userId, int flags) {
18682        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18683        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18684            final String volumeUuid = vol.getFsUuid();
18685            reconcileAppsData(volumeUuid, userId, flags);
18686        }
18687    }
18688
18689    /**
18690     * Reconcile all app data on given mounted volume.
18691     * <p>
18692     * Destroys app data that isn't expected, either due to uninstallation or
18693     * reinstallation on another volume.
18694     * <p>
18695     * Verifies that directories exist and that ownership and labeling is
18696     * correct for all installed apps.
18697     */
18698    private void reconcileAppsData(String volumeUuid, int userId, int flags) {
18699        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
18700                + Integer.toHexString(flags));
18701
18702        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
18703        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
18704
18705        boolean restoreconNeeded = false;
18706
18707        // First look for stale data that doesn't belong, and check if things
18708        // have changed since we did our last restorecon
18709        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18710            if (!isUserKeyUnlocked(userId)) {
18711                throw new RuntimeException(
18712                        "Yikes, someone asked us to reconcile CE storage while " + userId
18713                                + " was still locked; this would have caused massive data loss!");
18714            }
18715
18716            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
18717
18718            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
18719            for (File file : files) {
18720                final String packageName = file.getName();
18721                try {
18722                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18723                } catch (PackageManagerException e) {
18724                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18725                    synchronized (mInstallLock) {
18726                        destroyAppDataLI(volumeUuid, packageName, userId,
18727                                StorageManager.FLAG_STORAGE_CE);
18728                    }
18729                }
18730            }
18731        }
18732        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18733            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
18734
18735            final File[] files = FileUtils.listFilesOrEmpty(deDir);
18736            for (File file : files) {
18737                final String packageName = file.getName();
18738                try {
18739                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18740                } catch (PackageManagerException e) {
18741                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18742                    synchronized (mInstallLock) {
18743                        destroyAppDataLI(volumeUuid, packageName, userId,
18744                                StorageManager.FLAG_STORAGE_DE);
18745                    }
18746                }
18747            }
18748        }
18749
18750        // Ensure that data directories are ready to roll for all packages
18751        // installed for this volume and user
18752        final List<PackageSetting> packages;
18753        synchronized (mPackages) {
18754            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18755        }
18756        int preparedCount = 0;
18757        for (PackageSetting ps : packages) {
18758            final String packageName = ps.name;
18759            if (ps.pkg == null) {
18760                Slog.w(TAG, "Odd, missing scanned package " + packageName);
18761                // TODO: might be due to legacy ASEC apps; we should circle back
18762                // and reconcile again once they're scanned
18763                continue;
18764            }
18765
18766            if (ps.getInstalled(userId)) {
18767                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
18768
18769                if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) {
18770                    // We may have just shuffled around app data directories, so
18771                    // prepare them one more time
18772                    prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
18773                }
18774
18775                preparedCount++;
18776            }
18777        }
18778
18779        if (restoreconNeeded) {
18780            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18781                SELinuxMMAC.setRestoreconDone(ceDir);
18782            }
18783            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18784                SELinuxMMAC.setRestoreconDone(deDir);
18785            }
18786        }
18787
18788        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
18789                + " packages; restoreconNeeded was " + restoreconNeeded);
18790    }
18791
18792    /**
18793     * Prepare app data for the given app just after it was installed or
18794     * upgraded. This method carefully only touches users that it's installed
18795     * for, and it forces a restorecon to handle any seinfo changes.
18796     * <p>
18797     * Verifies that directories exist and that ownership and labeling is
18798     * correct for all installed apps. If there is an ownership mismatch, it
18799     * will try recovering system apps by wiping data; third-party app data is
18800     * left intact.
18801     * <p>
18802     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
18803     */
18804    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
18805        prepareAppDataAfterInstallInternal(pkg);
18806        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18807        for (int i = 0; i < childCount; i++) {
18808            PackageParser.Package childPackage = pkg.childPackages.get(i);
18809            prepareAppDataAfterInstallInternal(childPackage);
18810        }
18811    }
18812
18813    private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) {
18814        final PackageSetting ps;
18815        synchronized (mPackages) {
18816            ps = mSettings.mPackages.get(pkg.packageName);
18817            mSettings.writeKernelMappingLPr(ps);
18818        }
18819
18820        final UserManager um = mContext.getSystemService(UserManager.class);
18821        for (UserInfo user : um.getUsers()) {
18822            final int flags;
18823            if (um.isUserUnlocked(user.id)) {
18824                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18825            } else if (um.isUserRunning(user.id)) {
18826                flags = StorageManager.FLAG_STORAGE_DE;
18827            } else {
18828                continue;
18829            }
18830
18831            if (ps.getInstalled(user.id)) {
18832                // Whenever an app changes, force a restorecon of its data
18833                // TODO: when user data is locked, mark that we're still dirty
18834                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
18835            }
18836        }
18837    }
18838
18839    /**
18840     * Prepare app data for the given app.
18841     * <p>
18842     * Verifies that directories exist and that ownership and labeling is
18843     * correct for all installed apps. If there is an ownership mismatch, this
18844     * will try recovering system apps by wiping data; third-party app data is
18845     * left intact.
18846     */
18847    private void prepareAppData(String volumeUuid, int userId, int flags,
18848            PackageParser.Package pkg, boolean restoreconNeeded) {
18849        if (DEBUG_APP_DATA) {
18850            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
18851                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
18852        }
18853
18854        final String packageName = pkg.packageName;
18855        final ApplicationInfo app = pkg.applicationInfo;
18856        final int appId = UserHandle.getAppId(app.uid);
18857
18858        Preconditions.checkNotNull(app.seinfo);
18859
18860        synchronized (mInstallLock) {
18861            try {
18862                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18863                        appId, app.seinfo, app.targetSdkVersion);
18864            } catch (InstallerException e) {
18865                if (app.isSystemApp()) {
18866                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
18867                            + ", but trying to recover: " + e);
18868                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
18869                    try {
18870                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18871                                appId, app.seinfo, app.targetSdkVersion);
18872                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
18873                    } catch (InstallerException e2) {
18874                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
18875                    }
18876                } else {
18877                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
18878                }
18879            }
18880
18881            if (restoreconNeeded) {
18882                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
18883            }
18884
18885            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18886                // Create a native library symlink only if we have native libraries
18887                // and if the native libraries are 32 bit libraries. We do not provide
18888                // this symlink for 64 bit libraries.
18889                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
18890                    final String nativeLibPath = app.nativeLibraryDir;
18891                    try {
18892                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
18893                                nativeLibPath, userId);
18894                    } catch (InstallerException e) {
18895                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
18896                    }
18897                }
18898            }
18899        }
18900    }
18901
18902    /**
18903     * For system apps on non-FBE devices, this method migrates any existing
18904     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
18905     * requested by the app.
18906     */
18907    private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) {
18908        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
18909                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
18910            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
18911                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
18912            synchronized (mInstallLock) {
18913                try {
18914                    mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget);
18915                } catch (InstallerException e) {
18916                    logCriticalInfo(Log.WARN,
18917                            "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
18918                }
18919            }
18920            return true;
18921        } else {
18922            return false;
18923        }
18924    }
18925
18926    private void unfreezePackage(String packageName) {
18927        synchronized (mPackages) {
18928            final PackageSetting ps = mSettings.mPackages.get(packageName);
18929            if (ps != null) {
18930                ps.frozen = false;
18931            }
18932        }
18933    }
18934
18935    @Override
18936    public int movePackage(final String packageName, final String volumeUuid) {
18937        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18938
18939        final int moveId = mNextMoveId.getAndIncrement();
18940        mHandler.post(new Runnable() {
18941            @Override
18942            public void run() {
18943                try {
18944                    movePackageInternal(packageName, volumeUuid, moveId);
18945                } catch (PackageManagerException e) {
18946                    Slog.w(TAG, "Failed to move " + packageName, e);
18947                    mMoveCallbacks.notifyStatusChanged(moveId,
18948                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18949                }
18950            }
18951        });
18952        return moveId;
18953    }
18954
18955    private void movePackageInternal(final String packageName, final String volumeUuid,
18956            final int moveId) throws PackageManagerException {
18957        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
18958        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18959        final PackageManager pm = mContext.getPackageManager();
18960
18961        final boolean currentAsec;
18962        final String currentVolumeUuid;
18963        final File codeFile;
18964        final String installerPackageName;
18965        final String packageAbiOverride;
18966        final int appId;
18967        final String seinfo;
18968        final String label;
18969        final int targetSdkVersion;
18970
18971        // reader
18972        synchronized (mPackages) {
18973            final PackageParser.Package pkg = mPackages.get(packageName);
18974            final PackageSetting ps = mSettings.mPackages.get(packageName);
18975            if (pkg == null || ps == null) {
18976                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
18977            }
18978
18979            if (pkg.applicationInfo.isSystemApp()) {
18980                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
18981                        "Cannot move system application");
18982            }
18983
18984            if (pkg.applicationInfo.isExternalAsec()) {
18985                currentAsec = true;
18986                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
18987            } else if (pkg.applicationInfo.isForwardLocked()) {
18988                currentAsec = true;
18989                currentVolumeUuid = "forward_locked";
18990            } else {
18991                currentAsec = false;
18992                currentVolumeUuid = ps.volumeUuid;
18993
18994                final File probe = new File(pkg.codePath);
18995                final File probeOat = new File(probe, "oat");
18996                if (!probe.isDirectory() || !probeOat.isDirectory()) {
18997                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18998                            "Move only supported for modern cluster style installs");
18999                }
19000            }
19001
19002            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
19003                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19004                        "Package already moved to " + volumeUuid);
19005            }
19006            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
19007                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
19008                        "Device admin cannot be moved");
19009            }
19010
19011            if (ps.frozen) {
19012                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
19013                        "Failed to move already frozen package");
19014            }
19015            ps.frozen = true;
19016
19017            codeFile = new File(pkg.codePath);
19018            installerPackageName = ps.installerPackageName;
19019            packageAbiOverride = ps.cpuAbiOverrideString;
19020            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19021            seinfo = pkg.applicationInfo.seinfo;
19022            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
19023            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
19024        }
19025
19026        // Now that we're guarded by frozen state, kill app during move
19027        final long token = Binder.clearCallingIdentity();
19028        try {
19029            killApplication(packageName, appId, "move pkg");
19030        } finally {
19031            Binder.restoreCallingIdentity(token);
19032        }
19033
19034        final Bundle extras = new Bundle();
19035        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
19036        extras.putString(Intent.EXTRA_TITLE, label);
19037        mMoveCallbacks.notifyCreated(moveId, extras);
19038
19039        int installFlags;
19040        final boolean moveCompleteApp;
19041        final File measurePath;
19042
19043        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
19044            installFlags = INSTALL_INTERNAL;
19045            moveCompleteApp = !currentAsec;
19046            measurePath = Environment.getDataAppDirectory(volumeUuid);
19047        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
19048            installFlags = INSTALL_EXTERNAL;
19049            moveCompleteApp = false;
19050            measurePath = storage.getPrimaryPhysicalVolume().getPath();
19051        } else {
19052            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
19053            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
19054                    || !volume.isMountedWritable()) {
19055                unfreezePackage(packageName);
19056                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19057                        "Move location not mounted private volume");
19058            }
19059
19060            Preconditions.checkState(!currentAsec);
19061
19062            installFlags = INSTALL_INTERNAL;
19063            moveCompleteApp = true;
19064            measurePath = Environment.getDataAppDirectory(volumeUuid);
19065        }
19066
19067        final PackageStats stats = new PackageStats(null, -1);
19068        synchronized (mInstaller) {
19069            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
19070                unfreezePackage(packageName);
19071                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19072                        "Failed to measure package size");
19073            }
19074        }
19075
19076        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
19077                + stats.dataSize);
19078
19079        final long startFreeBytes = measurePath.getFreeSpace();
19080        final long sizeBytes;
19081        if (moveCompleteApp) {
19082            sizeBytes = stats.codeSize + stats.dataSize;
19083        } else {
19084            sizeBytes = stats.codeSize;
19085        }
19086
19087        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
19088            unfreezePackage(packageName);
19089            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19090                    "Not enough free space to move");
19091        }
19092
19093        mMoveCallbacks.notifyStatusChanged(moveId, 10);
19094
19095        final CountDownLatch installedLatch = new CountDownLatch(1);
19096        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
19097            @Override
19098            public void onUserActionRequired(Intent intent) throws RemoteException {
19099                throw new IllegalStateException();
19100            }
19101
19102            @Override
19103            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
19104                    Bundle extras) throws RemoteException {
19105                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
19106                        + PackageManager.installStatusToString(returnCode, msg));
19107
19108                installedLatch.countDown();
19109
19110                // Regardless of success or failure of the move operation,
19111                // always unfreeze the package
19112                unfreezePackage(packageName);
19113
19114                final int status = PackageManager.installStatusToPublicStatus(returnCode);
19115                switch (status) {
19116                    case PackageInstaller.STATUS_SUCCESS:
19117                        mMoveCallbacks.notifyStatusChanged(moveId,
19118                                PackageManager.MOVE_SUCCEEDED);
19119                        break;
19120                    case PackageInstaller.STATUS_FAILURE_STORAGE:
19121                        mMoveCallbacks.notifyStatusChanged(moveId,
19122                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
19123                        break;
19124                    default:
19125                        mMoveCallbacks.notifyStatusChanged(moveId,
19126                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19127                        break;
19128                }
19129            }
19130        };
19131
19132        final MoveInfo move;
19133        if (moveCompleteApp) {
19134            // Kick off a thread to report progress estimates
19135            new Thread() {
19136                @Override
19137                public void run() {
19138                    while (true) {
19139                        try {
19140                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
19141                                break;
19142                            }
19143                        } catch (InterruptedException ignored) {
19144                        }
19145
19146                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
19147                        final int progress = 10 + (int) MathUtils.constrain(
19148                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
19149                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
19150                    }
19151                }
19152            }.start();
19153
19154            final String dataAppName = codeFile.getName();
19155            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
19156                    dataAppName, appId, seinfo, targetSdkVersion);
19157        } else {
19158            move = null;
19159        }
19160
19161        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
19162
19163        final Message msg = mHandler.obtainMessage(INIT_COPY);
19164        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
19165        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
19166                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
19167                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
19168        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
19169        msg.obj = params;
19170
19171        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
19172                System.identityHashCode(msg.obj));
19173        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
19174                System.identityHashCode(msg.obj));
19175
19176        mHandler.sendMessage(msg);
19177    }
19178
19179    @Override
19180    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
19181        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19182
19183        final int realMoveId = mNextMoveId.getAndIncrement();
19184        final Bundle extras = new Bundle();
19185        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
19186        mMoveCallbacks.notifyCreated(realMoveId, extras);
19187
19188        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
19189            @Override
19190            public void onCreated(int moveId, Bundle extras) {
19191                // Ignored
19192            }
19193
19194            @Override
19195            public void onStatusChanged(int moveId, int status, long estMillis) {
19196                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
19197            }
19198        };
19199
19200        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19201        storage.setPrimaryStorageUuid(volumeUuid, callback);
19202        return realMoveId;
19203    }
19204
19205    @Override
19206    public int getMoveStatus(int moveId) {
19207        mContext.enforceCallingOrSelfPermission(
19208                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19209        return mMoveCallbacks.mLastStatus.get(moveId);
19210    }
19211
19212    @Override
19213    public void registerMoveCallback(IPackageMoveObserver callback) {
19214        mContext.enforceCallingOrSelfPermission(
19215                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19216        mMoveCallbacks.register(callback);
19217    }
19218
19219    @Override
19220    public void unregisterMoveCallback(IPackageMoveObserver callback) {
19221        mContext.enforceCallingOrSelfPermission(
19222                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19223        mMoveCallbacks.unregister(callback);
19224    }
19225
19226    @Override
19227    public boolean setInstallLocation(int loc) {
19228        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
19229                null);
19230        if (getInstallLocation() == loc) {
19231            return true;
19232        }
19233        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
19234                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
19235            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
19236                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
19237            return true;
19238        }
19239        return false;
19240   }
19241
19242    @Override
19243    public int getInstallLocation() {
19244        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
19245                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
19246                PackageHelper.APP_INSTALL_AUTO);
19247    }
19248
19249    /** Called by UserManagerService */
19250    void cleanUpUser(UserManagerService userManager, int userHandle) {
19251        synchronized (mPackages) {
19252            mDirtyUsers.remove(userHandle);
19253            mUserNeedsBadging.delete(userHandle);
19254            mSettings.removeUserLPw(userHandle);
19255            mPendingBroadcasts.remove(userHandle);
19256            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
19257        }
19258        synchronized (mInstallLock) {
19259            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19260            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19261                final String volumeUuid = vol.getFsUuid();
19262                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
19263                try {
19264                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
19265                } catch (InstallerException e) {
19266                    Slog.w(TAG, "Failed to remove user data", e);
19267                }
19268            }
19269            synchronized (mPackages) {
19270                removeUnusedPackagesLILPw(userManager, userHandle);
19271            }
19272        }
19273    }
19274
19275    /**
19276     * We're removing userHandle and would like to remove any downloaded packages
19277     * that are no longer in use by any other user.
19278     * @param userHandle the user being removed
19279     */
19280    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
19281        final boolean DEBUG_CLEAN_APKS = false;
19282        int [] users = userManager.getUserIds();
19283        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
19284        while (psit.hasNext()) {
19285            PackageSetting ps = psit.next();
19286            if (ps.pkg == null) {
19287                continue;
19288            }
19289            final String packageName = ps.pkg.packageName;
19290            // Skip over if system app
19291            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
19292                continue;
19293            }
19294            if (DEBUG_CLEAN_APKS) {
19295                Slog.i(TAG, "Checking package " + packageName);
19296            }
19297            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
19298            if (keep) {
19299                if (DEBUG_CLEAN_APKS) {
19300                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
19301                }
19302            } else {
19303                for (int i = 0; i < users.length; i++) {
19304                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
19305                        keep = true;
19306                        if (DEBUG_CLEAN_APKS) {
19307                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
19308                                    + users[i]);
19309                        }
19310                        break;
19311                    }
19312                }
19313            }
19314            if (!keep) {
19315                if (DEBUG_CLEAN_APKS) {
19316                    Slog.i(TAG, "  Removing package " + packageName);
19317                }
19318                mHandler.post(new Runnable() {
19319                    public void run() {
19320                        deletePackageX(packageName, userHandle, 0);
19321                    } //end run
19322                });
19323            }
19324        }
19325    }
19326
19327    /** Called by UserManagerService */
19328    void createNewUser(int userHandle) {
19329        synchronized (mInstallLock) {
19330            try {
19331                mInstaller.createUserConfig(userHandle);
19332            } catch (InstallerException e) {
19333                Slog.w(TAG, "Failed to create user config", e);
19334            }
19335            mSettings.createNewUserLI(this, mInstaller, userHandle);
19336        }
19337        synchronized (mPackages) {
19338            applyFactoryDefaultBrowserLPw(userHandle);
19339            primeDomainVerificationsLPw(userHandle);
19340        }
19341    }
19342
19343    void newUserCreated(final int userHandle) {
19344        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
19345        // If permission review for legacy apps is required, we represent
19346        // dagerous permissions for such apps as always granted runtime
19347        // permissions to keep per user flag state whether review is needed.
19348        // Hence, if a new user is added we have to propagate dangerous
19349        // permission grants for these legacy apps.
19350        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
19351            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
19352                    | UPDATE_PERMISSIONS_REPLACE_ALL);
19353        }
19354    }
19355
19356    @Override
19357    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
19358        mContext.enforceCallingOrSelfPermission(
19359                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
19360                "Only package verification agents can read the verifier device identity");
19361
19362        synchronized (mPackages) {
19363            return mSettings.getVerifierDeviceIdentityLPw();
19364        }
19365    }
19366
19367    @Override
19368    public void setPermissionEnforced(String permission, boolean enforced) {
19369        // TODO: Now that we no longer change GID for storage, this should to away.
19370        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
19371                "setPermissionEnforced");
19372        if (READ_EXTERNAL_STORAGE.equals(permission)) {
19373            synchronized (mPackages) {
19374                if (mSettings.mReadExternalStorageEnforced == null
19375                        || mSettings.mReadExternalStorageEnforced != enforced) {
19376                    mSettings.mReadExternalStorageEnforced = enforced;
19377                    mSettings.writeLPr();
19378                }
19379            }
19380            // kill any non-foreground processes so we restart them and
19381            // grant/revoke the GID.
19382            final IActivityManager am = ActivityManagerNative.getDefault();
19383            if (am != null) {
19384                final long token = Binder.clearCallingIdentity();
19385                try {
19386                    am.killProcessesBelowForeground("setPermissionEnforcement");
19387                } catch (RemoteException e) {
19388                } finally {
19389                    Binder.restoreCallingIdentity(token);
19390                }
19391            }
19392        } else {
19393            throw new IllegalArgumentException("No selective enforcement for " + permission);
19394        }
19395    }
19396
19397    @Override
19398    @Deprecated
19399    public boolean isPermissionEnforced(String permission) {
19400        return true;
19401    }
19402
19403    @Override
19404    public boolean isStorageLow() {
19405        final long token = Binder.clearCallingIdentity();
19406        try {
19407            final DeviceStorageMonitorInternal
19408                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
19409            if (dsm != null) {
19410                return dsm.isMemoryLow();
19411            } else {
19412                return false;
19413            }
19414        } finally {
19415            Binder.restoreCallingIdentity(token);
19416        }
19417    }
19418
19419    @Override
19420    public IPackageInstaller getPackageInstaller() {
19421        return mInstallerService;
19422    }
19423
19424    private boolean userNeedsBadging(int userId) {
19425        int index = mUserNeedsBadging.indexOfKey(userId);
19426        if (index < 0) {
19427            final UserInfo userInfo;
19428            final long token = Binder.clearCallingIdentity();
19429            try {
19430                userInfo = sUserManager.getUserInfo(userId);
19431            } finally {
19432                Binder.restoreCallingIdentity(token);
19433            }
19434            final boolean b;
19435            if (userInfo != null && userInfo.isManagedProfile()) {
19436                b = true;
19437            } else {
19438                b = false;
19439            }
19440            mUserNeedsBadging.put(userId, b);
19441            return b;
19442        }
19443        return mUserNeedsBadging.valueAt(index);
19444    }
19445
19446    @Override
19447    public KeySet getKeySetByAlias(String packageName, String alias) {
19448        if (packageName == null || alias == null) {
19449            return null;
19450        }
19451        synchronized(mPackages) {
19452            final PackageParser.Package pkg = mPackages.get(packageName);
19453            if (pkg == null) {
19454                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19455                throw new IllegalArgumentException("Unknown package: " + packageName);
19456            }
19457            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19458            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
19459        }
19460    }
19461
19462    @Override
19463    public KeySet getSigningKeySet(String packageName) {
19464        if (packageName == null) {
19465            return null;
19466        }
19467        synchronized(mPackages) {
19468            final PackageParser.Package pkg = mPackages.get(packageName);
19469            if (pkg == null) {
19470                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19471                throw new IllegalArgumentException("Unknown package: " + packageName);
19472            }
19473            if (pkg.applicationInfo.uid != Binder.getCallingUid()
19474                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
19475                throw new SecurityException("May not access signing KeySet of other apps.");
19476            }
19477            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19478            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
19479        }
19480    }
19481
19482    @Override
19483    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
19484        if (packageName == null || ks == null) {
19485            return false;
19486        }
19487        synchronized(mPackages) {
19488            final PackageParser.Package pkg = mPackages.get(packageName);
19489            if (pkg == null) {
19490                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19491                throw new IllegalArgumentException("Unknown package: " + packageName);
19492            }
19493            IBinder ksh = ks.getToken();
19494            if (ksh instanceof KeySetHandle) {
19495                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19496                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
19497            }
19498            return false;
19499        }
19500    }
19501
19502    @Override
19503    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
19504        if (packageName == null || ks == null) {
19505            return false;
19506        }
19507        synchronized(mPackages) {
19508            final PackageParser.Package pkg = mPackages.get(packageName);
19509            if (pkg == null) {
19510                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19511                throw new IllegalArgumentException("Unknown package: " + packageName);
19512            }
19513            IBinder ksh = ks.getToken();
19514            if (ksh instanceof KeySetHandle) {
19515                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19516                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
19517            }
19518            return false;
19519        }
19520    }
19521
19522    private void deletePackageIfUnusedLPr(final String packageName) {
19523        PackageSetting ps = mSettings.mPackages.get(packageName);
19524        if (ps == null) {
19525            return;
19526        }
19527        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
19528            // TODO Implement atomic delete if package is unused
19529            // It is currently possible that the package will be deleted even if it is installed
19530            // after this method returns.
19531            mHandler.post(new Runnable() {
19532                public void run() {
19533                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
19534                }
19535            });
19536        }
19537    }
19538
19539    /**
19540     * Check and throw if the given before/after packages would be considered a
19541     * downgrade.
19542     */
19543    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
19544            throws PackageManagerException {
19545        if (after.versionCode < before.mVersionCode) {
19546            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19547                    "Update version code " + after.versionCode + " is older than current "
19548                    + before.mVersionCode);
19549        } else if (after.versionCode == before.mVersionCode) {
19550            if (after.baseRevisionCode < before.baseRevisionCode) {
19551                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19552                        "Update base revision code " + after.baseRevisionCode
19553                        + " is older than current " + before.baseRevisionCode);
19554            }
19555
19556            if (!ArrayUtils.isEmpty(after.splitNames)) {
19557                for (int i = 0; i < after.splitNames.length; i++) {
19558                    final String splitName = after.splitNames[i];
19559                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
19560                    if (j != -1) {
19561                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
19562                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19563                                    "Update split " + splitName + " revision code "
19564                                    + after.splitRevisionCodes[i] + " is older than current "
19565                                    + before.splitRevisionCodes[j]);
19566                        }
19567                    }
19568                }
19569            }
19570        }
19571    }
19572
19573    private static class MoveCallbacks extends Handler {
19574        private static final int MSG_CREATED = 1;
19575        private static final int MSG_STATUS_CHANGED = 2;
19576
19577        private final RemoteCallbackList<IPackageMoveObserver>
19578                mCallbacks = new RemoteCallbackList<>();
19579
19580        private final SparseIntArray mLastStatus = new SparseIntArray();
19581
19582        public MoveCallbacks(Looper looper) {
19583            super(looper);
19584        }
19585
19586        public void register(IPackageMoveObserver callback) {
19587            mCallbacks.register(callback);
19588        }
19589
19590        public void unregister(IPackageMoveObserver callback) {
19591            mCallbacks.unregister(callback);
19592        }
19593
19594        @Override
19595        public void handleMessage(Message msg) {
19596            final SomeArgs args = (SomeArgs) msg.obj;
19597            final int n = mCallbacks.beginBroadcast();
19598            for (int i = 0; i < n; i++) {
19599                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
19600                try {
19601                    invokeCallback(callback, msg.what, args);
19602                } catch (RemoteException ignored) {
19603                }
19604            }
19605            mCallbacks.finishBroadcast();
19606            args.recycle();
19607        }
19608
19609        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
19610                throws RemoteException {
19611            switch (what) {
19612                case MSG_CREATED: {
19613                    callback.onCreated(args.argi1, (Bundle) args.arg2);
19614                    break;
19615                }
19616                case MSG_STATUS_CHANGED: {
19617                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
19618                    break;
19619                }
19620            }
19621        }
19622
19623        private void notifyCreated(int moveId, Bundle extras) {
19624            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
19625
19626            final SomeArgs args = SomeArgs.obtain();
19627            args.argi1 = moveId;
19628            args.arg2 = extras;
19629            obtainMessage(MSG_CREATED, args).sendToTarget();
19630        }
19631
19632        private void notifyStatusChanged(int moveId, int status) {
19633            notifyStatusChanged(moveId, status, -1);
19634        }
19635
19636        private void notifyStatusChanged(int moveId, int status, long estMillis) {
19637            Slog.v(TAG, "Move " + moveId + " status " + status);
19638
19639            final SomeArgs args = SomeArgs.obtain();
19640            args.argi1 = moveId;
19641            args.argi2 = status;
19642            args.arg3 = estMillis;
19643            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
19644
19645            synchronized (mLastStatus) {
19646                mLastStatus.put(moveId, status);
19647            }
19648        }
19649    }
19650
19651    private final static class OnPermissionChangeListeners extends Handler {
19652        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
19653
19654        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
19655                new RemoteCallbackList<>();
19656
19657        public OnPermissionChangeListeners(Looper looper) {
19658            super(looper);
19659        }
19660
19661        @Override
19662        public void handleMessage(Message msg) {
19663            switch (msg.what) {
19664                case MSG_ON_PERMISSIONS_CHANGED: {
19665                    final int uid = msg.arg1;
19666                    handleOnPermissionsChanged(uid);
19667                } break;
19668            }
19669        }
19670
19671        public void addListenerLocked(IOnPermissionsChangeListener listener) {
19672            mPermissionListeners.register(listener);
19673
19674        }
19675
19676        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
19677            mPermissionListeners.unregister(listener);
19678        }
19679
19680        public void onPermissionsChanged(int uid) {
19681            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
19682                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
19683            }
19684        }
19685
19686        private void handleOnPermissionsChanged(int uid) {
19687            final int count = mPermissionListeners.beginBroadcast();
19688            try {
19689                for (int i = 0; i < count; i++) {
19690                    IOnPermissionsChangeListener callback = mPermissionListeners
19691                            .getBroadcastItem(i);
19692                    try {
19693                        callback.onPermissionsChanged(uid);
19694                    } catch (RemoteException e) {
19695                        Log.e(TAG, "Permission listener is dead", e);
19696                    }
19697                }
19698            } finally {
19699                mPermissionListeners.finishBroadcast();
19700            }
19701        }
19702    }
19703
19704    private class PackageManagerInternalImpl extends PackageManagerInternal {
19705        @Override
19706        public void setLocationPackagesProvider(PackagesProvider provider) {
19707            synchronized (mPackages) {
19708                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
19709            }
19710        }
19711
19712        @Override
19713        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
19714            synchronized (mPackages) {
19715                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
19716            }
19717        }
19718
19719        @Override
19720        public void setSmsAppPackagesProvider(PackagesProvider provider) {
19721            synchronized (mPackages) {
19722                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
19723            }
19724        }
19725
19726        @Override
19727        public void setDialerAppPackagesProvider(PackagesProvider provider) {
19728            synchronized (mPackages) {
19729                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
19730            }
19731        }
19732
19733        @Override
19734        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
19735            synchronized (mPackages) {
19736                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
19737            }
19738        }
19739
19740        @Override
19741        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
19742            synchronized (mPackages) {
19743                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
19744            }
19745        }
19746
19747        @Override
19748        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
19749            synchronized (mPackages) {
19750                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
19751                        packageName, userId);
19752            }
19753        }
19754
19755        @Override
19756        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
19757            synchronized (mPackages) {
19758                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
19759                        packageName, userId);
19760            }
19761        }
19762
19763        @Override
19764        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
19765            synchronized (mPackages) {
19766                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
19767                        packageName, userId);
19768            }
19769        }
19770
19771        @Override
19772        public void setKeepUninstalledPackages(final List<String> packageList) {
19773            Preconditions.checkNotNull(packageList);
19774            List<String> removedFromList = null;
19775            synchronized (mPackages) {
19776                if (mKeepUninstalledPackages != null) {
19777                    final int packagesCount = mKeepUninstalledPackages.size();
19778                    for (int i = 0; i < packagesCount; i++) {
19779                        String oldPackage = mKeepUninstalledPackages.get(i);
19780                        if (packageList != null && packageList.contains(oldPackage)) {
19781                            continue;
19782                        }
19783                        if (removedFromList == null) {
19784                            removedFromList = new ArrayList<>();
19785                        }
19786                        removedFromList.add(oldPackage);
19787                    }
19788                }
19789                mKeepUninstalledPackages = new ArrayList<>(packageList);
19790                if (removedFromList != null) {
19791                    final int removedCount = removedFromList.size();
19792                    for (int i = 0; i < removedCount; i++) {
19793                        deletePackageIfUnusedLPr(removedFromList.get(i));
19794                    }
19795                }
19796            }
19797        }
19798
19799        @Override
19800        public boolean isPermissionsReviewRequired(String packageName, int userId) {
19801            synchronized (mPackages) {
19802                // If we do not support permission review, done.
19803                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
19804                    return false;
19805                }
19806
19807                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
19808                if (packageSetting == null) {
19809                    return false;
19810                }
19811
19812                // Permission review applies only to apps not supporting the new permission model.
19813                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
19814                    return false;
19815                }
19816
19817                // Legacy apps have the permission and get user consent on launch.
19818                PermissionsState permissionsState = packageSetting.getPermissionsState();
19819                return permissionsState.isPermissionReviewRequired(userId);
19820            }
19821        }
19822
19823        @Override
19824        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
19825            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
19826        }
19827
19828        @Override
19829        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19830                int userId) {
19831            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
19832        }
19833    }
19834
19835    @Override
19836    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
19837        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
19838        synchronized (mPackages) {
19839            final long identity = Binder.clearCallingIdentity();
19840            try {
19841                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
19842                        packageNames, userId);
19843            } finally {
19844                Binder.restoreCallingIdentity(identity);
19845            }
19846        }
19847    }
19848
19849    private static void enforceSystemOrPhoneCaller(String tag) {
19850        int callingUid = Binder.getCallingUid();
19851        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
19852            throw new SecurityException(
19853                    "Cannot call " + tag + " from UID " + callingUid);
19854        }
19855    }
19856
19857    boolean isHistoricalPackageUsageAvailable() {
19858        return mPackageUsage.isHistoricalPackageUsageAvailable();
19859    }
19860
19861    /**
19862     * Return a <b>copy</b> of the collection of packages known to the package manager.
19863     * @return A copy of the values of mPackages.
19864     */
19865    Collection<PackageParser.Package> getPackages() {
19866        synchronized (mPackages) {
19867            return new ArrayList<>(mPackages.values());
19868        }
19869    }
19870
19871    /**
19872     * Logs process start information (including base APK hash) to the security log.
19873     * @hide
19874     */
19875    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
19876            String apkFile, int pid) {
19877        if (!SecurityLog.isLoggingEnabled()) {
19878            return;
19879        }
19880        Bundle data = new Bundle();
19881        data.putLong("startTimestamp", System.currentTimeMillis());
19882        data.putString("processName", processName);
19883        data.putInt("uid", uid);
19884        data.putString("seinfo", seinfo);
19885        data.putString("apkFile", apkFile);
19886        data.putInt("pid", pid);
19887        Message msg = mProcessLoggingHandler.obtainMessage(
19888                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
19889        msg.setData(data);
19890        mProcessLoggingHandler.sendMessage(msg);
19891    }
19892}
19893