PackageManagerService.java revision 5c8acb4380874d7793ba4e44fd3f7baa9a0cb692
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.app.usage.UsageStatsManager;
114import android.content.BroadcastReceiver;
115import android.content.ComponentName;
116import android.content.Context;
117import android.content.IIntentReceiver;
118import android.content.Intent;
119import android.content.IntentFilter;
120import android.content.IntentFilter.AuthorityEntry;
121import android.content.IntentSender;
122import android.content.IntentSender.SendIntentException;
123import android.content.ServiceConnection;
124import android.content.pm.ActivityInfo;
125import android.content.pm.ApplicationInfo;
126import android.content.pm.AppsQueryHelper;
127import android.content.pm.ComponentInfo;
128import android.content.pm.EphemeralApplicationInfo;
129import android.content.pm.EphemeralResolveInfo;
130import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
131import android.content.pm.FeatureInfo;
132import android.content.pm.IOnPermissionsChangeListener;
133import android.content.pm.IPackageDataObserver;
134import android.content.pm.IPackageDeleteObserver;
135import android.content.pm.IPackageDeleteObserver2;
136import android.content.pm.IPackageInstallObserver2;
137import android.content.pm.IPackageInstaller;
138import android.content.pm.IPackageManager;
139import android.content.pm.IPackageMoveObserver;
140import android.content.pm.IPackageStatsObserver;
141import android.content.pm.InstrumentationInfo;
142import android.content.pm.IntentFilterVerificationInfo;
143import android.content.pm.KeySet;
144import android.content.pm.PackageCleanItem;
145import android.content.pm.PackageInfo;
146import android.content.pm.PackageInfoLite;
147import android.content.pm.PackageInstaller;
148import android.content.pm.PackageManager;
149import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
150import android.content.pm.PackageManagerInternal;
151import android.content.pm.PackageParser;
152import android.content.pm.PackageParser.ActivityIntentInfo;
153import android.content.pm.PackageParser.IntentInfo;
154import android.content.pm.PackageParser.PackageLite;
155import android.content.pm.PackageParser.PackageParserException;
156import android.content.pm.PackageStats;
157import android.content.pm.PackageUserState;
158import android.content.pm.ParceledListSlice;
159import android.content.pm.PermissionGroupInfo;
160import android.content.pm.PermissionInfo;
161import android.content.pm.ProviderInfo;
162import android.content.pm.ResolveInfo;
163import android.content.pm.ServiceInfo;
164import android.content.pm.Signature;
165import android.content.pm.UserInfo;
166import android.content.pm.VerifierDeviceIdentity;
167import android.content.pm.VerifierInfo;
168import android.content.res.Resources;
169import android.graphics.Bitmap;
170import android.hardware.display.DisplayManager;
171import android.net.Uri;
172import android.os.Binder;
173import android.os.Build;
174import android.os.Bundle;
175import android.os.Debug;
176import android.os.Environment;
177import android.os.Environment.UserEnvironment;
178import android.os.FileUtils;
179import android.os.Handler;
180import android.os.IBinder;
181import android.os.Looper;
182import android.os.Message;
183import android.os.Parcel;
184import android.os.ParcelFileDescriptor;
185import android.os.Process;
186import android.os.RemoteCallbackList;
187import android.os.RemoteException;
188import android.os.ResultReceiver;
189import android.os.SELinux;
190import android.os.ServiceManager;
191import android.os.SystemClock;
192import android.os.SystemProperties;
193import android.os.Trace;
194import android.os.UserHandle;
195import android.os.UserManager;
196import android.os.storage.IMountService;
197import android.os.storage.MountServiceInternal;
198import android.os.storage.StorageEventListener;
199import android.os.storage.StorageManager;
200import android.os.storage.VolumeInfo;
201import android.os.storage.VolumeRecord;
202import android.security.KeyStore;
203import android.security.SystemKeyStore;
204import android.system.ErrnoException;
205import android.system.Os;
206import android.text.TextUtils;
207import android.text.format.DateUtils;
208import android.util.ArrayMap;
209import android.util.ArraySet;
210import android.util.AtomicFile;
211import android.util.DisplayMetrics;
212import android.util.EventLog;
213import android.util.ExceptionUtils;
214import android.util.Log;
215import android.util.LogPrinter;
216import android.util.MathUtils;
217import android.util.PrintStreamPrinter;
218import android.util.Slog;
219import android.util.SparseArray;
220import android.util.SparseBooleanArray;
221import android.util.SparseIntArray;
222import android.util.Xml;
223import android.view.Display;
224
225import com.android.internal.R;
226import com.android.internal.annotations.GuardedBy;
227import com.android.internal.app.IMediaContainerService;
228import com.android.internal.app.ResolverActivity;
229import com.android.internal.content.NativeLibraryHelper;
230import com.android.internal.content.PackageHelper;
231import com.android.internal.os.IParcelFileDescriptorFactory;
232import com.android.internal.os.InstallerConnection.InstallerException;
233import com.android.internal.os.SomeArgs;
234import com.android.internal.os.Zygote;
235import com.android.internal.util.ArrayUtils;
236import com.android.internal.util.FastPrintWriter;
237import com.android.internal.util.FastXmlSerializer;
238import com.android.internal.util.IndentingPrintWriter;
239import com.android.internal.util.Preconditions;
240import com.android.internal.util.XmlUtils;
241import com.android.server.EventLogTags;
242import com.android.server.FgThread;
243import com.android.server.IntentResolver;
244import com.android.server.LocalServices;
245import com.android.server.ServiceThread;
246import com.android.server.SystemConfig;
247import com.android.server.Watchdog;
248import com.android.server.pm.PermissionsState.PermissionState;
249import com.android.server.pm.Settings.DatabaseVersion;
250import com.android.server.pm.Settings.VersionInfo;
251import com.android.server.storage.DeviceStorageMonitorInternal;
252
253import dalvik.system.DexFile;
254import dalvik.system.VMRuntime;
255
256import libcore.io.IoUtils;
257import libcore.util.EmptyArray;
258
259import org.xmlpull.v1.XmlPullParser;
260import org.xmlpull.v1.XmlPullParserException;
261import org.xmlpull.v1.XmlSerializer;
262
263import java.io.BufferedInputStream;
264import java.io.BufferedOutputStream;
265import java.io.BufferedReader;
266import java.io.ByteArrayInputStream;
267import java.io.ByteArrayOutputStream;
268import java.io.File;
269import java.io.FileDescriptor;
270import java.io.FileNotFoundException;
271import java.io.FileOutputStream;
272import java.io.FileReader;
273import java.io.FilenameFilter;
274import java.io.IOException;
275import java.io.InputStream;
276import java.io.PrintWriter;
277import java.nio.charset.StandardCharsets;
278import java.security.MessageDigest;
279import java.security.NoSuchAlgorithmException;
280import java.security.PublicKey;
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        UsageStatsManager usageMgr =
7010                (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
7011
7012        int curr = 0;
7013        int total = pkgs.size();
7014        for (PackageParser.Package pkg : pkgs) {
7015            curr++;
7016
7017            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7018                if (DEBUG_DEXOPT) {
7019                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7020                }
7021                continue;
7022            }
7023
7024            if (!causeFirstBoot && usageMgr.isAppInactive(pkg.packageName)) {
7025                if (DEBUG_DEXOPT) {
7026                    Log.i(TAG, "Skipping update of of idle app " + pkg.packageName);
7027                }
7028                continue;
7029            }
7030
7031            if (DEBUG_DEXOPT) {
7032                Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName);
7033            }
7034
7035            if (!isFirstBoot()) {
7036                try {
7037                    ActivityManagerNative.getDefault().showBootMessage(
7038                            mContext.getResources().getString(R.string.android_upgrading_apk,
7039                                    curr, total), true);
7040                } catch (RemoteException e) {
7041                }
7042            }
7043
7044            performDexOpt(pkg.packageName,
7045                    null /* instructionSet */,
7046                    false /* checkProfiles */,
7047                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
7048                    false /* force */);
7049        }
7050    }
7051
7052    @Override
7053    public void notifyPackageUse(String packageName) {
7054        synchronized (mPackages) {
7055            PackageParser.Package p = mPackages.get(packageName);
7056            if (p == null) {
7057                return;
7058            }
7059            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
7060        }
7061    }
7062
7063    // TODO: this is not used nor needed. Delete it.
7064    @Override
7065    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
7066        return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */,
7067                getFullCompilerFilter(), false /* force */);
7068    }
7069
7070    @Override
7071    public boolean performDexOpt(String packageName, String instructionSet,
7072            boolean checkProfiles, int compileReason, boolean force) {
7073        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7074                getCompilerFilterForReason(compileReason), force);
7075    }
7076
7077    @Override
7078    public boolean performDexOptMode(String packageName, String instructionSet,
7079            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7080        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7081                targetCompilerFilter, force);
7082    }
7083
7084    private boolean performDexOptTraced(String packageName, String instructionSet,
7085                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7086        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7087        try {
7088            return performDexOptInternal(packageName, instructionSet, checkProfiles,
7089                    targetCompilerFilter, force);
7090        } finally {
7091            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7092        }
7093    }
7094
7095    private boolean performDexOptInternal(String packageName, String instructionSet,
7096                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7097        PackageParser.Package p;
7098        final String targetInstructionSet;
7099        synchronized (mPackages) {
7100            p = mPackages.get(packageName);
7101            if (p == null) {
7102                return false;
7103            }
7104            mPackageUsage.write(false);
7105
7106            targetInstructionSet = instructionSet != null ? instructionSet :
7107                    getPrimaryInstructionSet(p.applicationInfo);
7108        }
7109        long callingId = Binder.clearCallingIdentity();
7110        try {
7111            synchronized (mInstallLock) {
7112                final String[] instructionSets = new String[] { targetInstructionSet };
7113                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
7114                        checkProfiles, targetCompilerFilter, force);
7115                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
7116            }
7117        } finally {
7118            Binder.restoreCallingIdentity(callingId);
7119        }
7120    }
7121
7122    public ArraySet<String> getOptimizablePackages() {
7123        ArraySet<String> pkgs = new ArraySet<String>();
7124        synchronized (mPackages) {
7125            for (PackageParser.Package p : mPackages.values()) {
7126                if (PackageDexOptimizer.canOptimizePackage(p)) {
7127                    pkgs.add(p.packageName);
7128                }
7129            }
7130        }
7131        return pkgs;
7132    }
7133
7134    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7135            String instructionSets[], boolean checkProfiles, String targetCompilerFilter,
7136            boolean force) {
7137        // Select the dex optimizer based on the force parameter.
7138        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7139        //       allocate an object here.
7140        PackageDexOptimizer pdo = force
7141                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7142                : mPackageDexOptimizer;
7143
7144        // Optimize all dependencies first. Note: we ignore the return value and march on
7145        // on errors.
7146        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7147        if (!deps.isEmpty()) {
7148            for (PackageParser.Package depPackage : deps) {
7149                // TODO: Analyze and investigate if we (should) profile libraries.
7150                // Currently this will do a full compilation of the library by default.
7151                pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */,
7152                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7153            }
7154        }
7155
7156        return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter);
7157    }
7158
7159    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7160        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7161            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7162            Set<String> collectedNames = new HashSet<>();
7163            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7164
7165            retValue.remove(p);
7166
7167            return retValue;
7168        } else {
7169            return Collections.emptyList();
7170        }
7171    }
7172
7173    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7174            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7175        if (!collectedNames.contains(p.packageName)) {
7176            collectedNames.add(p.packageName);
7177            collected.add(p);
7178
7179            if (p.usesLibraries != null) {
7180                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7181            }
7182            if (p.usesOptionalLibraries != null) {
7183                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7184                        collectedNames);
7185            }
7186        }
7187    }
7188
7189    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7190            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7191        for (String libName : libs) {
7192            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7193            if (libPkg != null) {
7194                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7195            }
7196        }
7197    }
7198
7199    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7200        synchronized (mPackages) {
7201            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7202            if (lib != null && lib.apk != null) {
7203                return mPackages.get(lib.apk);
7204            }
7205        }
7206        return null;
7207    }
7208
7209    public void shutdown() {
7210        mPackageUsage.write(true);
7211    }
7212
7213    @Override
7214    public void forceDexOpt(String packageName) {
7215        enforceSystemOrRoot("forceDexOpt");
7216
7217        PackageParser.Package pkg;
7218        synchronized (mPackages) {
7219            pkg = mPackages.get(packageName);
7220            if (pkg == null) {
7221                throw new IllegalArgumentException("Unknown package: " + packageName);
7222            }
7223        }
7224
7225        synchronized (mInstallLock) {
7226            final String[] instructionSets = new String[] {
7227                    getPrimaryInstructionSet(pkg.applicationInfo) };
7228
7229            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7230
7231            // Whoever is calling forceDexOpt wants a fully compiled package.
7232            // Don't use profiles since that may cause compilation to be skipped.
7233            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7234                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7235                    true /* force */);
7236
7237            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7238            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7239                throw new IllegalStateException("Failed to dexopt: " + res);
7240            }
7241        }
7242    }
7243
7244    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7245        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7246            Slog.w(TAG, "Unable to update from " + oldPkg.name
7247                    + " to " + newPkg.packageName
7248                    + ": old package not in system partition");
7249            return false;
7250        } else if (mPackages.get(oldPkg.name) != null) {
7251            Slog.w(TAG, "Unable to update from " + oldPkg.name
7252                    + " to " + newPkg.packageName
7253                    + ": old package still exists");
7254            return false;
7255        }
7256        return true;
7257    }
7258
7259    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
7260        // TODO: triage flags as part of 26466827
7261        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7262
7263        boolean res = true;
7264        final int[] users = sUserManager.getUserIds();
7265        for (int user : users) {
7266            try {
7267                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
7268            } catch (InstallerException e) {
7269                Slog.w(TAG, "Failed to delete data directory", e);
7270                res = false;
7271            }
7272        }
7273        return res;
7274    }
7275
7276    void removeCodePathLI(File codePath) {
7277        if (codePath.isDirectory()) {
7278            try {
7279                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7280            } catch (InstallerException e) {
7281                Slog.w(TAG, "Failed to remove code path", e);
7282            }
7283        } else {
7284            codePath.delete();
7285        }
7286    }
7287
7288    void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) {
7289        try {
7290            mInstaller.destroyAppData(volumeUuid, packageName, userId, flags);
7291        } catch (InstallerException e) {
7292            Slog.w(TAG, "Failed to destroy app data", e);
7293        }
7294    }
7295
7296    void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags,
7297            int appId, String seinfo) {
7298        try {
7299            mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo);
7300        } catch (InstallerException e) {
7301            Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
7302        }
7303    }
7304
7305    private void deleteProfilesLI(String packageName, boolean destroy) {
7306        final PackageParser.Package pkg;
7307        synchronized (mPackages) {
7308            pkg = mPackages.get(packageName);
7309        }
7310        if (pkg == null) {
7311            Slog.w(TAG, "Failed to delete profiles. No package: " + packageName);
7312            return;
7313        }
7314        deleteProfilesLI(pkg, destroy);
7315    }
7316
7317    private void deleteProfilesLI(PackageParser.Package pkg, boolean destroy) {
7318        try {
7319            if (destroy) {
7320                mInstaller.destroyAppProfiles(pkg.packageName);
7321            } else {
7322                mInstaller.clearAppProfiles(pkg.packageName);
7323            }
7324        } catch (InstallerException ex) {
7325            Log.e(TAG, "Could not delete profiles for package " + pkg.packageName);
7326        }
7327    }
7328
7329    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
7330        final PackageParser.Package pkg;
7331        synchronized (mPackages) {
7332            pkg = mPackages.get(packageName);
7333        }
7334        if (pkg == null) {
7335            Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName);
7336            return;
7337        }
7338        deleteCodeCacheDirsLI(pkg);
7339    }
7340
7341    private void deleteCodeCacheDirsLI(PackageParser.Package pkg) {
7342        // TODO: triage flags as part of 26466827
7343        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7344
7345        int[] users = sUserManager.getUserIds();
7346        int res = 0;
7347        for (int user : users) {
7348            // Remove the parent code cache
7349            try {
7350                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user,
7351                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7352            } catch (InstallerException e) {
7353                Slog.w(TAG, "Failed to delete code cache directory", e);
7354            }
7355            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7356            for (int i = 0; i < childCount; i++) {
7357                PackageParser.Package childPkg = pkg.childPackages.get(i);
7358                // Remove the child code cache
7359                try {
7360                    mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName,
7361                            user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7362                } catch (InstallerException e) {
7363                    Slog.w(TAG, "Failed to delete code cache directory", e);
7364                }
7365            }
7366        }
7367    }
7368
7369    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7370            long lastUpdateTime) {
7371        // Set parent install/update time
7372        PackageSetting ps = (PackageSetting) pkg.mExtras;
7373        if (ps != null) {
7374            ps.firstInstallTime = firstInstallTime;
7375            ps.lastUpdateTime = lastUpdateTime;
7376        }
7377        // Set children install/update time
7378        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7379        for (int i = 0; i < childCount; i++) {
7380            PackageParser.Package childPkg = pkg.childPackages.get(i);
7381            ps = (PackageSetting) childPkg.mExtras;
7382            if (ps != null) {
7383                ps.firstInstallTime = firstInstallTime;
7384                ps.lastUpdateTime = lastUpdateTime;
7385            }
7386        }
7387    }
7388
7389    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7390            PackageParser.Package changingLib) {
7391        if (file.path != null) {
7392            usesLibraryFiles.add(file.path);
7393            return;
7394        }
7395        PackageParser.Package p = mPackages.get(file.apk);
7396        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7397            // If we are doing this while in the middle of updating a library apk,
7398            // then we need to make sure to use that new apk for determining the
7399            // dependencies here.  (We haven't yet finished committing the new apk
7400            // to the package manager state.)
7401            if (p == null || p.packageName.equals(changingLib.packageName)) {
7402                p = changingLib;
7403            }
7404        }
7405        if (p != null) {
7406            usesLibraryFiles.addAll(p.getAllCodePaths());
7407        }
7408    }
7409
7410    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7411            PackageParser.Package changingLib) throws PackageManagerException {
7412        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7413            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7414            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7415            for (int i=0; i<N; i++) {
7416                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7417                if (file == null) {
7418                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7419                            "Package " + pkg.packageName + " requires unavailable shared library "
7420                            + pkg.usesLibraries.get(i) + "; failing!");
7421                }
7422                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7423            }
7424            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7425            for (int i=0; i<N; i++) {
7426                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7427                if (file == null) {
7428                    Slog.w(TAG, "Package " + pkg.packageName
7429                            + " desires unavailable shared library "
7430                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7431                } else {
7432                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7433                }
7434            }
7435            N = usesLibraryFiles.size();
7436            if (N > 0) {
7437                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7438            } else {
7439                pkg.usesLibraryFiles = null;
7440            }
7441        }
7442    }
7443
7444    private static boolean hasString(List<String> list, List<String> which) {
7445        if (list == null) {
7446            return false;
7447        }
7448        for (int i=list.size()-1; i>=0; i--) {
7449            for (int j=which.size()-1; j>=0; j--) {
7450                if (which.get(j).equals(list.get(i))) {
7451                    return true;
7452                }
7453            }
7454        }
7455        return false;
7456    }
7457
7458    private void updateAllSharedLibrariesLPw() {
7459        for (PackageParser.Package pkg : mPackages.values()) {
7460            try {
7461                updateSharedLibrariesLPw(pkg, null);
7462            } catch (PackageManagerException e) {
7463                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7464            }
7465        }
7466    }
7467
7468    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7469            PackageParser.Package changingPkg) {
7470        ArrayList<PackageParser.Package> res = null;
7471        for (PackageParser.Package pkg : mPackages.values()) {
7472            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7473                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7474                if (res == null) {
7475                    res = new ArrayList<PackageParser.Package>();
7476                }
7477                res.add(pkg);
7478                try {
7479                    updateSharedLibrariesLPw(pkg, changingPkg);
7480                } catch (PackageManagerException e) {
7481                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7482                }
7483            }
7484        }
7485        return res;
7486    }
7487
7488    /**
7489     * Derive the value of the {@code cpuAbiOverride} based on the provided
7490     * value and an optional stored value from the package settings.
7491     */
7492    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7493        String cpuAbiOverride = null;
7494
7495        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7496            cpuAbiOverride = null;
7497        } else if (abiOverride != null) {
7498            cpuAbiOverride = abiOverride;
7499        } else if (settings != null) {
7500            cpuAbiOverride = settings.cpuAbiOverrideString;
7501        }
7502
7503        return cpuAbiOverride;
7504    }
7505
7506    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
7507            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7508        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7509        // If the package has children and this is the first dive in the function
7510        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7511        // whether all packages (parent and children) would be successfully scanned
7512        // before the actual scan since scanning mutates internal state and we want
7513        // to atomically install the package and its children.
7514        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7515            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7516                scanFlags |= SCAN_CHECK_ONLY;
7517            }
7518        } else {
7519            scanFlags &= ~SCAN_CHECK_ONLY;
7520        }
7521
7522        final PackageParser.Package scannedPkg;
7523        try {
7524            // Scan the parent
7525            scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
7526            // Scan the children
7527            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7528            for (int i = 0; i < childCount; i++) {
7529                PackageParser.Package childPkg = pkg.childPackages.get(i);
7530                scanPackageLI(childPkg, parseFlags,
7531                        scanFlags, currentTime, user);
7532            }
7533        } finally {
7534            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7535        }
7536
7537        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7538            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
7539        }
7540
7541        return scannedPkg;
7542    }
7543
7544    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
7545            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7546        boolean success = false;
7547        try {
7548            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
7549                    currentTime, user);
7550            success = true;
7551            return res;
7552        } finally {
7553            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7554                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
7555            }
7556        }
7557    }
7558
7559    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
7560            int scanFlags, long currentTime, UserHandle user)
7561            throws PackageManagerException {
7562        final File scanFile = new File(pkg.codePath);
7563        if (pkg.applicationInfo.getCodePath() == null ||
7564                pkg.applicationInfo.getResourcePath() == null) {
7565            // Bail out. The resource and code paths haven't been set.
7566            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7567                    "Code and resource paths haven't been set correctly");
7568        }
7569
7570        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7571            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7572        } else {
7573            // Only allow system apps to be flagged as core apps.
7574            pkg.coreApp = false;
7575        }
7576
7577        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7578            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7579        }
7580
7581        if (mCustomResolverComponentName != null &&
7582                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7583            setUpCustomResolverActivity(pkg);
7584        }
7585
7586        if (pkg.packageName.equals("android")) {
7587            synchronized (mPackages) {
7588                if (mAndroidApplication != null) {
7589                    Slog.w(TAG, "*************************************************");
7590                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7591                    Slog.w(TAG, " file=" + scanFile);
7592                    Slog.w(TAG, "*************************************************");
7593                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7594                            "Core android package being redefined.  Skipping.");
7595                }
7596
7597                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7598                    // Set up information for our fall-back user intent resolution activity.
7599                    mPlatformPackage = pkg;
7600                    pkg.mVersionCode = mSdkVersion;
7601                    mAndroidApplication = pkg.applicationInfo;
7602
7603                    if (!mResolverReplaced) {
7604                        mResolveActivity.applicationInfo = mAndroidApplication;
7605                        mResolveActivity.name = ResolverActivity.class.getName();
7606                        mResolveActivity.packageName = mAndroidApplication.packageName;
7607                        mResolveActivity.processName = "system:ui";
7608                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7609                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7610                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7611                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7612                        mResolveActivity.exported = true;
7613                        mResolveActivity.enabled = true;
7614                        mResolveInfo.activityInfo = mResolveActivity;
7615                        mResolveInfo.priority = 0;
7616                        mResolveInfo.preferredOrder = 0;
7617                        mResolveInfo.match = 0;
7618                        mResolveComponentName = new ComponentName(
7619                                mAndroidApplication.packageName, mResolveActivity.name);
7620                    }
7621                }
7622            }
7623        }
7624
7625        if (DEBUG_PACKAGE_SCANNING) {
7626            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7627                Log.d(TAG, "Scanning package " + pkg.packageName);
7628        }
7629
7630        synchronized (mPackages) {
7631            if (mPackages.containsKey(pkg.packageName)
7632                    || mSharedLibraries.containsKey(pkg.packageName)) {
7633                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7634                        "Application package " + pkg.packageName
7635                                + " already installed.  Skipping duplicate.");
7636            }
7637
7638            // If we're only installing presumed-existing packages, require that the
7639            // scanned APK is both already known and at the path previously established
7640            // for it.  Previously unknown packages we pick up normally, but if we have an
7641            // a priori expectation about this package's install presence, enforce it.
7642            // With a singular exception for new system packages. When an OTA contains
7643            // a new system package, we allow the codepath to change from a system location
7644            // to the user-installed location. If we don't allow this change, any newer,
7645            // user-installed version of the application will be ignored.
7646            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7647                if (mExpectingBetter.containsKey(pkg.packageName)) {
7648                    logCriticalInfo(Log.WARN,
7649                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7650                } else {
7651                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7652                    if (known != null) {
7653                        if (DEBUG_PACKAGE_SCANNING) {
7654                            Log.d(TAG, "Examining " + pkg.codePath
7655                                    + " and requiring known paths " + known.codePathString
7656                                    + " & " + known.resourcePathString);
7657                        }
7658                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7659                                || !pkg.applicationInfo.getResourcePath().equals(
7660                                known.resourcePathString)) {
7661                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7662                                    "Application package " + pkg.packageName
7663                                            + " found at " + pkg.applicationInfo.getCodePath()
7664                                            + " but expected at " + known.codePathString
7665                                            + "; ignoring.");
7666                        }
7667                    }
7668                }
7669            }
7670        }
7671
7672        // Initialize package source and resource directories
7673        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7674        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7675
7676        SharedUserSetting suid = null;
7677        PackageSetting pkgSetting = null;
7678
7679        if (!isSystemApp(pkg)) {
7680            // Only system apps can use these features.
7681            pkg.mOriginalPackages = null;
7682            pkg.mRealPackage = null;
7683            pkg.mAdoptPermissions = null;
7684        }
7685
7686        // Getting the package setting may have a side-effect, so if we
7687        // are only checking if scan would succeed, stash a copy of the
7688        // old setting to restore at the end.
7689        PackageSetting nonMutatedPs = null;
7690
7691        // writer
7692        synchronized (mPackages) {
7693            if (pkg.mSharedUserId != null) {
7694                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7695                if (suid == null) {
7696                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7697                            "Creating application package " + pkg.packageName
7698                            + " for shared user failed");
7699                }
7700                if (DEBUG_PACKAGE_SCANNING) {
7701                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7702                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7703                                + "): packages=" + suid.packages);
7704                }
7705            }
7706
7707            // Check if we are renaming from an original package name.
7708            PackageSetting origPackage = null;
7709            String realName = null;
7710            if (pkg.mOriginalPackages != null) {
7711                // This package may need to be renamed to a previously
7712                // installed name.  Let's check on that...
7713                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7714                if (pkg.mOriginalPackages.contains(renamed)) {
7715                    // This package had originally been installed as the
7716                    // original name, and we have already taken care of
7717                    // transitioning to the new one.  Just update the new
7718                    // one to continue using the old name.
7719                    realName = pkg.mRealPackage;
7720                    if (!pkg.packageName.equals(renamed)) {
7721                        // Callers into this function may have already taken
7722                        // care of renaming the package; only do it here if
7723                        // it is not already done.
7724                        pkg.setPackageName(renamed);
7725                    }
7726
7727                } else {
7728                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7729                        if ((origPackage = mSettings.peekPackageLPr(
7730                                pkg.mOriginalPackages.get(i))) != null) {
7731                            // We do have the package already installed under its
7732                            // original name...  should we use it?
7733                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7734                                // New package is not compatible with original.
7735                                origPackage = null;
7736                                continue;
7737                            } else if (origPackage.sharedUser != null) {
7738                                // Make sure uid is compatible between packages.
7739                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7740                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7741                                            + " to " + pkg.packageName + ": old uid "
7742                                            + origPackage.sharedUser.name
7743                                            + " differs from " + pkg.mSharedUserId);
7744                                    origPackage = null;
7745                                    continue;
7746                                }
7747                            } else {
7748                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7749                                        + pkg.packageName + " to old name " + origPackage.name);
7750                            }
7751                            break;
7752                        }
7753                    }
7754                }
7755            }
7756
7757            if (mTransferedPackages.contains(pkg.packageName)) {
7758                Slog.w(TAG, "Package " + pkg.packageName
7759                        + " was transferred to another, but its .apk remains");
7760            }
7761
7762            // See comments in nonMutatedPs declaration
7763            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7764                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
7765                if (foundPs != null) {
7766                    nonMutatedPs = new PackageSetting(foundPs);
7767                }
7768            }
7769
7770            // Just create the setting, don't add it yet. For already existing packages
7771            // the PkgSetting exists already and doesn't have to be created.
7772            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7773                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7774                    pkg.applicationInfo.primaryCpuAbi,
7775                    pkg.applicationInfo.secondaryCpuAbi,
7776                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7777                    user, false);
7778            if (pkgSetting == null) {
7779                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7780                        "Creating application package " + pkg.packageName + " failed");
7781            }
7782
7783            if (pkgSetting.origPackage != null) {
7784                // If we are first transitioning from an original package,
7785                // fix up the new package's name now.  We need to do this after
7786                // looking up the package under its new name, so getPackageLP
7787                // can take care of fiddling things correctly.
7788                pkg.setPackageName(origPackage.name);
7789
7790                // File a report about this.
7791                String msg = "New package " + pkgSetting.realName
7792                        + " renamed to replace old package " + pkgSetting.name;
7793                reportSettingsProblem(Log.WARN, msg);
7794
7795                // Make a note of it.
7796                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7797                    mTransferedPackages.add(origPackage.name);
7798                }
7799
7800                // No longer need to retain this.
7801                pkgSetting.origPackage = null;
7802            }
7803
7804            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
7805                // Make a note of it.
7806                mTransferedPackages.add(pkg.packageName);
7807            }
7808
7809            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7810                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7811            }
7812
7813            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7814                // Check all shared libraries and map to their actual file path.
7815                // We only do this here for apps not on a system dir, because those
7816                // are the only ones that can fail an install due to this.  We
7817                // will take care of the system apps by updating all of their
7818                // library paths after the scan is done.
7819                updateSharedLibrariesLPw(pkg, null);
7820            }
7821
7822            if (mFoundPolicyFile) {
7823                SELinuxMMAC.assignSeinfoValue(pkg);
7824            }
7825
7826            pkg.applicationInfo.uid = pkgSetting.appId;
7827            pkg.mExtras = pkgSetting;
7828            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7829                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7830                    // We just determined the app is signed correctly, so bring
7831                    // over the latest parsed certs.
7832                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7833                } else {
7834                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7835                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7836                                "Package " + pkg.packageName + " upgrade keys do not match the "
7837                                + "previously installed version");
7838                    } else {
7839                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7840                        String msg = "System package " + pkg.packageName
7841                            + " signature changed; retaining data.";
7842                        reportSettingsProblem(Log.WARN, msg);
7843                    }
7844                }
7845            } else {
7846                try {
7847                    verifySignaturesLP(pkgSetting, pkg);
7848                    // We just determined the app is signed correctly, so bring
7849                    // over the latest parsed certs.
7850                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7851                } catch (PackageManagerException e) {
7852                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7853                        throw e;
7854                    }
7855                    // The signature has changed, but this package is in the system
7856                    // image...  let's recover!
7857                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7858                    // However...  if this package is part of a shared user, but it
7859                    // doesn't match the signature of the shared user, let's fail.
7860                    // What this means is that you can't change the signatures
7861                    // associated with an overall shared user, which doesn't seem all
7862                    // that unreasonable.
7863                    if (pkgSetting.sharedUser != null) {
7864                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7865                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7866                            throw new PackageManagerException(
7867                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7868                                            "Signature mismatch for shared user: "
7869                                            + pkgSetting.sharedUser);
7870                        }
7871                    }
7872                    // File a report about this.
7873                    String msg = "System package " + pkg.packageName
7874                        + " signature changed; retaining data.";
7875                    reportSettingsProblem(Log.WARN, msg);
7876                }
7877            }
7878            // Verify that this new package doesn't have any content providers
7879            // that conflict with existing packages.  Only do this if the
7880            // package isn't already installed, since we don't want to break
7881            // things that are installed.
7882            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7883                final int N = pkg.providers.size();
7884                int i;
7885                for (i=0; i<N; i++) {
7886                    PackageParser.Provider p = pkg.providers.get(i);
7887                    if (p.info.authority != null) {
7888                        String names[] = p.info.authority.split(";");
7889                        for (int j = 0; j < names.length; j++) {
7890                            if (mProvidersByAuthority.containsKey(names[j])) {
7891                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7892                                final String otherPackageName =
7893                                        ((other != null && other.getComponentName() != null) ?
7894                                                other.getComponentName().getPackageName() : "?");
7895                                throw new PackageManagerException(
7896                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7897                                                "Can't install because provider name " + names[j]
7898                                                + " (in package " + pkg.applicationInfo.packageName
7899                                                + ") is already used by " + otherPackageName);
7900                            }
7901                        }
7902                    }
7903                }
7904            }
7905
7906            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
7907                // This package wants to adopt ownership of permissions from
7908                // another package.
7909                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7910                    final String origName = pkg.mAdoptPermissions.get(i);
7911                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7912                    if (orig != null) {
7913                        if (verifyPackageUpdateLPr(orig, pkg)) {
7914                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7915                                    + pkg.packageName);
7916                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7917                        }
7918                    }
7919                }
7920            }
7921        }
7922
7923        final String pkgName = pkg.packageName;
7924
7925        final long scanFileTime = scanFile.lastModified();
7926        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7927        pkg.applicationInfo.processName = fixProcessName(
7928                pkg.applicationInfo.packageName,
7929                pkg.applicationInfo.processName,
7930                pkg.applicationInfo.uid);
7931
7932        if (pkg != mPlatformPackage) {
7933            // Get all of our default paths setup
7934            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7935        }
7936
7937        final String path = scanFile.getPath();
7938        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7939
7940        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7941            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7942
7943            // Some system apps still use directory structure for native libraries
7944            // in which case we might end up not detecting abi solely based on apk
7945            // structure. Try to detect abi based on directory structure.
7946            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7947                    pkg.applicationInfo.primaryCpuAbi == null) {
7948                setBundledAppAbisAndRoots(pkg, pkgSetting);
7949                setNativeLibraryPaths(pkg);
7950            }
7951
7952        } else {
7953            if ((scanFlags & SCAN_MOVE) != 0) {
7954                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7955                // but we already have this packages package info in the PackageSetting. We just
7956                // use that and derive the native library path based on the new codepath.
7957                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7958                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7959            }
7960
7961            // Set native library paths again. For moves, the path will be updated based on the
7962            // ABIs we've determined above. For non-moves, the path will be updated based on the
7963            // ABIs we determined during compilation, but the path will depend on the final
7964            // package path (after the rename away from the stage path).
7965            setNativeLibraryPaths(pkg);
7966        }
7967
7968        // This is a special case for the "system" package, where the ABI is
7969        // dictated by the zygote configuration (and init.rc). We should keep track
7970        // of this ABI so that we can deal with "normal" applications that run under
7971        // the same UID correctly.
7972        if (mPlatformPackage == pkg) {
7973            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7974                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7975        }
7976
7977        // If there's a mismatch between the abi-override in the package setting
7978        // and the abiOverride specified for the install. Warn about this because we
7979        // would've already compiled the app without taking the package setting into
7980        // account.
7981        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7982            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7983                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7984                        " for package " + pkg.packageName);
7985            }
7986        }
7987
7988        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7989        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7990        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7991
7992        // Copy the derived override back to the parsed package, so that we can
7993        // update the package settings accordingly.
7994        pkg.cpuAbiOverride = cpuAbiOverride;
7995
7996        if (DEBUG_ABI_SELECTION) {
7997            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7998                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7999                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8000        }
8001
8002        // Push the derived path down into PackageSettings so we know what to
8003        // clean up at uninstall time.
8004        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8005
8006        if (DEBUG_ABI_SELECTION) {
8007            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8008                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8009                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8010        }
8011
8012        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8013            // We don't do this here during boot because we can do it all
8014            // at once after scanning all existing packages.
8015            //
8016            // We also do this *before* we perform dexopt on this package, so that
8017            // we can avoid redundant dexopts, and also to make sure we've got the
8018            // code and package path correct.
8019            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8020                    pkg, true /* boot complete */);
8021        }
8022
8023        if (mFactoryTest && pkg.requestedPermissions.contains(
8024                android.Manifest.permission.FACTORY_TEST)) {
8025            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8026        }
8027
8028        ArrayList<PackageParser.Package> clientLibPkgs = null;
8029
8030        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8031            if (nonMutatedPs != null) {
8032                synchronized (mPackages) {
8033                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8034                }
8035            }
8036            return pkg;
8037        }
8038
8039        // Only privileged apps and updated privileged apps can add child packages.
8040        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8041            if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) {
8042                throw new PackageManagerException("Only privileged apps and updated "
8043                        + "privileged apps can add child packages. Ignoring package "
8044                        + pkg.packageName);
8045            }
8046            final int childCount = pkg.childPackages.size();
8047            for (int i = 0; i < childCount; i++) {
8048                PackageParser.Package childPkg = pkg.childPackages.get(i);
8049                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8050                        childPkg.packageName)) {
8051                    throw new PackageManagerException("Cannot override a child package of "
8052                            + "another disabled system app. Ignoring package " + pkg.packageName);
8053                }
8054            }
8055        }
8056
8057        // writer
8058        synchronized (mPackages) {
8059            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8060                // Only system apps can add new shared libraries.
8061                if (pkg.libraryNames != null) {
8062                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8063                        String name = pkg.libraryNames.get(i);
8064                        boolean allowed = false;
8065                        if (pkg.isUpdatedSystemApp()) {
8066                            // New library entries can only be added through the
8067                            // system image.  This is important to get rid of a lot
8068                            // of nasty edge cases: for example if we allowed a non-
8069                            // system update of the app to add a library, then uninstalling
8070                            // the update would make the library go away, and assumptions
8071                            // we made such as through app install filtering would now
8072                            // have allowed apps on the device which aren't compatible
8073                            // with it.  Better to just have the restriction here, be
8074                            // conservative, and create many fewer cases that can negatively
8075                            // impact the user experience.
8076                            final PackageSetting sysPs = mSettings
8077                                    .getDisabledSystemPkgLPr(pkg.packageName);
8078                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8079                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8080                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8081                                        allowed = true;
8082                                        break;
8083                                    }
8084                                }
8085                            }
8086                        } else {
8087                            allowed = true;
8088                        }
8089                        if (allowed) {
8090                            if (!mSharedLibraries.containsKey(name)) {
8091                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8092                            } else if (!name.equals(pkg.packageName)) {
8093                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8094                                        + name + " already exists; skipping");
8095                            }
8096                        } else {
8097                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8098                                    + name + " that is not declared on system image; skipping");
8099                        }
8100                    }
8101                    if ((scanFlags & SCAN_BOOTING) == 0) {
8102                        // If we are not booting, we need to update any applications
8103                        // that are clients of our shared library.  If we are booting,
8104                        // this will all be done once the scan is complete.
8105                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8106                    }
8107                }
8108            }
8109        }
8110
8111        // Request the ActivityManager to kill the process(only for existing packages)
8112        // so that we do not end up in a confused state while the user is still using the older
8113        // version of the application while the new one gets installed.
8114        final boolean isReplacing = (scanFlags & SCAN_REPLACING) != 0;
8115        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
8116        if (killApp) {
8117            if (isReplacing) {
8118                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
8119
8120                killApplication(pkg.applicationInfo.packageName,
8121                            pkg.applicationInfo.uid, "replace pkg");
8122
8123                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8124            }
8125        }
8126
8127        // Also need to kill any apps that are dependent on the library.
8128        if (clientLibPkgs != null) {
8129            for (int i=0; i<clientLibPkgs.size(); i++) {
8130                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8131                killApplication(clientPkg.applicationInfo.packageName,
8132                        clientPkg.applicationInfo.uid, "update lib");
8133            }
8134        }
8135
8136        // Make sure we're not adding any bogus keyset info
8137        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8138        ksms.assertScannedPackageValid(pkg);
8139
8140        // writer
8141        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8142
8143        boolean createIdmapFailed = false;
8144        synchronized (mPackages) {
8145            // We don't expect installation to fail beyond this point
8146
8147            // Add the new setting to mSettings
8148            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8149            // Add the new setting to mPackages
8150            mPackages.put(pkg.applicationInfo.packageName, pkg);
8151            // Make sure we don't accidentally delete its data.
8152            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8153            while (iter.hasNext()) {
8154                PackageCleanItem item = iter.next();
8155                if (pkgName.equals(item.packageName)) {
8156                    iter.remove();
8157                }
8158            }
8159
8160            // Take care of first install / last update times.
8161            if (currentTime != 0) {
8162                if (pkgSetting.firstInstallTime == 0) {
8163                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8164                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8165                    pkgSetting.lastUpdateTime = currentTime;
8166                }
8167            } else if (pkgSetting.firstInstallTime == 0) {
8168                // We need *something*.  Take time time stamp of the file.
8169                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8170            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8171                if (scanFileTime != pkgSetting.timeStamp) {
8172                    // A package on the system image has changed; consider this
8173                    // to be an update.
8174                    pkgSetting.lastUpdateTime = scanFileTime;
8175                }
8176            }
8177
8178            // Add the package's KeySets to the global KeySetManagerService
8179            ksms.addScannedPackageLPw(pkg);
8180
8181            int N = pkg.providers.size();
8182            StringBuilder r = null;
8183            int i;
8184            for (i=0; i<N; i++) {
8185                PackageParser.Provider p = pkg.providers.get(i);
8186                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8187                        p.info.processName, pkg.applicationInfo.uid);
8188                mProviders.addProvider(p);
8189                p.syncable = p.info.isSyncable;
8190                if (p.info.authority != null) {
8191                    String names[] = p.info.authority.split(";");
8192                    p.info.authority = null;
8193                    for (int j = 0; j < names.length; j++) {
8194                        if (j == 1 && p.syncable) {
8195                            // We only want the first authority for a provider to possibly be
8196                            // syncable, so if we already added this provider using a different
8197                            // authority clear the syncable flag. We copy the provider before
8198                            // changing it because the mProviders object contains a reference
8199                            // to a provider that we don't want to change.
8200                            // Only do this for the second authority since the resulting provider
8201                            // object can be the same for all future authorities for this provider.
8202                            p = new PackageParser.Provider(p);
8203                            p.syncable = false;
8204                        }
8205                        if (!mProvidersByAuthority.containsKey(names[j])) {
8206                            mProvidersByAuthority.put(names[j], p);
8207                            if (p.info.authority == null) {
8208                                p.info.authority = names[j];
8209                            } else {
8210                                p.info.authority = p.info.authority + ";" + names[j];
8211                            }
8212                            if (DEBUG_PACKAGE_SCANNING) {
8213                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
8214                                    Log.d(TAG, "Registered content provider: " + names[j]
8215                                            + ", className = " + p.info.name + ", isSyncable = "
8216                                            + p.info.isSyncable);
8217                            }
8218                        } else {
8219                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8220                            Slog.w(TAG, "Skipping provider name " + names[j] +
8221                                    " (in package " + pkg.applicationInfo.packageName +
8222                                    "): name already used by "
8223                                    + ((other != null && other.getComponentName() != null)
8224                                            ? other.getComponentName().getPackageName() : "?"));
8225                        }
8226                    }
8227                }
8228                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8229                    if (r == null) {
8230                        r = new StringBuilder(256);
8231                    } else {
8232                        r.append(' ');
8233                    }
8234                    r.append(p.info.name);
8235                }
8236            }
8237            if (r != null) {
8238                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8239            }
8240
8241            N = pkg.services.size();
8242            r = null;
8243            for (i=0; i<N; i++) {
8244                PackageParser.Service s = pkg.services.get(i);
8245                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8246                        s.info.processName, pkg.applicationInfo.uid);
8247                mServices.addService(s);
8248                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8249                    if (r == null) {
8250                        r = new StringBuilder(256);
8251                    } else {
8252                        r.append(' ');
8253                    }
8254                    r.append(s.info.name);
8255                }
8256            }
8257            if (r != null) {
8258                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8259            }
8260
8261            N = pkg.receivers.size();
8262            r = null;
8263            for (i=0; i<N; i++) {
8264                PackageParser.Activity a = pkg.receivers.get(i);
8265                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8266                        a.info.processName, pkg.applicationInfo.uid);
8267                mReceivers.addActivity(a, "receiver");
8268                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8269                    if (r == null) {
8270                        r = new StringBuilder(256);
8271                    } else {
8272                        r.append(' ');
8273                    }
8274                    r.append(a.info.name);
8275                }
8276            }
8277            if (r != null) {
8278                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8279            }
8280
8281            N = pkg.activities.size();
8282            r = null;
8283            for (i=0; i<N; i++) {
8284                PackageParser.Activity a = pkg.activities.get(i);
8285                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8286                        a.info.processName, pkg.applicationInfo.uid);
8287                mActivities.addActivity(a, "activity");
8288                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8289                    if (r == null) {
8290                        r = new StringBuilder(256);
8291                    } else {
8292                        r.append(' ');
8293                    }
8294                    r.append(a.info.name);
8295                }
8296            }
8297            if (r != null) {
8298                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8299            }
8300
8301            N = pkg.permissionGroups.size();
8302            r = null;
8303            for (i=0; i<N; i++) {
8304                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8305                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8306                if (cur == null) {
8307                    mPermissionGroups.put(pg.info.name, pg);
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(pg.info.name);
8315                    }
8316                } else {
8317                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8318                            + pg.info.packageName + " ignored: original from "
8319                            + cur.info.packageName);
8320                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8321                        if (r == null) {
8322                            r = new StringBuilder(256);
8323                        } else {
8324                            r.append(' ');
8325                        }
8326                        r.append("DUP:");
8327                        r.append(pg.info.name);
8328                    }
8329                }
8330            }
8331            if (r != null) {
8332                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8333            }
8334
8335            N = pkg.permissions.size();
8336            r = null;
8337            for (i=0; i<N; i++) {
8338                PackageParser.Permission p = pkg.permissions.get(i);
8339
8340                // Assume by default that we did not install this permission into the system.
8341                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8342
8343                // Now that permission groups have a special meaning, we ignore permission
8344                // groups for legacy apps to prevent unexpected behavior. In particular,
8345                // permissions for one app being granted to someone just becase they happen
8346                // to be in a group defined by another app (before this had no implications).
8347                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8348                    p.group = mPermissionGroups.get(p.info.group);
8349                    // Warn for a permission in an unknown group.
8350                    if (p.info.group != null && p.group == null) {
8351                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8352                                + p.info.packageName + " in an unknown group " + p.info.group);
8353                    }
8354                }
8355
8356                ArrayMap<String, BasePermission> permissionMap =
8357                        p.tree ? mSettings.mPermissionTrees
8358                                : mSettings.mPermissions;
8359                BasePermission bp = permissionMap.get(p.info.name);
8360
8361                // Allow system apps to redefine non-system permissions
8362                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8363                    final boolean currentOwnerIsSystem = (bp.perm != null
8364                            && isSystemApp(bp.perm.owner));
8365                    if (isSystemApp(p.owner)) {
8366                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8367                            // It's a built-in permission and no owner, take ownership now
8368                            bp.packageSetting = pkgSetting;
8369                            bp.perm = p;
8370                            bp.uid = pkg.applicationInfo.uid;
8371                            bp.sourcePackage = p.info.packageName;
8372                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8373                        } else if (!currentOwnerIsSystem) {
8374                            String msg = "New decl " + p.owner + " of permission  "
8375                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8376                            reportSettingsProblem(Log.WARN, msg);
8377                            bp = null;
8378                        }
8379                    }
8380                }
8381
8382                if (bp == null) {
8383                    bp = new BasePermission(p.info.name, p.info.packageName,
8384                            BasePermission.TYPE_NORMAL);
8385                    permissionMap.put(p.info.name, bp);
8386                }
8387
8388                if (bp.perm == null) {
8389                    if (bp.sourcePackage == null
8390                            || bp.sourcePackage.equals(p.info.packageName)) {
8391                        BasePermission tree = findPermissionTreeLP(p.info.name);
8392                        if (tree == null
8393                                || tree.sourcePackage.equals(p.info.packageName)) {
8394                            bp.packageSetting = pkgSetting;
8395                            bp.perm = p;
8396                            bp.uid = pkg.applicationInfo.uid;
8397                            bp.sourcePackage = p.info.packageName;
8398                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8399                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8400                                if (r == null) {
8401                                    r = new StringBuilder(256);
8402                                } else {
8403                                    r.append(' ');
8404                                }
8405                                r.append(p.info.name);
8406                            }
8407                        } else {
8408                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8409                                    + p.info.packageName + " ignored: base tree "
8410                                    + tree.name + " is from package "
8411                                    + tree.sourcePackage);
8412                        }
8413                    } else {
8414                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8415                                + p.info.packageName + " ignored: original from "
8416                                + bp.sourcePackage);
8417                    }
8418                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8419                    if (r == null) {
8420                        r = new StringBuilder(256);
8421                    } else {
8422                        r.append(' ');
8423                    }
8424                    r.append("DUP:");
8425                    r.append(p.info.name);
8426                }
8427                if (bp.perm == p) {
8428                    bp.protectionLevel = p.info.protectionLevel;
8429                }
8430            }
8431
8432            if (r != null) {
8433                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8434            }
8435
8436            N = pkg.instrumentation.size();
8437            r = null;
8438            for (i=0; i<N; i++) {
8439                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8440                a.info.packageName = pkg.applicationInfo.packageName;
8441                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8442                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8443                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8444                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8445                a.info.dataDir = pkg.applicationInfo.dataDir;
8446                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8447                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8448
8449                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8450                // need other information about the application, like the ABI and what not ?
8451                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8452                mInstrumentation.put(a.getComponentName(), a);
8453                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8454                    if (r == null) {
8455                        r = new StringBuilder(256);
8456                    } else {
8457                        r.append(' ');
8458                    }
8459                    r.append(a.info.name);
8460                }
8461            }
8462            if (r != null) {
8463                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8464            }
8465
8466            if (pkg.protectedBroadcasts != null) {
8467                N = pkg.protectedBroadcasts.size();
8468                for (i=0; i<N; i++) {
8469                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8470                }
8471            }
8472
8473            pkgSetting.setTimeStamp(scanFileTime);
8474
8475            // Create idmap files for pairs of (packages, overlay packages).
8476            // Note: "android", ie framework-res.apk, is handled by native layers.
8477            if (pkg.mOverlayTarget != null) {
8478                // This is an overlay package.
8479                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8480                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8481                        mOverlays.put(pkg.mOverlayTarget,
8482                                new ArrayMap<String, PackageParser.Package>());
8483                    }
8484                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8485                    map.put(pkg.packageName, pkg);
8486                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8487                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8488                        createIdmapFailed = true;
8489                    }
8490                }
8491            } else if (mOverlays.containsKey(pkg.packageName) &&
8492                    !pkg.packageName.equals("android")) {
8493                // This is a regular package, with one or more known overlay packages.
8494                createIdmapsForPackageLI(pkg);
8495            }
8496        }
8497
8498        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8499
8500        if (createIdmapFailed) {
8501            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8502                    "scanPackageLI failed to createIdmap");
8503        }
8504        return pkg;
8505    }
8506
8507    /**
8508     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8509     * is derived purely on the basis of the contents of {@code scanFile} and
8510     * {@code cpuAbiOverride}.
8511     *
8512     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8513     */
8514    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8515                                 String cpuAbiOverride, boolean extractLibs)
8516            throws PackageManagerException {
8517        // TODO: We can probably be smarter about this stuff. For installed apps,
8518        // we can calculate this information at install time once and for all. For
8519        // system apps, we can probably assume that this information doesn't change
8520        // after the first boot scan. As things stand, we do lots of unnecessary work.
8521
8522        // Give ourselves some initial paths; we'll come back for another
8523        // pass once we've determined ABI below.
8524        setNativeLibraryPaths(pkg);
8525
8526        // We would never need to extract libs for forward-locked and external packages,
8527        // since the container service will do it for us. We shouldn't attempt to
8528        // extract libs from system app when it was not updated.
8529        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8530                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8531            extractLibs = false;
8532        }
8533
8534        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8535        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8536
8537        NativeLibraryHelper.Handle handle = null;
8538        try {
8539            handle = NativeLibraryHelper.Handle.create(pkg);
8540            // TODO(multiArch): This can be null for apps that didn't go through the
8541            // usual installation process. We can calculate it again, like we
8542            // do during install time.
8543            //
8544            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8545            // unnecessary.
8546            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8547
8548            // Null out the abis so that they can be recalculated.
8549            pkg.applicationInfo.primaryCpuAbi = null;
8550            pkg.applicationInfo.secondaryCpuAbi = null;
8551            if (isMultiArch(pkg.applicationInfo)) {
8552                // Warn if we've set an abiOverride for multi-lib packages..
8553                // By definition, we need to copy both 32 and 64 bit libraries for
8554                // such packages.
8555                if (pkg.cpuAbiOverride != null
8556                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8557                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8558                }
8559
8560                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8561                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8562                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8563                    if (extractLibs) {
8564                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8565                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8566                                useIsaSpecificSubdirs);
8567                    } else {
8568                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8569                    }
8570                }
8571
8572                maybeThrowExceptionForMultiArchCopy(
8573                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8574
8575                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8576                    if (extractLibs) {
8577                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8578                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8579                                useIsaSpecificSubdirs);
8580                    } else {
8581                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8582                    }
8583                }
8584
8585                maybeThrowExceptionForMultiArchCopy(
8586                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8587
8588                if (abi64 >= 0) {
8589                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8590                }
8591
8592                if (abi32 >= 0) {
8593                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8594                    if (abi64 >= 0) {
8595                        if (pkg.use32bitAbi) {
8596                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8597                            pkg.applicationInfo.primaryCpuAbi = abi;
8598                        } else {
8599                            pkg.applicationInfo.secondaryCpuAbi = abi;
8600                        }
8601                    } else {
8602                        pkg.applicationInfo.primaryCpuAbi = abi;
8603                    }
8604                }
8605
8606            } else {
8607                String[] abiList = (cpuAbiOverride != null) ?
8608                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8609
8610                // Enable gross and lame hacks for apps that are built with old
8611                // SDK tools. We must scan their APKs for renderscript bitcode and
8612                // not launch them if it's present. Don't bother checking on devices
8613                // that don't have 64 bit support.
8614                boolean needsRenderScriptOverride = false;
8615                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8616                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8617                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8618                    needsRenderScriptOverride = true;
8619                }
8620
8621                final int copyRet;
8622                if (extractLibs) {
8623                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8624                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8625                } else {
8626                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8627                }
8628
8629                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8630                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8631                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8632                }
8633
8634                if (copyRet >= 0) {
8635                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8636                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8637                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8638                } else if (needsRenderScriptOverride) {
8639                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8640                }
8641            }
8642        } catch (IOException ioe) {
8643            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8644        } finally {
8645            IoUtils.closeQuietly(handle);
8646        }
8647
8648        // Now that we've calculated the ABIs and determined if it's an internal app,
8649        // we will go ahead and populate the nativeLibraryPath.
8650        setNativeLibraryPaths(pkg);
8651    }
8652
8653    /**
8654     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8655     * i.e, so that all packages can be run inside a single process if required.
8656     *
8657     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8658     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8659     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8660     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8661     * updating a package that belongs to a shared user.
8662     *
8663     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8664     * adds unnecessary complexity.
8665     */
8666    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8667            PackageParser.Package scannedPackage, boolean bootComplete) {
8668        String requiredInstructionSet = null;
8669        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8670            requiredInstructionSet = VMRuntime.getInstructionSet(
8671                     scannedPackage.applicationInfo.primaryCpuAbi);
8672        }
8673
8674        PackageSetting requirer = null;
8675        for (PackageSetting ps : packagesForUser) {
8676            // If packagesForUser contains scannedPackage, we skip it. This will happen
8677            // when scannedPackage is an update of an existing package. Without this check,
8678            // we will never be able to change the ABI of any package belonging to a shared
8679            // user, even if it's compatible with other packages.
8680            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8681                if (ps.primaryCpuAbiString == null) {
8682                    continue;
8683                }
8684
8685                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8686                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8687                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8688                    // this but there's not much we can do.
8689                    String errorMessage = "Instruction set mismatch, "
8690                            + ((requirer == null) ? "[caller]" : requirer)
8691                            + " requires " + requiredInstructionSet + " whereas " + ps
8692                            + " requires " + instructionSet;
8693                    Slog.w(TAG, errorMessage);
8694                }
8695
8696                if (requiredInstructionSet == null) {
8697                    requiredInstructionSet = instructionSet;
8698                    requirer = ps;
8699                }
8700            }
8701        }
8702
8703        if (requiredInstructionSet != null) {
8704            String adjustedAbi;
8705            if (requirer != null) {
8706                // requirer != null implies that either scannedPackage was null or that scannedPackage
8707                // did not require an ABI, in which case we have to adjust scannedPackage to match
8708                // the ABI of the set (which is the same as requirer's ABI)
8709                adjustedAbi = requirer.primaryCpuAbiString;
8710                if (scannedPackage != null) {
8711                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8712                }
8713            } else {
8714                // requirer == null implies that we're updating all ABIs in the set to
8715                // match scannedPackage.
8716                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8717            }
8718
8719            for (PackageSetting ps : packagesForUser) {
8720                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8721                    if (ps.primaryCpuAbiString != null) {
8722                        continue;
8723                    }
8724
8725                    ps.primaryCpuAbiString = adjustedAbi;
8726                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8727                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8728                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8729                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8730                                + " (requirer="
8731                                + (requirer == null ? "null" : requirer.pkg.packageName)
8732                                + ", scannedPackage="
8733                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8734                                + ")");
8735                        try {
8736                            mInstaller.rmdex(ps.codePathString,
8737                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8738                        } catch (InstallerException ignored) {
8739                        }
8740                    }
8741                }
8742            }
8743        }
8744    }
8745
8746    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8747        synchronized (mPackages) {
8748            mResolverReplaced = true;
8749            // Set up information for custom user intent resolution activity.
8750            mResolveActivity.applicationInfo = pkg.applicationInfo;
8751            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8752            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8753            mResolveActivity.processName = pkg.applicationInfo.packageName;
8754            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8755            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8756                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8757            mResolveActivity.theme = 0;
8758            mResolveActivity.exported = true;
8759            mResolveActivity.enabled = true;
8760            mResolveInfo.activityInfo = mResolveActivity;
8761            mResolveInfo.priority = 0;
8762            mResolveInfo.preferredOrder = 0;
8763            mResolveInfo.match = 0;
8764            mResolveComponentName = mCustomResolverComponentName;
8765            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8766                    mResolveComponentName);
8767        }
8768    }
8769
8770    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8771        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8772
8773        // Set up information for ephemeral installer activity
8774        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8775        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8776        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8777        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8778        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8779        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8780                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8781        mEphemeralInstallerActivity.theme = 0;
8782        mEphemeralInstallerActivity.exported = true;
8783        mEphemeralInstallerActivity.enabled = true;
8784        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8785        mEphemeralInstallerInfo.priority = 0;
8786        mEphemeralInstallerInfo.preferredOrder = 0;
8787        mEphemeralInstallerInfo.match = 0;
8788
8789        if (DEBUG_EPHEMERAL) {
8790            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8791        }
8792    }
8793
8794    private static String calculateBundledApkRoot(final String codePathString) {
8795        final File codePath = new File(codePathString);
8796        final File codeRoot;
8797        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8798            codeRoot = Environment.getRootDirectory();
8799        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8800            codeRoot = Environment.getOemDirectory();
8801        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8802            codeRoot = Environment.getVendorDirectory();
8803        } else {
8804            // Unrecognized code path; take its top real segment as the apk root:
8805            // e.g. /something/app/blah.apk => /something
8806            try {
8807                File f = codePath.getCanonicalFile();
8808                File parent = f.getParentFile();    // non-null because codePath is a file
8809                File tmp;
8810                while ((tmp = parent.getParentFile()) != null) {
8811                    f = parent;
8812                    parent = tmp;
8813                }
8814                codeRoot = f;
8815                Slog.w(TAG, "Unrecognized code path "
8816                        + codePath + " - using " + codeRoot);
8817            } catch (IOException e) {
8818                // Can't canonicalize the code path -- shenanigans?
8819                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8820                return Environment.getRootDirectory().getPath();
8821            }
8822        }
8823        return codeRoot.getPath();
8824    }
8825
8826    /**
8827     * Derive and set the location of native libraries for the given package,
8828     * which varies depending on where and how the package was installed.
8829     */
8830    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8831        final ApplicationInfo info = pkg.applicationInfo;
8832        final String codePath = pkg.codePath;
8833        final File codeFile = new File(codePath);
8834        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8835        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8836
8837        info.nativeLibraryRootDir = null;
8838        info.nativeLibraryRootRequiresIsa = false;
8839        info.nativeLibraryDir = null;
8840        info.secondaryNativeLibraryDir = null;
8841
8842        if (isApkFile(codeFile)) {
8843            // Monolithic install
8844            if (bundledApp) {
8845                // If "/system/lib64/apkname" exists, assume that is the per-package
8846                // native library directory to use; otherwise use "/system/lib/apkname".
8847                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8848                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8849                        getPrimaryInstructionSet(info));
8850
8851                // This is a bundled system app so choose the path based on the ABI.
8852                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8853                // is just the default path.
8854                final String apkName = deriveCodePathName(codePath);
8855                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8856                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8857                        apkName).getAbsolutePath();
8858
8859                if (info.secondaryCpuAbi != null) {
8860                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8861                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8862                            secondaryLibDir, apkName).getAbsolutePath();
8863                }
8864            } else if (asecApp) {
8865                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8866                        .getAbsolutePath();
8867            } else {
8868                final String apkName = deriveCodePathName(codePath);
8869                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8870                        .getAbsolutePath();
8871            }
8872
8873            info.nativeLibraryRootRequiresIsa = false;
8874            info.nativeLibraryDir = info.nativeLibraryRootDir;
8875        } else {
8876            // Cluster install
8877            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8878            info.nativeLibraryRootRequiresIsa = true;
8879
8880            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8881                    getPrimaryInstructionSet(info)).getAbsolutePath();
8882
8883            if (info.secondaryCpuAbi != null) {
8884                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8885                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8886            }
8887        }
8888    }
8889
8890    /**
8891     * Calculate the abis and roots for a bundled app. These can uniquely
8892     * be determined from the contents of the system partition, i.e whether
8893     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8894     * of this information, and instead assume that the system was built
8895     * sensibly.
8896     */
8897    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8898                                           PackageSetting pkgSetting) {
8899        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8900
8901        // If "/system/lib64/apkname" exists, assume that is the per-package
8902        // native library directory to use; otherwise use "/system/lib/apkname".
8903        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8904        setBundledAppAbi(pkg, apkRoot, apkName);
8905        // pkgSetting might be null during rescan following uninstall of updates
8906        // to a bundled app, so accommodate that possibility.  The settings in
8907        // that case will be established later from the parsed package.
8908        //
8909        // If the settings aren't null, sync them up with what we've just derived.
8910        // note that apkRoot isn't stored in the package settings.
8911        if (pkgSetting != null) {
8912            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8913            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8914        }
8915    }
8916
8917    /**
8918     * Deduces the ABI of a bundled app and sets the relevant fields on the
8919     * parsed pkg object.
8920     *
8921     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8922     *        under which system libraries are installed.
8923     * @param apkName the name of the installed package.
8924     */
8925    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8926        final File codeFile = new File(pkg.codePath);
8927
8928        final boolean has64BitLibs;
8929        final boolean has32BitLibs;
8930        if (isApkFile(codeFile)) {
8931            // Monolithic install
8932            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8933            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8934        } else {
8935            // Cluster install
8936            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8937            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8938                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8939                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8940                has64BitLibs = (new File(rootDir, isa)).exists();
8941            } else {
8942                has64BitLibs = false;
8943            }
8944            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8945                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8946                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8947                has32BitLibs = (new File(rootDir, isa)).exists();
8948            } else {
8949                has32BitLibs = false;
8950            }
8951        }
8952
8953        if (has64BitLibs && !has32BitLibs) {
8954            // The package has 64 bit libs, but not 32 bit libs. Its primary
8955            // ABI should be 64 bit. We can safely assume here that the bundled
8956            // native libraries correspond to the most preferred ABI in the list.
8957
8958            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8959            pkg.applicationInfo.secondaryCpuAbi = null;
8960        } else if (has32BitLibs && !has64BitLibs) {
8961            // The package has 32 bit libs but not 64 bit libs. Its primary
8962            // ABI should be 32 bit.
8963
8964            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8965            pkg.applicationInfo.secondaryCpuAbi = null;
8966        } else if (has32BitLibs && has64BitLibs) {
8967            // The application has both 64 and 32 bit bundled libraries. We check
8968            // here that the app declares multiArch support, and warn if it doesn't.
8969            //
8970            // We will be lenient here and record both ABIs. The primary will be the
8971            // ABI that's higher on the list, i.e, a device that's configured to prefer
8972            // 64 bit apps will see a 64 bit primary ABI,
8973
8974            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8975                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8976            }
8977
8978            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8979                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8980                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8981            } else {
8982                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8983                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8984            }
8985        } else {
8986            pkg.applicationInfo.primaryCpuAbi = null;
8987            pkg.applicationInfo.secondaryCpuAbi = null;
8988        }
8989    }
8990
8991    private void killPackage(PackageParser.Package pkg, String reason) {
8992        // Kill the parent package
8993        killApplication(pkg.packageName, pkg.applicationInfo.uid, reason);
8994        // Kill the child packages
8995        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8996        for (int i = 0; i < childCount; i++) {
8997            PackageParser.Package childPkg = pkg.childPackages.get(i);
8998            killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason);
8999        }
9000    }
9001
9002    private void killApplication(String pkgName, int appId, String reason) {
9003        // Request the ActivityManager to kill the process(only for existing packages)
9004        // so that we do not end up in a confused state while the user is still using the older
9005        // version of the application while the new one gets installed.
9006        IActivityManager am = ActivityManagerNative.getDefault();
9007        if (am != null) {
9008            try {
9009                am.killApplicationWithAppId(pkgName, appId, reason);
9010            } catch (RemoteException e) {
9011            }
9012        }
9013    }
9014
9015    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9016        // Remove the parent package setting
9017        PackageSetting ps = (PackageSetting) pkg.mExtras;
9018        if (ps != null) {
9019            removePackageLI(ps, chatty);
9020        }
9021        // Remove the child package setting
9022        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9023        for (int i = 0; i < childCount; i++) {
9024            PackageParser.Package childPkg = pkg.childPackages.get(i);
9025            ps = (PackageSetting) childPkg.mExtras;
9026            if (ps != null) {
9027                removePackageLI(ps, chatty);
9028            }
9029        }
9030    }
9031
9032    void removePackageLI(PackageSetting ps, boolean chatty) {
9033        if (DEBUG_INSTALL) {
9034            if (chatty)
9035                Log.d(TAG, "Removing package " + ps.name);
9036        }
9037
9038        // writer
9039        synchronized (mPackages) {
9040            mPackages.remove(ps.name);
9041            final PackageParser.Package pkg = ps.pkg;
9042            if (pkg != null) {
9043                cleanPackageDataStructuresLILPw(pkg, chatty);
9044            }
9045        }
9046    }
9047
9048    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9049        if (DEBUG_INSTALL) {
9050            if (chatty)
9051                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9052        }
9053
9054        // writer
9055        synchronized (mPackages) {
9056            // Remove the parent package
9057            mPackages.remove(pkg.applicationInfo.packageName);
9058            cleanPackageDataStructuresLILPw(pkg, chatty);
9059
9060            // Remove the child packages
9061            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9062            for (int i = 0; i < childCount; i++) {
9063                PackageParser.Package childPkg = pkg.childPackages.get(i);
9064                mPackages.remove(childPkg.applicationInfo.packageName);
9065                cleanPackageDataStructuresLILPw(childPkg, chatty);
9066            }
9067        }
9068    }
9069
9070    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9071        int N = pkg.providers.size();
9072        StringBuilder r = null;
9073        int i;
9074        for (i=0; i<N; i++) {
9075            PackageParser.Provider p = pkg.providers.get(i);
9076            mProviders.removeProvider(p);
9077            if (p.info.authority == null) {
9078
9079                /* There was another ContentProvider with this authority when
9080                 * this app was installed so this authority is null,
9081                 * Ignore it as we don't have to unregister the provider.
9082                 */
9083                continue;
9084            }
9085            String names[] = p.info.authority.split(";");
9086            for (int j = 0; j < names.length; j++) {
9087                if (mProvidersByAuthority.get(names[j]) == p) {
9088                    mProvidersByAuthority.remove(names[j]);
9089                    if (DEBUG_REMOVE) {
9090                        if (chatty)
9091                            Log.d(TAG, "Unregistered content provider: " + names[j]
9092                                    + ", className = " + p.info.name + ", isSyncable = "
9093                                    + p.info.isSyncable);
9094                    }
9095                }
9096            }
9097            if (DEBUG_REMOVE && chatty) {
9098                if (r == null) {
9099                    r = new StringBuilder(256);
9100                } else {
9101                    r.append(' ');
9102                }
9103                r.append(p.info.name);
9104            }
9105        }
9106        if (r != null) {
9107            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9108        }
9109
9110        N = pkg.services.size();
9111        r = null;
9112        for (i=0; i<N; i++) {
9113            PackageParser.Service s = pkg.services.get(i);
9114            mServices.removeService(s);
9115            if (chatty) {
9116                if (r == null) {
9117                    r = new StringBuilder(256);
9118                } else {
9119                    r.append(' ');
9120                }
9121                r.append(s.info.name);
9122            }
9123        }
9124        if (r != null) {
9125            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9126        }
9127
9128        N = pkg.receivers.size();
9129        r = null;
9130        for (i=0; i<N; i++) {
9131            PackageParser.Activity a = pkg.receivers.get(i);
9132            mReceivers.removeActivity(a, "receiver");
9133            if (DEBUG_REMOVE && chatty) {
9134                if (r == null) {
9135                    r = new StringBuilder(256);
9136                } else {
9137                    r.append(' ');
9138                }
9139                r.append(a.info.name);
9140            }
9141        }
9142        if (r != null) {
9143            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9144        }
9145
9146        N = pkg.activities.size();
9147        r = null;
9148        for (i=0; i<N; i++) {
9149            PackageParser.Activity a = pkg.activities.get(i);
9150            mActivities.removeActivity(a, "activity");
9151            if (DEBUG_REMOVE && chatty) {
9152                if (r == null) {
9153                    r = new StringBuilder(256);
9154                } else {
9155                    r.append(' ');
9156                }
9157                r.append(a.info.name);
9158            }
9159        }
9160        if (r != null) {
9161            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9162        }
9163
9164        N = pkg.permissions.size();
9165        r = null;
9166        for (i=0; i<N; i++) {
9167            PackageParser.Permission p = pkg.permissions.get(i);
9168            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9169            if (bp == null) {
9170                bp = mSettings.mPermissionTrees.get(p.info.name);
9171            }
9172            if (bp != null && bp.perm == p) {
9173                bp.perm = null;
9174                if (DEBUG_REMOVE && chatty) {
9175                    if (r == null) {
9176                        r = new StringBuilder(256);
9177                    } else {
9178                        r.append(' ');
9179                    }
9180                    r.append(p.info.name);
9181                }
9182            }
9183            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9184                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9185                if (appOpPkgs != null) {
9186                    appOpPkgs.remove(pkg.packageName);
9187                }
9188            }
9189        }
9190        if (r != null) {
9191            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9192        }
9193
9194        N = pkg.requestedPermissions.size();
9195        r = null;
9196        for (i=0; i<N; i++) {
9197            String perm = pkg.requestedPermissions.get(i);
9198            BasePermission bp = mSettings.mPermissions.get(perm);
9199            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9200                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9201                if (appOpPkgs != null) {
9202                    appOpPkgs.remove(pkg.packageName);
9203                    if (appOpPkgs.isEmpty()) {
9204                        mAppOpPermissionPackages.remove(perm);
9205                    }
9206                }
9207            }
9208        }
9209        if (r != null) {
9210            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9211        }
9212
9213        N = pkg.instrumentation.size();
9214        r = null;
9215        for (i=0; i<N; i++) {
9216            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9217            mInstrumentation.remove(a.getComponentName());
9218            if (DEBUG_REMOVE && chatty) {
9219                if (r == null) {
9220                    r = new StringBuilder(256);
9221                } else {
9222                    r.append(' ');
9223                }
9224                r.append(a.info.name);
9225            }
9226        }
9227        if (r != null) {
9228            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9229        }
9230
9231        r = null;
9232        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9233            // Only system apps can hold shared libraries.
9234            if (pkg.libraryNames != null) {
9235                for (i=0; i<pkg.libraryNames.size(); i++) {
9236                    String name = pkg.libraryNames.get(i);
9237                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9238                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9239                        mSharedLibraries.remove(name);
9240                        if (DEBUG_REMOVE && chatty) {
9241                            if (r == null) {
9242                                r = new StringBuilder(256);
9243                            } else {
9244                                r.append(' ');
9245                            }
9246                            r.append(name);
9247                        }
9248                    }
9249                }
9250            }
9251        }
9252        if (r != null) {
9253            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9254        }
9255    }
9256
9257    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9258        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9259            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9260                return true;
9261            }
9262        }
9263        return false;
9264    }
9265
9266    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9267    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9268    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9269
9270    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9271        // Update the parent permissions
9272        updatePermissionsLPw(pkg.packageName, pkg, flags);
9273        // Update the child permissions
9274        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9275        for (int i = 0; i < childCount; i++) {
9276            PackageParser.Package childPkg = pkg.childPackages.get(i);
9277            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9278        }
9279    }
9280
9281    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9282            int flags) {
9283        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9284        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9285    }
9286
9287    private void updatePermissionsLPw(String changingPkg,
9288            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9289        // Make sure there are no dangling permission trees.
9290        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9291        while (it.hasNext()) {
9292            final BasePermission bp = it.next();
9293            if (bp.packageSetting == null) {
9294                // We may not yet have parsed the package, so just see if
9295                // we still know about its settings.
9296                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9297            }
9298            if (bp.packageSetting == null) {
9299                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9300                        + " from package " + bp.sourcePackage);
9301                it.remove();
9302            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9303                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9304                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9305                            + " from package " + bp.sourcePackage);
9306                    flags |= UPDATE_PERMISSIONS_ALL;
9307                    it.remove();
9308                }
9309            }
9310        }
9311
9312        // Make sure all dynamic permissions have been assigned to a package,
9313        // and make sure there are no dangling permissions.
9314        it = mSettings.mPermissions.values().iterator();
9315        while (it.hasNext()) {
9316            final BasePermission bp = it.next();
9317            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9318                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9319                        + bp.name + " pkg=" + bp.sourcePackage
9320                        + " info=" + bp.pendingInfo);
9321                if (bp.packageSetting == null && bp.pendingInfo != null) {
9322                    final BasePermission tree = findPermissionTreeLP(bp.name);
9323                    if (tree != null && tree.perm != null) {
9324                        bp.packageSetting = tree.packageSetting;
9325                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9326                                new PermissionInfo(bp.pendingInfo));
9327                        bp.perm.info.packageName = tree.perm.info.packageName;
9328                        bp.perm.info.name = bp.name;
9329                        bp.uid = tree.uid;
9330                    }
9331                }
9332            }
9333            if (bp.packageSetting == null) {
9334                // We may not yet have parsed the package, so just see if
9335                // we still know about its settings.
9336                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9337            }
9338            if (bp.packageSetting == null) {
9339                Slog.w(TAG, "Removing dangling permission: " + bp.name
9340                        + " from package " + bp.sourcePackage);
9341                it.remove();
9342            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9343                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9344                    Slog.i(TAG, "Removing old permission: " + bp.name
9345                            + " from package " + bp.sourcePackage);
9346                    flags |= UPDATE_PERMISSIONS_ALL;
9347                    it.remove();
9348                }
9349            }
9350        }
9351
9352        // Now update the permissions for all packages, in particular
9353        // replace the granted permissions of the system packages.
9354        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9355            for (PackageParser.Package pkg : mPackages.values()) {
9356                if (pkg != pkgInfo) {
9357                    // Only replace for packages on requested volume
9358                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9359                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9360                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9361                    grantPermissionsLPw(pkg, replace, changingPkg);
9362                }
9363            }
9364        }
9365
9366        if (pkgInfo != null) {
9367            // Only replace for packages on requested volume
9368            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9369            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9370                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9371            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9372        }
9373    }
9374
9375    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9376            String packageOfInterest) {
9377        // IMPORTANT: There are two types of permissions: install and runtime.
9378        // Install time permissions are granted when the app is installed to
9379        // all device users and users added in the future. Runtime permissions
9380        // are granted at runtime explicitly to specific users. Normal and signature
9381        // protected permissions are install time permissions. Dangerous permissions
9382        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9383        // otherwise they are runtime permissions. This function does not manage
9384        // runtime permissions except for the case an app targeting Lollipop MR1
9385        // being upgraded to target a newer SDK, in which case dangerous permissions
9386        // are transformed from install time to runtime ones.
9387
9388        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9389        if (ps == null) {
9390            return;
9391        }
9392
9393        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9394
9395        PermissionsState permissionsState = ps.getPermissionsState();
9396        PermissionsState origPermissions = permissionsState;
9397
9398        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9399
9400        boolean runtimePermissionsRevoked = false;
9401        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9402
9403        boolean changedInstallPermission = false;
9404
9405        if (replace) {
9406            ps.installPermissionsFixed = false;
9407            if (!ps.isSharedUser()) {
9408                origPermissions = new PermissionsState(permissionsState);
9409                permissionsState.reset();
9410            } else {
9411                // We need to know only about runtime permission changes since the
9412                // calling code always writes the install permissions state but
9413                // the runtime ones are written only if changed. The only cases of
9414                // changed runtime permissions here are promotion of an install to
9415                // runtime and revocation of a runtime from a shared user.
9416                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9417                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9418                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9419                    runtimePermissionsRevoked = true;
9420                }
9421            }
9422        }
9423
9424        permissionsState.setGlobalGids(mGlobalGids);
9425
9426        final int N = pkg.requestedPermissions.size();
9427        for (int i=0; i<N; i++) {
9428            final String name = pkg.requestedPermissions.get(i);
9429            final BasePermission bp = mSettings.mPermissions.get(name);
9430
9431            if (DEBUG_INSTALL) {
9432                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9433            }
9434
9435            if (bp == null || bp.packageSetting == null) {
9436                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9437                    Slog.w(TAG, "Unknown permission " + name
9438                            + " in package " + pkg.packageName);
9439                }
9440                continue;
9441            }
9442
9443            final String perm = bp.name;
9444            boolean allowedSig = false;
9445            int grant = GRANT_DENIED;
9446
9447            // Keep track of app op permissions.
9448            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9449                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9450                if (pkgs == null) {
9451                    pkgs = new ArraySet<>();
9452                    mAppOpPermissionPackages.put(bp.name, pkgs);
9453                }
9454                pkgs.add(pkg.packageName);
9455            }
9456
9457            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9458            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9459                    >= Build.VERSION_CODES.M;
9460            switch (level) {
9461                case PermissionInfo.PROTECTION_NORMAL: {
9462                    // For all apps normal permissions are install time ones.
9463                    grant = GRANT_INSTALL;
9464                } break;
9465
9466                case PermissionInfo.PROTECTION_DANGEROUS: {
9467                    // If a permission review is required for legacy apps we represent
9468                    // their permissions as always granted runtime ones since we need
9469                    // to keep the review required permission flag per user while an
9470                    // install permission's state is shared across all users.
9471                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9472                        // For legacy apps dangerous permissions are install time ones.
9473                        grant = GRANT_INSTALL;
9474                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9475                        // For legacy apps that became modern, install becomes runtime.
9476                        grant = GRANT_UPGRADE;
9477                    } else if (mPromoteSystemApps
9478                            && isSystemApp(ps)
9479                            && mExistingSystemPackages.contains(ps.name)) {
9480                        // For legacy system apps, install becomes runtime.
9481                        // We cannot check hasInstallPermission() for system apps since those
9482                        // permissions were granted implicitly and not persisted pre-M.
9483                        grant = GRANT_UPGRADE;
9484                    } else {
9485                        // For modern apps keep runtime permissions unchanged.
9486                        grant = GRANT_RUNTIME;
9487                    }
9488                } break;
9489
9490                case PermissionInfo.PROTECTION_SIGNATURE: {
9491                    // For all apps signature permissions are install time ones.
9492                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9493                    if (allowedSig) {
9494                        grant = GRANT_INSTALL;
9495                    }
9496                } break;
9497            }
9498
9499            if (DEBUG_INSTALL) {
9500                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9501            }
9502
9503            if (grant != GRANT_DENIED) {
9504                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9505                    // If this is an existing, non-system package, then
9506                    // we can't add any new permissions to it.
9507                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9508                        // Except...  if this is a permission that was added
9509                        // to the platform (note: need to only do this when
9510                        // updating the platform).
9511                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9512                            grant = GRANT_DENIED;
9513                        }
9514                    }
9515                }
9516
9517                switch (grant) {
9518                    case GRANT_INSTALL: {
9519                        // Revoke this as runtime permission to handle the case of
9520                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9521                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9522                            if (origPermissions.getRuntimePermissionState(
9523                                    bp.name, userId) != null) {
9524                                // Revoke the runtime permission and clear the flags.
9525                                origPermissions.revokeRuntimePermission(bp, userId);
9526                                origPermissions.updatePermissionFlags(bp, userId,
9527                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9528                                // If we revoked a permission permission, we have to write.
9529                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9530                                        changedRuntimePermissionUserIds, userId);
9531                            }
9532                        }
9533                        // Grant an install permission.
9534                        if (permissionsState.grantInstallPermission(bp) !=
9535                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9536                            changedInstallPermission = true;
9537                        }
9538                    } break;
9539
9540                    case GRANT_RUNTIME: {
9541                        // Grant previously granted runtime permissions.
9542                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9543                            PermissionState permissionState = origPermissions
9544                                    .getRuntimePermissionState(bp.name, userId);
9545                            int flags = permissionState != null
9546                                    ? permissionState.getFlags() : 0;
9547                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9548                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9549                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9550                                    // If we cannot put the permission as it was, we have to write.
9551                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9552                                            changedRuntimePermissionUserIds, userId);
9553                                }
9554                                // If the app supports runtime permissions no need for a review.
9555                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9556                                        && appSupportsRuntimePermissions
9557                                        && (flags & PackageManager
9558                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9559                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9560                                    // Since we changed the flags, we have to write.
9561                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9562                                            changedRuntimePermissionUserIds, userId);
9563                                }
9564                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9565                                    && !appSupportsRuntimePermissions) {
9566                                // For legacy apps that need a permission review, every new
9567                                // runtime permission is granted but it is pending a review.
9568                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9569                                    permissionsState.grantRuntimePermission(bp, userId);
9570                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9571                                    // We changed the permission and flags, hence have to write.
9572                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9573                                            changedRuntimePermissionUserIds, userId);
9574                                }
9575                            }
9576                            // Propagate the permission flags.
9577                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9578                        }
9579                    } break;
9580
9581                    case GRANT_UPGRADE: {
9582                        // Grant runtime permissions for a previously held install permission.
9583                        PermissionState permissionState = origPermissions
9584                                .getInstallPermissionState(bp.name);
9585                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9586
9587                        if (origPermissions.revokeInstallPermission(bp)
9588                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9589                            // We will be transferring the permission flags, so clear them.
9590                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9591                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9592                            changedInstallPermission = true;
9593                        }
9594
9595                        // If the permission is not to be promoted to runtime we ignore it and
9596                        // also its other flags as they are not applicable to install permissions.
9597                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9598                            for (int userId : currentUserIds) {
9599                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9600                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9601                                    // Transfer the permission flags.
9602                                    permissionsState.updatePermissionFlags(bp, userId,
9603                                            flags, flags);
9604                                    // If we granted the permission, we have to write.
9605                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9606                                            changedRuntimePermissionUserIds, userId);
9607                                }
9608                            }
9609                        }
9610                    } break;
9611
9612                    default: {
9613                        if (packageOfInterest == null
9614                                || packageOfInterest.equals(pkg.packageName)) {
9615                            Slog.w(TAG, "Not granting permission " + perm
9616                                    + " to package " + pkg.packageName
9617                                    + " because it was previously installed without");
9618                        }
9619                    } break;
9620                }
9621            } else {
9622                if (permissionsState.revokeInstallPermission(bp) !=
9623                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9624                    // Also drop the permission flags.
9625                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9626                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9627                    changedInstallPermission = true;
9628                    Slog.i(TAG, "Un-granting permission " + perm
9629                            + " from package " + pkg.packageName
9630                            + " (protectionLevel=" + bp.protectionLevel
9631                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9632                            + ")");
9633                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9634                    // Don't print warning for app op permissions, since it is fine for them
9635                    // not to be granted, there is a UI for the user to decide.
9636                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9637                        Slog.w(TAG, "Not granting permission " + perm
9638                                + " to package " + pkg.packageName
9639                                + " (protectionLevel=" + bp.protectionLevel
9640                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9641                                + ")");
9642                    }
9643                }
9644            }
9645        }
9646
9647        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9648                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9649            // This is the first that we have heard about this package, so the
9650            // permissions we have now selected are fixed until explicitly
9651            // changed.
9652            ps.installPermissionsFixed = true;
9653        }
9654
9655        // Persist the runtime permissions state for users with changes. If permissions
9656        // were revoked because no app in the shared user declares them we have to
9657        // write synchronously to avoid losing runtime permissions state.
9658        for (int userId : changedRuntimePermissionUserIds) {
9659            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9660        }
9661
9662        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9663    }
9664
9665    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9666        boolean allowed = false;
9667        final int NP = PackageParser.NEW_PERMISSIONS.length;
9668        for (int ip=0; ip<NP; ip++) {
9669            final PackageParser.NewPermissionInfo npi
9670                    = PackageParser.NEW_PERMISSIONS[ip];
9671            if (npi.name.equals(perm)
9672                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9673                allowed = true;
9674                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9675                        + pkg.packageName);
9676                break;
9677            }
9678        }
9679        return allowed;
9680    }
9681
9682    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9683            BasePermission bp, PermissionsState origPermissions) {
9684        boolean allowed;
9685        allowed = (compareSignatures(
9686                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9687                        == PackageManager.SIGNATURE_MATCH)
9688                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9689                        == PackageManager.SIGNATURE_MATCH);
9690        if (!allowed && (bp.protectionLevel
9691                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9692            if (isSystemApp(pkg)) {
9693                // For updated system applications, a system permission
9694                // is granted only if it had been defined by the original application.
9695                if (pkg.isUpdatedSystemApp()) {
9696                    final PackageSetting sysPs = mSettings
9697                            .getDisabledSystemPkgLPr(pkg.packageName);
9698                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9699                        // If the original was granted this permission, we take
9700                        // that grant decision as read and propagate it to the
9701                        // update.
9702                        if (sysPs.isPrivileged()) {
9703                            allowed = true;
9704                        }
9705                    } else {
9706                        // The system apk may have been updated with an older
9707                        // version of the one on the data partition, but which
9708                        // granted a new system permission that it didn't have
9709                        // before.  In this case we do want to allow the app to
9710                        // now get the new permission if the ancestral apk is
9711                        // privileged to get it.
9712                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9713                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9714                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9715                                    allowed = true;
9716                                    break;
9717                                }
9718                            }
9719                        }
9720                        // Also if a privileged parent package on the system image or any of
9721                        // its children requested a privileged permission, the updated child
9722                        // packages can also get the permission.
9723                        if (pkg.parentPackage != null) {
9724                            final PackageSetting disabledSysParentPs = mSettings
9725                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9726                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9727                                    && disabledSysParentPs.isPrivileged()) {
9728                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9729                                    allowed = true;
9730                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9731                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9732                                    for (int i = 0; i < count; i++) {
9733                                        PackageParser.Package disabledSysChildPkg =
9734                                                disabledSysParentPs.pkg.childPackages.get(i);
9735                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9736                                                perm)) {
9737                                            allowed = true;
9738                                            break;
9739                                        }
9740                                    }
9741                                }
9742                            }
9743                        }
9744                    }
9745                } else {
9746                    allowed = isPrivilegedApp(pkg);
9747                }
9748            }
9749        }
9750        if (!allowed) {
9751            if (!allowed && (bp.protectionLevel
9752                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9753                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9754                // If this was a previously normal/dangerous permission that got moved
9755                // to a system permission as part of the runtime permission redesign, then
9756                // we still want to blindly grant it to old apps.
9757                allowed = true;
9758            }
9759            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9760                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9761                // If this permission is to be granted to the system installer and
9762                // this app is an installer, then it gets the permission.
9763                allowed = true;
9764            }
9765            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9766                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9767                // If this permission is to be granted to the system verifier and
9768                // this app is a verifier, then it gets the permission.
9769                allowed = true;
9770            }
9771            if (!allowed && (bp.protectionLevel
9772                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9773                    && isSystemApp(pkg)) {
9774                // Any pre-installed system app is allowed to get this permission.
9775                allowed = true;
9776            }
9777            if (!allowed && (bp.protectionLevel
9778                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9779                // For development permissions, a development permission
9780                // is granted only if it was already granted.
9781                allowed = origPermissions.hasInstallPermission(perm);
9782            }
9783            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
9784                    && pkg.packageName.equals(mSetupWizardPackage)) {
9785                // If this permission is to be granted to the system setup wizard and
9786                // this app is a setup wizard, then it gets the permission.
9787                allowed = true;
9788            }
9789        }
9790        return allowed;
9791    }
9792
9793    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
9794        final int permCount = pkg.requestedPermissions.size();
9795        for (int j = 0; j < permCount; j++) {
9796            String requestedPermission = pkg.requestedPermissions.get(j);
9797            if (permission.equals(requestedPermission)) {
9798                return true;
9799            }
9800        }
9801        return false;
9802    }
9803
9804    final class ActivityIntentResolver
9805            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9806        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9807                boolean defaultOnly, int userId) {
9808            if (!sUserManager.exists(userId)) return null;
9809            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9810            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9811        }
9812
9813        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9814                int userId) {
9815            if (!sUserManager.exists(userId)) return null;
9816            mFlags = flags;
9817            return super.queryIntent(intent, resolvedType,
9818                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9819        }
9820
9821        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9822                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9823            if (!sUserManager.exists(userId)) return null;
9824            if (packageActivities == null) {
9825                return null;
9826            }
9827            mFlags = flags;
9828            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9829            final int N = packageActivities.size();
9830            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9831                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9832
9833            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9834            for (int i = 0; i < N; ++i) {
9835                intentFilters = packageActivities.get(i).intents;
9836                if (intentFilters != null && intentFilters.size() > 0) {
9837                    PackageParser.ActivityIntentInfo[] array =
9838                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9839                    intentFilters.toArray(array);
9840                    listCut.add(array);
9841                }
9842            }
9843            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9844        }
9845
9846        /**
9847         * Finds a privileged activity that matches the specified activity names.
9848         */
9849        private PackageParser.Activity findMatchingActivity(
9850                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
9851            for (PackageParser.Activity sysActivity : activityList) {
9852                if (sysActivity.info.name.equals(activityInfo.name)) {
9853                    return sysActivity;
9854                }
9855                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
9856                    return sysActivity;
9857                }
9858                if (sysActivity.info.targetActivity != null) {
9859                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
9860                        return sysActivity;
9861                    }
9862                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
9863                        return sysActivity;
9864                    }
9865                }
9866            }
9867            return null;
9868        }
9869
9870        public class IterGenerator<E> {
9871            public Iterator<E> generate(ActivityIntentInfo info) {
9872                return null;
9873            }
9874        }
9875
9876        public class ActionIterGenerator extends IterGenerator<String> {
9877            @Override
9878            public Iterator<String> generate(ActivityIntentInfo info) {
9879                return info.actionsIterator();
9880            }
9881        }
9882
9883        public class CategoriesIterGenerator extends IterGenerator<String> {
9884            @Override
9885            public Iterator<String> generate(ActivityIntentInfo info) {
9886                return info.categoriesIterator();
9887            }
9888        }
9889
9890        public class SchemesIterGenerator extends IterGenerator<String> {
9891            @Override
9892            public Iterator<String> generate(ActivityIntentInfo info) {
9893                return info.schemesIterator();
9894            }
9895        }
9896
9897        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
9898            @Override
9899            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
9900                return info.authoritiesIterator();
9901            }
9902        }
9903
9904        /**
9905         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
9906         * MODIFIED. Do not pass in a list that should not be changed.
9907         */
9908        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
9909                IterGenerator<T> generator, Iterator<T> searchIterator) {
9910            // loop through the set of actions; every one must be found in the intent filter
9911            while (searchIterator.hasNext()) {
9912                // we must have at least one filter in the list to consider a match
9913                if (intentList.size() == 0) {
9914                    break;
9915                }
9916
9917                final T searchAction = searchIterator.next();
9918
9919                // loop through the set of intent filters
9920                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
9921                while (intentIter.hasNext()) {
9922                    final ActivityIntentInfo intentInfo = intentIter.next();
9923                    boolean selectionFound = false;
9924
9925                    // loop through the intent filter's selection criteria; at least one
9926                    // of them must match the searched criteria
9927                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
9928                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
9929                        final T intentSelection = intentSelectionIter.next();
9930                        if (intentSelection != null && intentSelection.equals(searchAction)) {
9931                            selectionFound = true;
9932                            break;
9933                        }
9934                    }
9935
9936                    // the selection criteria wasn't found in this filter's set; this filter
9937                    // is not a potential match
9938                    if (!selectionFound) {
9939                        intentIter.remove();
9940                    }
9941                }
9942            }
9943        }
9944
9945        private boolean isProtectedAction(ActivityIntentInfo filter) {
9946            final Iterator<String> actionsIter = filter.actionsIterator();
9947            while (actionsIter != null && actionsIter.hasNext()) {
9948                final String filterAction = actionsIter.next();
9949                if (PROTECTED_ACTIONS.contains(filterAction)) {
9950                    return true;
9951                }
9952            }
9953            return false;
9954        }
9955
9956        /**
9957         * Adjusts the priority of the given intent filter according to policy.
9958         * <p>
9959         * <ul>
9960         * <li>The priority for non privileged applications is capped to '0'</li>
9961         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
9962         * <li>The priority for unbundled updates to privileged applications is capped to the
9963         *      priority defined on the system partition</li>
9964         * </ul>
9965         * <p>
9966         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
9967         * allowed to obtain any priority on any action.
9968         */
9969        private void adjustPriority(
9970                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
9971            // nothing to do; priority is fine as-is
9972            if (intent.getPriority() <= 0) {
9973                return;
9974            }
9975
9976            final ActivityInfo activityInfo = intent.activity.info;
9977            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
9978
9979            final boolean privilegedApp =
9980                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
9981            if (!privilegedApp) {
9982                // non-privileged applications can never define a priority >0
9983                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
9984                        + " package: " + applicationInfo.packageName
9985                        + " activity: " + intent.activity.className
9986                        + " origPrio: " + intent.getPriority());
9987                intent.setPriority(0);
9988                return;
9989            }
9990
9991            if (systemActivities == null) {
9992                // the system package is not disabled; we're parsing the system partition
9993                if (isProtectedAction(intent)) {
9994                    if (mDeferProtectedFilters) {
9995                        // We can't deal with these just yet. No component should ever obtain a
9996                        // >0 priority for a protected actions, with ONE exception -- the setup
9997                        // wizard. The setup wizard, however, cannot be known until we're able to
9998                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
9999                        // until all intent filters have been processed. Chicken, meet egg.
10000                        // Let the filter temporarily have a high priority and rectify the
10001                        // priorities after all system packages have been scanned.
10002                        mProtectedFilters.add(intent);
10003                        if (DEBUG_FILTERS) {
10004                            Slog.i(TAG, "Protected action; save for later;"
10005                                    + " package: " + applicationInfo.packageName
10006                                    + " activity: " + intent.activity.className
10007                                    + " origPrio: " + intent.getPriority());
10008                        }
10009                        return;
10010                    } else {
10011                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10012                            Slog.i(TAG, "No setup wizard;"
10013                                + " All protected intents capped to priority 0");
10014                        }
10015                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10016                            if (DEBUG_FILTERS) {
10017                                Slog.i(TAG, "Found setup wizard;"
10018                                    + " allow priority " + intent.getPriority() + ";"
10019                                    + " package: " + intent.activity.info.packageName
10020                                    + " activity: " + intent.activity.className
10021                                    + " priority: " + intent.getPriority());
10022                            }
10023                            // setup wizard gets whatever it wants
10024                            return;
10025                        }
10026                        Slog.w(TAG, "Protected action; cap priority to 0;"
10027                                + " package: " + intent.activity.info.packageName
10028                                + " activity: " + intent.activity.className
10029                                + " origPrio: " + intent.getPriority());
10030                        intent.setPriority(0);
10031                        return;
10032                    }
10033                }
10034                // privileged apps on the system image get whatever priority they request
10035                return;
10036            }
10037
10038            // privileged app unbundled update ... try to find the same activity
10039            final PackageParser.Activity foundActivity =
10040                    findMatchingActivity(systemActivities, activityInfo);
10041            if (foundActivity == null) {
10042                // this is a new activity; it cannot obtain >0 priority
10043                if (DEBUG_FILTERS) {
10044                    Slog.i(TAG, "New activity; cap priority to 0;"
10045                            + " package: " + applicationInfo.packageName
10046                            + " activity: " + intent.activity.className
10047                            + " origPrio: " + intent.getPriority());
10048                }
10049                intent.setPriority(0);
10050                return;
10051            }
10052
10053            // found activity, now check for filter equivalence
10054
10055            // a shallow copy is enough; we modify the list, not its contents
10056            final List<ActivityIntentInfo> intentListCopy =
10057                    new ArrayList<>(foundActivity.intents);
10058            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10059
10060            // find matching action subsets
10061            final Iterator<String> actionsIterator = intent.actionsIterator();
10062            if (actionsIterator != null) {
10063                getIntentListSubset(
10064                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10065                if (intentListCopy.size() == 0) {
10066                    // no more intents to match; we're not equivalent
10067                    if (DEBUG_FILTERS) {
10068                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10069                                + " package: " + applicationInfo.packageName
10070                                + " activity: " + intent.activity.className
10071                                + " origPrio: " + intent.getPriority());
10072                    }
10073                    intent.setPriority(0);
10074                    return;
10075                }
10076            }
10077
10078            // find matching category subsets
10079            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10080            if (categoriesIterator != null) {
10081                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10082                        categoriesIterator);
10083                if (intentListCopy.size() == 0) {
10084                    // no more intents to match; we're not equivalent
10085                    if (DEBUG_FILTERS) {
10086                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10087                                + " package: " + applicationInfo.packageName
10088                                + " activity: " + intent.activity.className
10089                                + " origPrio: " + intent.getPriority());
10090                    }
10091                    intent.setPriority(0);
10092                    return;
10093                }
10094            }
10095
10096            // find matching schemes subsets
10097            final Iterator<String> schemesIterator = intent.schemesIterator();
10098            if (schemesIterator != null) {
10099                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10100                        schemesIterator);
10101                if (intentListCopy.size() == 0) {
10102                    // no more intents to match; we're not equivalent
10103                    if (DEBUG_FILTERS) {
10104                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10105                                + " package: " + applicationInfo.packageName
10106                                + " activity: " + intent.activity.className
10107                                + " origPrio: " + intent.getPriority());
10108                    }
10109                    intent.setPriority(0);
10110                    return;
10111                }
10112            }
10113
10114            // find matching authorities subsets
10115            final Iterator<IntentFilter.AuthorityEntry>
10116                    authoritiesIterator = intent.authoritiesIterator();
10117            if (authoritiesIterator != null) {
10118                getIntentListSubset(intentListCopy,
10119                        new AuthoritiesIterGenerator(),
10120                        authoritiesIterator);
10121                if (intentListCopy.size() == 0) {
10122                    // no more intents to match; we're not equivalent
10123                    if (DEBUG_FILTERS) {
10124                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10125                                + " package: " + applicationInfo.packageName
10126                                + " activity: " + intent.activity.className
10127                                + " origPrio: " + intent.getPriority());
10128                    }
10129                    intent.setPriority(0);
10130                    return;
10131                }
10132            }
10133
10134            // we found matching filter(s); app gets the max priority of all intents
10135            int cappedPriority = 0;
10136            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10137                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10138            }
10139            if (intent.getPriority() > cappedPriority) {
10140                if (DEBUG_FILTERS) {
10141                    Slog.i(TAG, "Found matching filter(s);"
10142                            + " cap priority to " + cappedPriority + ";"
10143                            + " package: " + applicationInfo.packageName
10144                            + " activity: " + intent.activity.className
10145                            + " origPrio: " + intent.getPriority());
10146                }
10147                intent.setPriority(cappedPriority);
10148                return;
10149            }
10150            // all this for nothing; the requested priority was <= what was on the system
10151        }
10152
10153        public final void addActivity(PackageParser.Activity a, String type) {
10154            mActivities.put(a.getComponentName(), a);
10155            if (DEBUG_SHOW_INFO)
10156                Log.v(
10157                TAG, "  " + type + " " +
10158                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10159            if (DEBUG_SHOW_INFO)
10160                Log.v(TAG, "    Class=" + a.info.name);
10161            final int NI = a.intents.size();
10162            for (int j=0; j<NI; j++) {
10163                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10164                if ("activity".equals(type)) {
10165                    final PackageSetting ps =
10166                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10167                    final List<PackageParser.Activity> systemActivities =
10168                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10169                    adjustPriority(systemActivities, intent);
10170                }
10171                if (DEBUG_SHOW_INFO) {
10172                    Log.v(TAG, "    IntentFilter:");
10173                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10174                }
10175                if (!intent.debugCheck()) {
10176                    Log.w(TAG, "==> For Activity " + a.info.name);
10177                }
10178                addFilter(intent);
10179            }
10180        }
10181
10182        public final void removeActivity(PackageParser.Activity a, String type) {
10183            mActivities.remove(a.getComponentName());
10184            if (DEBUG_SHOW_INFO) {
10185                Log.v(TAG, "  " + type + " "
10186                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10187                                : a.info.name) + ":");
10188                Log.v(TAG, "    Class=" + a.info.name);
10189            }
10190            final int NI = a.intents.size();
10191            for (int j=0; j<NI; j++) {
10192                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10193                if (DEBUG_SHOW_INFO) {
10194                    Log.v(TAG, "    IntentFilter:");
10195                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10196                }
10197                removeFilter(intent);
10198            }
10199        }
10200
10201        @Override
10202        protected boolean allowFilterResult(
10203                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10204            ActivityInfo filterAi = filter.activity.info;
10205            for (int i=dest.size()-1; i>=0; i--) {
10206                ActivityInfo destAi = dest.get(i).activityInfo;
10207                if (destAi.name == filterAi.name
10208                        && destAi.packageName == filterAi.packageName) {
10209                    return false;
10210                }
10211            }
10212            return true;
10213        }
10214
10215        @Override
10216        protected ActivityIntentInfo[] newArray(int size) {
10217            return new ActivityIntentInfo[size];
10218        }
10219
10220        @Override
10221        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10222            if (!sUserManager.exists(userId)) return true;
10223            PackageParser.Package p = filter.activity.owner;
10224            if (p != null) {
10225                PackageSetting ps = (PackageSetting)p.mExtras;
10226                if (ps != null) {
10227                    // System apps are never considered stopped for purposes of
10228                    // filtering, because there may be no way for the user to
10229                    // actually re-launch them.
10230                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10231                            && ps.getStopped(userId);
10232                }
10233            }
10234            return false;
10235        }
10236
10237        @Override
10238        protected boolean isPackageForFilter(String packageName,
10239                PackageParser.ActivityIntentInfo info) {
10240            return packageName.equals(info.activity.owner.packageName);
10241        }
10242
10243        @Override
10244        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10245                int match, int userId) {
10246            if (!sUserManager.exists(userId)) return null;
10247            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10248                return null;
10249            }
10250            final PackageParser.Activity activity = info.activity;
10251            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10252            if (ps == null) {
10253                return null;
10254            }
10255            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10256                    ps.readUserState(userId), userId);
10257            if (ai == null) {
10258                return null;
10259            }
10260            final ResolveInfo res = new ResolveInfo();
10261            res.activityInfo = ai;
10262            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10263                res.filter = info;
10264            }
10265            if (info != null) {
10266                res.handleAllWebDataURI = info.handleAllWebDataURI();
10267            }
10268            res.priority = info.getPriority();
10269            res.preferredOrder = activity.owner.mPreferredOrder;
10270            //System.out.println("Result: " + res.activityInfo.className +
10271            //                   " = " + res.priority);
10272            res.match = match;
10273            res.isDefault = info.hasDefault;
10274            res.labelRes = info.labelRes;
10275            res.nonLocalizedLabel = info.nonLocalizedLabel;
10276            if (userNeedsBadging(userId)) {
10277                res.noResourceId = true;
10278            } else {
10279                res.icon = info.icon;
10280            }
10281            res.iconResourceId = info.icon;
10282            res.system = res.activityInfo.applicationInfo.isSystemApp();
10283            return res;
10284        }
10285
10286        @Override
10287        protected void sortResults(List<ResolveInfo> results) {
10288            Collections.sort(results, mResolvePrioritySorter);
10289        }
10290
10291        @Override
10292        protected void dumpFilter(PrintWriter out, String prefix,
10293                PackageParser.ActivityIntentInfo filter) {
10294            out.print(prefix); out.print(
10295                    Integer.toHexString(System.identityHashCode(filter.activity)));
10296                    out.print(' ');
10297                    filter.activity.printComponentShortName(out);
10298                    out.print(" filter ");
10299                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10300        }
10301
10302        @Override
10303        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10304            return filter.activity;
10305        }
10306
10307        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10308            PackageParser.Activity activity = (PackageParser.Activity)label;
10309            out.print(prefix); out.print(
10310                    Integer.toHexString(System.identityHashCode(activity)));
10311                    out.print(' ');
10312                    activity.printComponentShortName(out);
10313            if (count > 1) {
10314                out.print(" ("); out.print(count); out.print(" filters)");
10315            }
10316            out.println();
10317        }
10318
10319        // Keys are String (activity class name), values are Activity.
10320        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10321                = new ArrayMap<ComponentName, PackageParser.Activity>();
10322        private int mFlags;
10323    }
10324
10325    private final class ServiceIntentResolver
10326            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10327        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10328                boolean defaultOnly, int userId) {
10329            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10330            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10331        }
10332
10333        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10334                int userId) {
10335            if (!sUserManager.exists(userId)) return null;
10336            mFlags = flags;
10337            return super.queryIntent(intent, resolvedType,
10338                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10339        }
10340
10341        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10342                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10343            if (!sUserManager.exists(userId)) return null;
10344            if (packageServices == null) {
10345                return null;
10346            }
10347            mFlags = flags;
10348            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10349            final int N = packageServices.size();
10350            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10351                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10352
10353            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10354            for (int i = 0; i < N; ++i) {
10355                intentFilters = packageServices.get(i).intents;
10356                if (intentFilters != null && intentFilters.size() > 0) {
10357                    PackageParser.ServiceIntentInfo[] array =
10358                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10359                    intentFilters.toArray(array);
10360                    listCut.add(array);
10361                }
10362            }
10363            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10364        }
10365
10366        public final void addService(PackageParser.Service s) {
10367            mServices.put(s.getComponentName(), s);
10368            if (DEBUG_SHOW_INFO) {
10369                Log.v(TAG, "  "
10370                        + (s.info.nonLocalizedLabel != null
10371                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10372                Log.v(TAG, "    Class=" + s.info.name);
10373            }
10374            final int NI = s.intents.size();
10375            int j;
10376            for (j=0; j<NI; j++) {
10377                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10378                if (DEBUG_SHOW_INFO) {
10379                    Log.v(TAG, "    IntentFilter:");
10380                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10381                }
10382                if (!intent.debugCheck()) {
10383                    Log.w(TAG, "==> For Service " + s.info.name);
10384                }
10385                addFilter(intent);
10386            }
10387        }
10388
10389        public final void removeService(PackageParser.Service s) {
10390            mServices.remove(s.getComponentName());
10391            if (DEBUG_SHOW_INFO) {
10392                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10393                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10394                Log.v(TAG, "    Class=" + s.info.name);
10395            }
10396            final int NI = s.intents.size();
10397            int j;
10398            for (j=0; j<NI; j++) {
10399                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10400                if (DEBUG_SHOW_INFO) {
10401                    Log.v(TAG, "    IntentFilter:");
10402                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10403                }
10404                removeFilter(intent);
10405            }
10406        }
10407
10408        @Override
10409        protected boolean allowFilterResult(
10410                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10411            ServiceInfo filterSi = filter.service.info;
10412            for (int i=dest.size()-1; i>=0; i--) {
10413                ServiceInfo destAi = dest.get(i).serviceInfo;
10414                if (destAi.name == filterSi.name
10415                        && destAi.packageName == filterSi.packageName) {
10416                    return false;
10417                }
10418            }
10419            return true;
10420        }
10421
10422        @Override
10423        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10424            return new PackageParser.ServiceIntentInfo[size];
10425        }
10426
10427        @Override
10428        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10429            if (!sUserManager.exists(userId)) return true;
10430            PackageParser.Package p = filter.service.owner;
10431            if (p != null) {
10432                PackageSetting ps = (PackageSetting)p.mExtras;
10433                if (ps != null) {
10434                    // System apps are never considered stopped for purposes of
10435                    // filtering, because there may be no way for the user to
10436                    // actually re-launch them.
10437                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10438                            && ps.getStopped(userId);
10439                }
10440            }
10441            return false;
10442        }
10443
10444        @Override
10445        protected boolean isPackageForFilter(String packageName,
10446                PackageParser.ServiceIntentInfo info) {
10447            return packageName.equals(info.service.owner.packageName);
10448        }
10449
10450        @Override
10451        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10452                int match, int userId) {
10453            if (!sUserManager.exists(userId)) return null;
10454            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10455            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10456                return null;
10457            }
10458            final PackageParser.Service service = info.service;
10459            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10460            if (ps == null) {
10461                return null;
10462            }
10463            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10464                    ps.readUserState(userId), userId);
10465            if (si == null) {
10466                return null;
10467            }
10468            final ResolveInfo res = new ResolveInfo();
10469            res.serviceInfo = si;
10470            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10471                res.filter = filter;
10472            }
10473            res.priority = info.getPriority();
10474            res.preferredOrder = service.owner.mPreferredOrder;
10475            res.match = match;
10476            res.isDefault = info.hasDefault;
10477            res.labelRes = info.labelRes;
10478            res.nonLocalizedLabel = info.nonLocalizedLabel;
10479            res.icon = info.icon;
10480            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10481            return res;
10482        }
10483
10484        @Override
10485        protected void sortResults(List<ResolveInfo> results) {
10486            Collections.sort(results, mResolvePrioritySorter);
10487        }
10488
10489        @Override
10490        protected void dumpFilter(PrintWriter out, String prefix,
10491                PackageParser.ServiceIntentInfo filter) {
10492            out.print(prefix); out.print(
10493                    Integer.toHexString(System.identityHashCode(filter.service)));
10494                    out.print(' ');
10495                    filter.service.printComponentShortName(out);
10496                    out.print(" filter ");
10497                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10498        }
10499
10500        @Override
10501        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10502            return filter.service;
10503        }
10504
10505        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10506            PackageParser.Service service = (PackageParser.Service)label;
10507            out.print(prefix); out.print(
10508                    Integer.toHexString(System.identityHashCode(service)));
10509                    out.print(' ');
10510                    service.printComponentShortName(out);
10511            if (count > 1) {
10512                out.print(" ("); out.print(count); out.print(" filters)");
10513            }
10514            out.println();
10515        }
10516
10517//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10518//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10519//            final List<ResolveInfo> retList = Lists.newArrayList();
10520//            while (i.hasNext()) {
10521//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10522//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10523//                    retList.add(resolveInfo);
10524//                }
10525//            }
10526//            return retList;
10527//        }
10528
10529        // Keys are String (activity class name), values are Activity.
10530        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10531                = new ArrayMap<ComponentName, PackageParser.Service>();
10532        private int mFlags;
10533    };
10534
10535    private final class ProviderIntentResolver
10536            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10537        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10538                boolean defaultOnly, int userId) {
10539            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10540            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10541        }
10542
10543        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10544                int userId) {
10545            if (!sUserManager.exists(userId))
10546                return null;
10547            mFlags = flags;
10548            return super.queryIntent(intent, resolvedType,
10549                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10550        }
10551
10552        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10553                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10554            if (!sUserManager.exists(userId))
10555                return null;
10556            if (packageProviders == null) {
10557                return null;
10558            }
10559            mFlags = flags;
10560            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10561            final int N = packageProviders.size();
10562            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10563                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10564
10565            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10566            for (int i = 0; i < N; ++i) {
10567                intentFilters = packageProviders.get(i).intents;
10568                if (intentFilters != null && intentFilters.size() > 0) {
10569                    PackageParser.ProviderIntentInfo[] array =
10570                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10571                    intentFilters.toArray(array);
10572                    listCut.add(array);
10573                }
10574            }
10575            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10576        }
10577
10578        public final void addProvider(PackageParser.Provider p) {
10579            if (mProviders.containsKey(p.getComponentName())) {
10580                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10581                return;
10582            }
10583
10584            mProviders.put(p.getComponentName(), p);
10585            if (DEBUG_SHOW_INFO) {
10586                Log.v(TAG, "  "
10587                        + (p.info.nonLocalizedLabel != null
10588                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10589                Log.v(TAG, "    Class=" + p.info.name);
10590            }
10591            final int NI = p.intents.size();
10592            int j;
10593            for (j = 0; j < NI; j++) {
10594                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10595                if (DEBUG_SHOW_INFO) {
10596                    Log.v(TAG, "    IntentFilter:");
10597                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10598                }
10599                if (!intent.debugCheck()) {
10600                    Log.w(TAG, "==> For Provider " + p.info.name);
10601                }
10602                addFilter(intent);
10603            }
10604        }
10605
10606        public final void removeProvider(PackageParser.Provider p) {
10607            mProviders.remove(p.getComponentName());
10608            if (DEBUG_SHOW_INFO) {
10609                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10610                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10611                Log.v(TAG, "    Class=" + p.info.name);
10612            }
10613            final int NI = p.intents.size();
10614            int j;
10615            for (j = 0; j < NI; j++) {
10616                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10617                if (DEBUG_SHOW_INFO) {
10618                    Log.v(TAG, "    IntentFilter:");
10619                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10620                }
10621                removeFilter(intent);
10622            }
10623        }
10624
10625        @Override
10626        protected boolean allowFilterResult(
10627                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10628            ProviderInfo filterPi = filter.provider.info;
10629            for (int i = dest.size() - 1; i >= 0; i--) {
10630                ProviderInfo destPi = dest.get(i).providerInfo;
10631                if (destPi.name == filterPi.name
10632                        && destPi.packageName == filterPi.packageName) {
10633                    return false;
10634                }
10635            }
10636            return true;
10637        }
10638
10639        @Override
10640        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10641            return new PackageParser.ProviderIntentInfo[size];
10642        }
10643
10644        @Override
10645        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10646            if (!sUserManager.exists(userId))
10647                return true;
10648            PackageParser.Package p = filter.provider.owner;
10649            if (p != null) {
10650                PackageSetting ps = (PackageSetting) p.mExtras;
10651                if (ps != null) {
10652                    // System apps are never considered stopped for purposes of
10653                    // filtering, because there may be no way for the user to
10654                    // actually re-launch them.
10655                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10656                            && ps.getStopped(userId);
10657                }
10658            }
10659            return false;
10660        }
10661
10662        @Override
10663        protected boolean isPackageForFilter(String packageName,
10664                PackageParser.ProviderIntentInfo info) {
10665            return packageName.equals(info.provider.owner.packageName);
10666        }
10667
10668        @Override
10669        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10670                int match, int userId) {
10671            if (!sUserManager.exists(userId))
10672                return null;
10673            final PackageParser.ProviderIntentInfo info = filter;
10674            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10675                return null;
10676            }
10677            final PackageParser.Provider provider = info.provider;
10678            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10679            if (ps == null) {
10680                return null;
10681            }
10682            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10683                    ps.readUserState(userId), userId);
10684            if (pi == null) {
10685                return null;
10686            }
10687            final ResolveInfo res = new ResolveInfo();
10688            res.providerInfo = pi;
10689            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10690                res.filter = filter;
10691            }
10692            res.priority = info.getPriority();
10693            res.preferredOrder = provider.owner.mPreferredOrder;
10694            res.match = match;
10695            res.isDefault = info.hasDefault;
10696            res.labelRes = info.labelRes;
10697            res.nonLocalizedLabel = info.nonLocalizedLabel;
10698            res.icon = info.icon;
10699            res.system = res.providerInfo.applicationInfo.isSystemApp();
10700            return res;
10701        }
10702
10703        @Override
10704        protected void sortResults(List<ResolveInfo> results) {
10705            Collections.sort(results, mResolvePrioritySorter);
10706        }
10707
10708        @Override
10709        protected void dumpFilter(PrintWriter out, String prefix,
10710                PackageParser.ProviderIntentInfo filter) {
10711            out.print(prefix);
10712            out.print(
10713                    Integer.toHexString(System.identityHashCode(filter.provider)));
10714            out.print(' ');
10715            filter.provider.printComponentShortName(out);
10716            out.print(" filter ");
10717            out.println(Integer.toHexString(System.identityHashCode(filter)));
10718        }
10719
10720        @Override
10721        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10722            return filter.provider;
10723        }
10724
10725        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10726            PackageParser.Provider provider = (PackageParser.Provider)label;
10727            out.print(prefix); out.print(
10728                    Integer.toHexString(System.identityHashCode(provider)));
10729                    out.print(' ');
10730                    provider.printComponentShortName(out);
10731            if (count > 1) {
10732                out.print(" ("); out.print(count); out.print(" filters)");
10733            }
10734            out.println();
10735        }
10736
10737        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10738                = new ArrayMap<ComponentName, PackageParser.Provider>();
10739        private int mFlags;
10740    }
10741
10742    private static final class EphemeralIntentResolver
10743            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10744        @Override
10745        protected EphemeralResolveIntentInfo[] newArray(int size) {
10746            return new EphemeralResolveIntentInfo[size];
10747        }
10748
10749        @Override
10750        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10751            return true;
10752        }
10753
10754        @Override
10755        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10756                int userId) {
10757            if (!sUserManager.exists(userId)) {
10758                return null;
10759            }
10760            return info.getEphemeralResolveInfo();
10761        }
10762    }
10763
10764    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10765            new Comparator<ResolveInfo>() {
10766        public int compare(ResolveInfo r1, ResolveInfo r2) {
10767            int v1 = r1.priority;
10768            int v2 = r2.priority;
10769            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10770            if (v1 != v2) {
10771                return (v1 > v2) ? -1 : 1;
10772            }
10773            v1 = r1.preferredOrder;
10774            v2 = r2.preferredOrder;
10775            if (v1 != v2) {
10776                return (v1 > v2) ? -1 : 1;
10777            }
10778            if (r1.isDefault != r2.isDefault) {
10779                return r1.isDefault ? -1 : 1;
10780            }
10781            v1 = r1.match;
10782            v2 = r2.match;
10783            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
10784            if (v1 != v2) {
10785                return (v1 > v2) ? -1 : 1;
10786            }
10787            if (r1.system != r2.system) {
10788                return r1.system ? -1 : 1;
10789            }
10790            if (r1.activityInfo != null) {
10791                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
10792            }
10793            if (r1.serviceInfo != null) {
10794                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
10795            }
10796            if (r1.providerInfo != null) {
10797                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
10798            }
10799            return 0;
10800        }
10801    };
10802
10803    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
10804            new Comparator<ProviderInfo>() {
10805        public int compare(ProviderInfo p1, ProviderInfo p2) {
10806            final int v1 = p1.initOrder;
10807            final int v2 = p2.initOrder;
10808            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
10809        }
10810    };
10811
10812    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
10813            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
10814            final int[] userIds) {
10815        mHandler.post(new Runnable() {
10816            @Override
10817            public void run() {
10818                try {
10819                    final IActivityManager am = ActivityManagerNative.getDefault();
10820                    if (am == null) return;
10821                    final int[] resolvedUserIds;
10822                    if (userIds == null) {
10823                        resolvedUserIds = am.getRunningUserIds();
10824                    } else {
10825                        resolvedUserIds = userIds;
10826                    }
10827                    for (int id : resolvedUserIds) {
10828                        final Intent intent = new Intent(action,
10829                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
10830                        if (extras != null) {
10831                            intent.putExtras(extras);
10832                        }
10833                        if (targetPkg != null) {
10834                            intent.setPackage(targetPkg);
10835                        }
10836                        // Modify the UID when posting to other users
10837                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
10838                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
10839                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
10840                            intent.putExtra(Intent.EXTRA_UID, uid);
10841                        }
10842                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
10843                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
10844                        if (DEBUG_BROADCASTS) {
10845                            RuntimeException here = new RuntimeException("here");
10846                            here.fillInStackTrace();
10847                            Slog.d(TAG, "Sending to user " + id + ": "
10848                                    + intent.toShortString(false, true, false, false)
10849                                    + " " + intent.getExtras(), here);
10850                        }
10851                        am.broadcastIntent(null, intent, null, finishedReceiver,
10852                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
10853                                null, finishedReceiver != null, false, id);
10854                    }
10855                } catch (RemoteException ex) {
10856                }
10857            }
10858        });
10859    }
10860
10861    /**
10862     * Check if the external storage media is available. This is true if there
10863     * is a mounted external storage medium or if the external storage is
10864     * emulated.
10865     */
10866    private boolean isExternalMediaAvailable() {
10867        return mMediaMounted || Environment.isExternalStorageEmulated();
10868    }
10869
10870    @Override
10871    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
10872        // writer
10873        synchronized (mPackages) {
10874            if (!isExternalMediaAvailable()) {
10875                // If the external storage is no longer mounted at this point,
10876                // the caller may not have been able to delete all of this
10877                // packages files and can not delete any more.  Bail.
10878                return null;
10879            }
10880            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
10881            if (lastPackage != null) {
10882                pkgs.remove(lastPackage);
10883            }
10884            if (pkgs.size() > 0) {
10885                return pkgs.get(0);
10886            }
10887        }
10888        return null;
10889    }
10890
10891    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
10892        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
10893                userId, andCode ? 1 : 0, packageName);
10894        if (mSystemReady) {
10895            msg.sendToTarget();
10896        } else {
10897            if (mPostSystemReadyMessages == null) {
10898                mPostSystemReadyMessages = new ArrayList<>();
10899            }
10900            mPostSystemReadyMessages.add(msg);
10901        }
10902    }
10903
10904    void startCleaningPackages() {
10905        // reader
10906        if (!isExternalMediaAvailable()) {
10907            return;
10908        }
10909        synchronized (mPackages) {
10910            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
10911                return;
10912            }
10913        }
10914        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
10915        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
10916        IActivityManager am = ActivityManagerNative.getDefault();
10917        if (am != null) {
10918            try {
10919                am.startService(null, intent, null, mContext.getOpPackageName(),
10920                        UserHandle.USER_SYSTEM);
10921            } catch (RemoteException e) {
10922            }
10923        }
10924    }
10925
10926    @Override
10927    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
10928            int installFlags, String installerPackageName, int userId) {
10929        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
10930
10931        final int callingUid = Binder.getCallingUid();
10932        enforceCrossUserPermission(callingUid, userId,
10933                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
10934
10935        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10936            try {
10937                if (observer != null) {
10938                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10939                }
10940            } catch (RemoteException re) {
10941            }
10942            return;
10943        }
10944
10945        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10946            installFlags |= PackageManager.INSTALL_FROM_ADB;
10947
10948        } else {
10949            // Caller holds INSTALL_PACKAGES permission, so we're less strict
10950            // about installerPackageName.
10951
10952            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10953            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10954        }
10955
10956        UserHandle user;
10957        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10958            user = UserHandle.ALL;
10959        } else {
10960            user = new UserHandle(userId);
10961        }
10962
10963        // Only system components can circumvent runtime permissions when installing.
10964        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10965                && mContext.checkCallingOrSelfPermission(Manifest.permission
10966                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10967            throw new SecurityException("You need the "
10968                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10969                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10970        }
10971
10972        final File originFile = new File(originPath);
10973        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10974
10975        final Message msg = mHandler.obtainMessage(INIT_COPY);
10976        final VerificationInfo verificationInfo = new VerificationInfo(
10977                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
10978        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
10979                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
10980                null /*packageAbiOverride*/, null /*grantedPermissions*/);
10981        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10982        msg.obj = params;
10983
10984        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10985                System.identityHashCode(msg.obj));
10986        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10987                System.identityHashCode(msg.obj));
10988
10989        mHandler.sendMessage(msg);
10990    }
10991
10992    void installStage(String packageName, File stagedDir, String stagedCid,
10993            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10994            String installerPackageName, int installerUid, UserHandle user) {
10995        if (DEBUG_EPHEMERAL) {
10996            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10997                Slog.d(TAG, "Ephemeral install of " + packageName);
10998            }
10999        }
11000        final VerificationInfo verificationInfo = new VerificationInfo(
11001                sessionParams.originatingUri, sessionParams.referrerUri,
11002                sessionParams.originatingUid, installerUid);
11003
11004        final OriginInfo origin;
11005        if (stagedDir != null) {
11006            origin = OriginInfo.fromStagedFile(stagedDir);
11007        } else {
11008            origin = OriginInfo.fromStagedContainer(stagedCid);
11009        }
11010
11011        final Message msg = mHandler.obtainMessage(INIT_COPY);
11012        final InstallParams params = new InstallParams(origin, null, observer,
11013                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11014                verificationInfo, user, sessionParams.abiOverride,
11015                sessionParams.grantedRuntimePermissions);
11016        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11017        msg.obj = params;
11018
11019        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11020                System.identityHashCode(msg.obj));
11021        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11022                System.identityHashCode(msg.obj));
11023
11024        mHandler.sendMessage(msg);
11025    }
11026
11027    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11028            int userId) {
11029        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11030        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11031    }
11032
11033    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11034            int appId, int userId) {
11035        Bundle extras = new Bundle(1);
11036        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11037
11038        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11039                packageName, extras, 0, null, null, new int[] {userId});
11040        try {
11041            IActivityManager am = ActivityManagerNative.getDefault();
11042            if (isSystem && am.isUserRunning(userId, 0)) {
11043                // The just-installed/enabled app is bundled on the system, so presumed
11044                // to be able to run automatically without needing an explicit launch.
11045                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11046                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11047                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11048                        .setPackage(packageName);
11049                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11050                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11051            }
11052        } catch (RemoteException e) {
11053            // shouldn't happen
11054            Slog.w(TAG, "Unable to bootstrap installed package", e);
11055        }
11056    }
11057
11058    @Override
11059    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11060            int userId) {
11061        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11062        PackageSetting pkgSetting;
11063        final int uid = Binder.getCallingUid();
11064        enforceCrossUserPermission(uid, userId,
11065                true /* requireFullPermission */, true /* checkShell */,
11066                "setApplicationHiddenSetting for user " + userId);
11067
11068        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11069            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11070            return false;
11071        }
11072
11073        long callingId = Binder.clearCallingIdentity();
11074        try {
11075            boolean sendAdded = false;
11076            boolean sendRemoved = false;
11077            // writer
11078            synchronized (mPackages) {
11079                pkgSetting = mSettings.mPackages.get(packageName);
11080                if (pkgSetting == null) {
11081                    return false;
11082                }
11083                if (pkgSetting.getHidden(userId) != hidden) {
11084                    pkgSetting.setHidden(hidden, userId);
11085                    mSettings.writePackageRestrictionsLPr(userId);
11086                    if (hidden) {
11087                        sendRemoved = true;
11088                    } else {
11089                        sendAdded = true;
11090                    }
11091                }
11092            }
11093            if (sendAdded) {
11094                sendPackageAddedForUser(packageName, pkgSetting, userId);
11095                return true;
11096            }
11097            if (sendRemoved) {
11098                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11099                        "hiding pkg");
11100                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11101                return true;
11102            }
11103        } finally {
11104            Binder.restoreCallingIdentity(callingId);
11105        }
11106        return false;
11107    }
11108
11109    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11110            int userId) {
11111        final PackageRemovedInfo info = new PackageRemovedInfo();
11112        info.removedPackage = packageName;
11113        info.removedUsers = new int[] {userId};
11114        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11115        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11116    }
11117
11118    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11119        if (pkgList.length > 0) {
11120            Bundle extras = new Bundle(1);
11121            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11122
11123            sendPackageBroadcast(
11124                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11125                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11126                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11127                    new int[] {userId});
11128        }
11129    }
11130
11131    /**
11132     * Returns true if application is not found or there was an error. Otherwise it returns
11133     * the hidden state of the package for the given user.
11134     */
11135    @Override
11136    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11137        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11138        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11139                true /* requireFullPermission */, false /* checkShell */,
11140                "getApplicationHidden for user " + userId);
11141        PackageSetting pkgSetting;
11142        long callingId = Binder.clearCallingIdentity();
11143        try {
11144            // writer
11145            synchronized (mPackages) {
11146                pkgSetting = mSettings.mPackages.get(packageName);
11147                if (pkgSetting == null) {
11148                    return true;
11149                }
11150                return pkgSetting.getHidden(userId);
11151            }
11152        } finally {
11153            Binder.restoreCallingIdentity(callingId);
11154        }
11155    }
11156
11157    /**
11158     * @hide
11159     */
11160    @Override
11161    public int installExistingPackageAsUser(String packageName, int userId) {
11162        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11163                null);
11164        PackageSetting pkgSetting;
11165        final int uid = Binder.getCallingUid();
11166        enforceCrossUserPermission(uid, userId,
11167                true /* requireFullPermission */, true /* checkShell */,
11168                "installExistingPackage for user " + userId);
11169        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11170            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11171        }
11172
11173        long callingId = Binder.clearCallingIdentity();
11174        try {
11175            boolean installed = false;
11176
11177            // writer
11178            synchronized (mPackages) {
11179                pkgSetting = mSettings.mPackages.get(packageName);
11180                if (pkgSetting == null) {
11181                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11182                }
11183                if (!pkgSetting.getInstalled(userId)) {
11184                    pkgSetting.setInstalled(true, userId);
11185                    pkgSetting.setHidden(false, userId);
11186                    mSettings.writePackageRestrictionsLPr(userId);
11187                    installed = true;
11188                }
11189            }
11190
11191            if (installed) {
11192                if (pkgSetting.pkg != null) {
11193                    prepareAppDataAfterInstall(pkgSetting.pkg);
11194                }
11195                sendPackageAddedForUser(packageName, pkgSetting, userId);
11196            }
11197        } finally {
11198            Binder.restoreCallingIdentity(callingId);
11199        }
11200
11201        return PackageManager.INSTALL_SUCCEEDED;
11202    }
11203
11204    boolean isUserRestricted(int userId, String restrictionKey) {
11205        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11206        if (restrictions.getBoolean(restrictionKey, false)) {
11207            Log.w(TAG, "User is restricted: " + restrictionKey);
11208            return true;
11209        }
11210        return false;
11211    }
11212
11213    @Override
11214    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11215            int userId) {
11216        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11217        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11218                true /* requireFullPermission */, true /* checkShell */,
11219                "setPackagesSuspended for user " + userId);
11220
11221        if (ArrayUtils.isEmpty(packageNames)) {
11222            return packageNames;
11223        }
11224
11225        // List of package names for whom the suspended state has changed.
11226        List<String> changedPackages = new ArrayList<>(packageNames.length);
11227        // List of package names for whom the suspended state is not set as requested in this
11228        // method.
11229        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11230        for (int i = 0; i < packageNames.length; i++) {
11231            String packageName = packageNames[i];
11232            long callingId = Binder.clearCallingIdentity();
11233            try {
11234                boolean changed = false;
11235                final int appId;
11236                synchronized (mPackages) {
11237                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11238                    if (pkgSetting == null) {
11239                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11240                                + "\". Skipping suspending/un-suspending.");
11241                        unactionedPackages.add(packageName);
11242                        continue;
11243                    }
11244                    appId = pkgSetting.appId;
11245                    if (pkgSetting.getSuspended(userId) != suspended) {
11246                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11247                            unactionedPackages.add(packageName);
11248                            continue;
11249                        }
11250                        pkgSetting.setSuspended(suspended, userId);
11251                        mSettings.writePackageRestrictionsLPr(userId);
11252                        changed = true;
11253                        changedPackages.add(packageName);
11254                    }
11255                }
11256
11257                if (changed && suspended) {
11258                    killApplication(packageName, UserHandle.getUid(userId, appId),
11259                            "suspending package");
11260                }
11261            } finally {
11262                Binder.restoreCallingIdentity(callingId);
11263            }
11264        }
11265
11266        if (!changedPackages.isEmpty()) {
11267            sendPackagesSuspendedForUser(changedPackages.toArray(
11268                    new String[changedPackages.size()]), userId, suspended);
11269        }
11270
11271        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11272    }
11273
11274    @Override
11275    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11276        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11277                true /* requireFullPermission */, false /* checkShell */,
11278                "isPackageSuspendedForUser for user " + userId);
11279        synchronized (mPackages) {
11280            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11281            if (pkgSetting == null) {
11282                throw new IllegalArgumentException("Unknown target package: " + packageName);
11283            }
11284            return pkgSetting.getSuspended(userId);
11285        }
11286    }
11287
11288    /**
11289     * TODO: cache and disallow blocking the active dialer.
11290     *
11291     * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions
11292     */
11293    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11294        if (isPackageDeviceAdmin(packageName, userId)) {
11295            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11296                    + "\": has an active device admin");
11297            return false;
11298        }
11299
11300        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11301        if (packageName.equals(activeLauncherPackageName)) {
11302            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11303                    + "\": contains the active launcher");
11304            return false;
11305        }
11306
11307        if (packageName.equals(mRequiredInstallerPackage)) {
11308            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11309                    + "\": required for package installation");
11310            return false;
11311        }
11312
11313        if (packageName.equals(mRequiredVerifierPackage)) {
11314            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11315                    + "\": required for package verification");
11316            return false;
11317        }
11318
11319        final PackageParser.Package pkg = mPackages.get(packageName);
11320        if (pkg != null && isPrivilegedApp(pkg)) {
11321            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11322                    + "\": is a privileged app");
11323            return false;
11324        }
11325
11326        return true;
11327    }
11328
11329    private String getActiveLauncherPackageName(int userId) {
11330        Intent intent = new Intent(Intent.ACTION_MAIN);
11331        intent.addCategory(Intent.CATEGORY_HOME);
11332        ResolveInfo resolveInfo = resolveIntent(
11333                intent,
11334                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11335                PackageManager.MATCH_DEFAULT_ONLY,
11336                userId);
11337
11338        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11339    }
11340
11341    @Override
11342    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11343        mContext.enforceCallingOrSelfPermission(
11344                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11345                "Only package verification agents can verify applications");
11346
11347        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11348        final PackageVerificationResponse response = new PackageVerificationResponse(
11349                verificationCode, Binder.getCallingUid());
11350        msg.arg1 = id;
11351        msg.obj = response;
11352        mHandler.sendMessage(msg);
11353    }
11354
11355    @Override
11356    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11357            long millisecondsToDelay) {
11358        mContext.enforceCallingOrSelfPermission(
11359                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11360                "Only package verification agents can extend verification timeouts");
11361
11362        final PackageVerificationState state = mPendingVerification.get(id);
11363        final PackageVerificationResponse response = new PackageVerificationResponse(
11364                verificationCodeAtTimeout, Binder.getCallingUid());
11365
11366        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11367            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11368        }
11369        if (millisecondsToDelay < 0) {
11370            millisecondsToDelay = 0;
11371        }
11372        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11373                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11374            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11375        }
11376
11377        if ((state != null) && !state.timeoutExtended()) {
11378            state.extendTimeout();
11379
11380            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11381            msg.arg1 = id;
11382            msg.obj = response;
11383            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11384        }
11385    }
11386
11387    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11388            int verificationCode, UserHandle user) {
11389        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11390        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11391        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11392        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11393        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11394
11395        mContext.sendBroadcastAsUser(intent, user,
11396                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11397    }
11398
11399    private ComponentName matchComponentForVerifier(String packageName,
11400            List<ResolveInfo> receivers) {
11401        ActivityInfo targetReceiver = null;
11402
11403        final int NR = receivers.size();
11404        for (int i = 0; i < NR; i++) {
11405            final ResolveInfo info = receivers.get(i);
11406            if (info.activityInfo == null) {
11407                continue;
11408            }
11409
11410            if (packageName.equals(info.activityInfo.packageName)) {
11411                targetReceiver = info.activityInfo;
11412                break;
11413            }
11414        }
11415
11416        if (targetReceiver == null) {
11417            return null;
11418        }
11419
11420        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11421    }
11422
11423    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11424            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11425        if (pkgInfo.verifiers.length == 0) {
11426            return null;
11427        }
11428
11429        final int N = pkgInfo.verifiers.length;
11430        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11431        for (int i = 0; i < N; i++) {
11432            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11433
11434            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11435                    receivers);
11436            if (comp == null) {
11437                continue;
11438            }
11439
11440            final int verifierUid = getUidForVerifier(verifierInfo);
11441            if (verifierUid == -1) {
11442                continue;
11443            }
11444
11445            if (DEBUG_VERIFY) {
11446                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11447                        + " with the correct signature");
11448            }
11449            sufficientVerifiers.add(comp);
11450            verificationState.addSufficientVerifier(verifierUid);
11451        }
11452
11453        return sufficientVerifiers;
11454    }
11455
11456    private int getUidForVerifier(VerifierInfo verifierInfo) {
11457        synchronized (mPackages) {
11458            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11459            if (pkg == null) {
11460                return -1;
11461            } else if (pkg.mSignatures.length != 1) {
11462                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11463                        + " has more than one signature; ignoring");
11464                return -1;
11465            }
11466
11467            /*
11468             * If the public key of the package's signature does not match
11469             * our expected public key, then this is a different package and
11470             * we should skip.
11471             */
11472
11473            final byte[] expectedPublicKey;
11474            try {
11475                final Signature verifierSig = pkg.mSignatures[0];
11476                final PublicKey publicKey = verifierSig.getPublicKey();
11477                expectedPublicKey = publicKey.getEncoded();
11478            } catch (CertificateException e) {
11479                return -1;
11480            }
11481
11482            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11483
11484            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11485                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11486                        + " does not have the expected public key; ignoring");
11487                return -1;
11488            }
11489
11490            return pkg.applicationInfo.uid;
11491        }
11492    }
11493
11494    @Override
11495    public void finishPackageInstall(int token) {
11496        enforceSystemOrRoot("Only the system is allowed to finish installs");
11497
11498        if (DEBUG_INSTALL) {
11499            Slog.v(TAG, "BM finishing package install for " + token);
11500        }
11501        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11502
11503        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11504        mHandler.sendMessage(msg);
11505    }
11506
11507    /**
11508     * Get the verification agent timeout.
11509     *
11510     * @return verification timeout in milliseconds
11511     */
11512    private long getVerificationTimeout() {
11513        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11514                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11515                DEFAULT_VERIFICATION_TIMEOUT);
11516    }
11517
11518    /**
11519     * Get the default verification agent response code.
11520     *
11521     * @return default verification response code
11522     */
11523    private int getDefaultVerificationResponse() {
11524        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11525                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11526                DEFAULT_VERIFICATION_RESPONSE);
11527    }
11528
11529    /**
11530     * Check whether or not package verification has been enabled.
11531     *
11532     * @return true if verification should be performed
11533     */
11534    private boolean isVerificationEnabled(int userId, int installFlags) {
11535        if (!DEFAULT_VERIFY_ENABLE) {
11536            return false;
11537        }
11538        // Ephemeral apps don't get the full verification treatment
11539        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11540            if (DEBUG_EPHEMERAL) {
11541                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11542            }
11543            return false;
11544        }
11545
11546        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11547
11548        // Check if installing from ADB
11549        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11550            // Do not run verification in a test harness environment
11551            if (ActivityManager.isRunningInTestHarness()) {
11552                return false;
11553            }
11554            if (ensureVerifyAppsEnabled) {
11555                return true;
11556            }
11557            // Check if the developer does not want package verification for ADB installs
11558            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11559                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11560                return false;
11561            }
11562        }
11563
11564        if (ensureVerifyAppsEnabled) {
11565            return true;
11566        }
11567
11568        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11569                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11570    }
11571
11572    @Override
11573    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11574            throws RemoteException {
11575        mContext.enforceCallingOrSelfPermission(
11576                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11577                "Only intentfilter verification agents can verify applications");
11578
11579        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11580        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11581                Binder.getCallingUid(), verificationCode, failedDomains);
11582        msg.arg1 = id;
11583        msg.obj = response;
11584        mHandler.sendMessage(msg);
11585    }
11586
11587    @Override
11588    public int getIntentVerificationStatus(String packageName, int userId) {
11589        synchronized (mPackages) {
11590            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11591        }
11592    }
11593
11594    @Override
11595    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11596        mContext.enforceCallingOrSelfPermission(
11597                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11598
11599        boolean result = false;
11600        synchronized (mPackages) {
11601            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11602        }
11603        if (result) {
11604            scheduleWritePackageRestrictionsLocked(userId);
11605        }
11606        return result;
11607    }
11608
11609    @Override
11610    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
11611            String packageName) {
11612        synchronized (mPackages) {
11613            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
11614        }
11615    }
11616
11617    @Override
11618    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
11619        if (TextUtils.isEmpty(packageName)) {
11620            return ParceledListSlice.emptyList();
11621        }
11622        synchronized (mPackages) {
11623            PackageParser.Package pkg = mPackages.get(packageName);
11624            if (pkg == null || pkg.activities == null) {
11625                return ParceledListSlice.emptyList();
11626            }
11627            final int count = pkg.activities.size();
11628            ArrayList<IntentFilter> result = new ArrayList<>();
11629            for (int n=0; n<count; n++) {
11630                PackageParser.Activity activity = pkg.activities.get(n);
11631                if (activity.intents != null && activity.intents.size() > 0) {
11632                    result.addAll(activity.intents);
11633                }
11634            }
11635            return new ParceledListSlice<>(result);
11636        }
11637    }
11638
11639    @Override
11640    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11641        mContext.enforceCallingOrSelfPermission(
11642                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11643
11644        synchronized (mPackages) {
11645            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11646            if (packageName != null) {
11647                result |= updateIntentVerificationStatus(packageName,
11648                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11649                        userId);
11650                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11651                        packageName, userId);
11652            }
11653            return result;
11654        }
11655    }
11656
11657    @Override
11658    public String getDefaultBrowserPackageName(int userId) {
11659        synchronized (mPackages) {
11660            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11661        }
11662    }
11663
11664    /**
11665     * Get the "allow unknown sources" setting.
11666     *
11667     * @return the current "allow unknown sources" setting
11668     */
11669    private int getUnknownSourcesSettings() {
11670        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
11671                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
11672                -1);
11673    }
11674
11675    @Override
11676    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11677        final int uid = Binder.getCallingUid();
11678        // writer
11679        synchronized (mPackages) {
11680            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11681            if (targetPackageSetting == null) {
11682                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11683            }
11684
11685            PackageSetting installerPackageSetting;
11686            if (installerPackageName != null) {
11687                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11688                if (installerPackageSetting == null) {
11689                    throw new IllegalArgumentException("Unknown installer package: "
11690                            + installerPackageName);
11691                }
11692            } else {
11693                installerPackageSetting = null;
11694            }
11695
11696            Signature[] callerSignature;
11697            Object obj = mSettings.getUserIdLPr(uid);
11698            if (obj != null) {
11699                if (obj instanceof SharedUserSetting) {
11700                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11701                } else if (obj instanceof PackageSetting) {
11702                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11703                } else {
11704                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11705                }
11706            } else {
11707                throw new SecurityException("Unknown calling UID: " + uid);
11708            }
11709
11710            // Verify: can't set installerPackageName to a package that is
11711            // not signed with the same cert as the caller.
11712            if (installerPackageSetting != null) {
11713                if (compareSignatures(callerSignature,
11714                        installerPackageSetting.signatures.mSignatures)
11715                        != PackageManager.SIGNATURE_MATCH) {
11716                    throw new SecurityException(
11717                            "Caller does not have same cert as new installer package "
11718                            + installerPackageName);
11719                }
11720            }
11721
11722            // Verify: if target already has an installer package, it must
11723            // be signed with the same cert as the caller.
11724            if (targetPackageSetting.installerPackageName != null) {
11725                PackageSetting setting = mSettings.mPackages.get(
11726                        targetPackageSetting.installerPackageName);
11727                // If the currently set package isn't valid, then it's always
11728                // okay to change it.
11729                if (setting != null) {
11730                    if (compareSignatures(callerSignature,
11731                            setting.signatures.mSignatures)
11732                            != PackageManager.SIGNATURE_MATCH) {
11733                        throw new SecurityException(
11734                                "Caller does not have same cert as old installer package "
11735                                + targetPackageSetting.installerPackageName);
11736                    }
11737                }
11738            }
11739
11740            // Okay!
11741            targetPackageSetting.installerPackageName = installerPackageName;
11742            scheduleWriteSettingsLocked();
11743        }
11744    }
11745
11746    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11747        // Queue up an async operation since the package installation may take a little while.
11748        mHandler.post(new Runnable() {
11749            public void run() {
11750                mHandler.removeCallbacks(this);
11751                 // Result object to be returned
11752                PackageInstalledInfo res = new PackageInstalledInfo();
11753                res.setReturnCode(currentStatus);
11754                res.uid = -1;
11755                res.pkg = null;
11756                res.removedInfo = null;
11757                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11758                    args.doPreInstall(res.returnCode);
11759                    synchronized (mInstallLock) {
11760                        installPackageTracedLI(args, res);
11761                    }
11762                    args.doPostInstall(res.returnCode, res.uid);
11763                }
11764
11765                // A restore should be performed at this point if (a) the install
11766                // succeeded, (b) the operation is not an update, and (c) the new
11767                // package has not opted out of backup participation.
11768                final boolean update = res.removedInfo != null
11769                        && res.removedInfo.removedPackage != null;
11770                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
11771                boolean doRestore = !update
11772                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
11773
11774                // Set up the post-install work request bookkeeping.  This will be used
11775                // and cleaned up by the post-install event handling regardless of whether
11776                // there's a restore pass performed.  Token values are >= 1.
11777                int token;
11778                if (mNextInstallToken < 0) mNextInstallToken = 1;
11779                token = mNextInstallToken++;
11780
11781                PostInstallData data = new PostInstallData(args, res);
11782                mRunningInstalls.put(token, data);
11783                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
11784
11785                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
11786                    // Pass responsibility to the Backup Manager.  It will perform a
11787                    // restore if appropriate, then pass responsibility back to the
11788                    // Package Manager to run the post-install observer callbacks
11789                    // and broadcasts.
11790                    IBackupManager bm = IBackupManager.Stub.asInterface(
11791                            ServiceManager.getService(Context.BACKUP_SERVICE));
11792                    if (bm != null) {
11793                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
11794                                + " to BM for possible restore");
11795                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11796                        try {
11797                            // TODO: http://b/22388012
11798                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
11799                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
11800                            } else {
11801                                doRestore = false;
11802                            }
11803                        } catch (RemoteException e) {
11804                            // can't happen; the backup manager is local
11805                        } catch (Exception e) {
11806                            Slog.e(TAG, "Exception trying to enqueue restore", e);
11807                            doRestore = false;
11808                        }
11809                    } else {
11810                        Slog.e(TAG, "Backup Manager not found!");
11811                        doRestore = false;
11812                    }
11813                }
11814
11815                if (!doRestore) {
11816                    // No restore possible, or the Backup Manager was mysteriously not
11817                    // available -- just fire the post-install work request directly.
11818                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
11819
11820                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
11821
11822                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11823                    mHandler.sendMessage(msg);
11824                }
11825            }
11826        });
11827    }
11828
11829    private abstract class HandlerParams {
11830        private static final int MAX_RETRIES = 4;
11831
11832        /**
11833         * Number of times startCopy() has been attempted and had a non-fatal
11834         * error.
11835         */
11836        private int mRetries = 0;
11837
11838        /** User handle for the user requesting the information or installation. */
11839        private final UserHandle mUser;
11840        String traceMethod;
11841        int traceCookie;
11842
11843        HandlerParams(UserHandle user) {
11844            mUser = user;
11845        }
11846
11847        UserHandle getUser() {
11848            return mUser;
11849        }
11850
11851        HandlerParams setTraceMethod(String traceMethod) {
11852            this.traceMethod = traceMethod;
11853            return this;
11854        }
11855
11856        HandlerParams setTraceCookie(int traceCookie) {
11857            this.traceCookie = traceCookie;
11858            return this;
11859        }
11860
11861        final boolean startCopy() {
11862            boolean res;
11863            try {
11864                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
11865
11866                if (++mRetries > MAX_RETRIES) {
11867                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
11868                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
11869                    handleServiceError();
11870                    return false;
11871                } else {
11872                    handleStartCopy();
11873                    res = true;
11874                }
11875            } catch (RemoteException e) {
11876                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
11877                mHandler.sendEmptyMessage(MCS_RECONNECT);
11878                res = false;
11879            }
11880            handleReturnCode();
11881            return res;
11882        }
11883
11884        final void serviceError() {
11885            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
11886            handleServiceError();
11887            handleReturnCode();
11888        }
11889
11890        abstract void handleStartCopy() throws RemoteException;
11891        abstract void handleServiceError();
11892        abstract void handleReturnCode();
11893    }
11894
11895    class MeasureParams extends HandlerParams {
11896        private final PackageStats mStats;
11897        private boolean mSuccess;
11898
11899        private final IPackageStatsObserver mObserver;
11900
11901        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
11902            super(new UserHandle(stats.userHandle));
11903            mObserver = observer;
11904            mStats = stats;
11905        }
11906
11907        @Override
11908        public String toString() {
11909            return "MeasureParams{"
11910                + Integer.toHexString(System.identityHashCode(this))
11911                + " " + mStats.packageName + "}";
11912        }
11913
11914        @Override
11915        void handleStartCopy() throws RemoteException {
11916            synchronized (mInstallLock) {
11917                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
11918            }
11919
11920            if (mSuccess) {
11921                final boolean mounted;
11922                if (Environment.isExternalStorageEmulated()) {
11923                    mounted = true;
11924                } else {
11925                    final String status = Environment.getExternalStorageState();
11926                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
11927                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
11928                }
11929
11930                if (mounted) {
11931                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
11932
11933                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
11934                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
11935
11936                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
11937                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
11938
11939                    // Always subtract cache size, since it's a subdirectory
11940                    mStats.externalDataSize -= mStats.externalCacheSize;
11941
11942                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
11943                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
11944
11945                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
11946                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
11947                }
11948            }
11949        }
11950
11951        @Override
11952        void handleReturnCode() {
11953            if (mObserver != null) {
11954                try {
11955                    mObserver.onGetStatsCompleted(mStats, mSuccess);
11956                } catch (RemoteException e) {
11957                    Slog.i(TAG, "Observer no longer exists.");
11958                }
11959            }
11960        }
11961
11962        @Override
11963        void handleServiceError() {
11964            Slog.e(TAG, "Could not measure application " + mStats.packageName
11965                            + " external storage");
11966        }
11967    }
11968
11969    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
11970            throws RemoteException {
11971        long result = 0;
11972        for (File path : paths) {
11973            result += mcs.calculateDirectorySize(path.getAbsolutePath());
11974        }
11975        return result;
11976    }
11977
11978    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
11979        for (File path : paths) {
11980            try {
11981                mcs.clearDirectory(path.getAbsolutePath());
11982            } catch (RemoteException e) {
11983            }
11984        }
11985    }
11986
11987    static class OriginInfo {
11988        /**
11989         * Location where install is coming from, before it has been
11990         * copied/renamed into place. This could be a single monolithic APK
11991         * file, or a cluster directory. This location may be untrusted.
11992         */
11993        final File file;
11994        final String cid;
11995
11996        /**
11997         * Flag indicating that {@link #file} or {@link #cid} has already been
11998         * staged, meaning downstream users don't need to defensively copy the
11999         * contents.
12000         */
12001        final boolean staged;
12002
12003        /**
12004         * Flag indicating that {@link #file} or {@link #cid} is an already
12005         * installed app that is being moved.
12006         */
12007        final boolean existing;
12008
12009        final String resolvedPath;
12010        final File resolvedFile;
12011
12012        static OriginInfo fromNothing() {
12013            return new OriginInfo(null, null, false, false);
12014        }
12015
12016        static OriginInfo fromUntrustedFile(File file) {
12017            return new OriginInfo(file, null, false, false);
12018        }
12019
12020        static OriginInfo fromExistingFile(File file) {
12021            return new OriginInfo(file, null, false, true);
12022        }
12023
12024        static OriginInfo fromStagedFile(File file) {
12025            return new OriginInfo(file, null, true, false);
12026        }
12027
12028        static OriginInfo fromStagedContainer(String cid) {
12029            return new OriginInfo(null, cid, true, false);
12030        }
12031
12032        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12033            this.file = file;
12034            this.cid = cid;
12035            this.staged = staged;
12036            this.existing = existing;
12037
12038            if (cid != null) {
12039                resolvedPath = PackageHelper.getSdDir(cid);
12040                resolvedFile = new File(resolvedPath);
12041            } else if (file != null) {
12042                resolvedPath = file.getAbsolutePath();
12043                resolvedFile = file;
12044            } else {
12045                resolvedPath = null;
12046                resolvedFile = null;
12047            }
12048        }
12049    }
12050
12051    static class MoveInfo {
12052        final int moveId;
12053        final String fromUuid;
12054        final String toUuid;
12055        final String packageName;
12056        final String dataAppName;
12057        final int appId;
12058        final String seinfo;
12059        final int targetSdkVersion;
12060
12061        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12062                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12063            this.moveId = moveId;
12064            this.fromUuid = fromUuid;
12065            this.toUuid = toUuid;
12066            this.packageName = packageName;
12067            this.dataAppName = dataAppName;
12068            this.appId = appId;
12069            this.seinfo = seinfo;
12070            this.targetSdkVersion = targetSdkVersion;
12071        }
12072    }
12073
12074    static class VerificationInfo {
12075        /** A constant used to indicate that a uid value is not present. */
12076        public static final int NO_UID = -1;
12077
12078        /** URI referencing where the package was downloaded from. */
12079        final Uri originatingUri;
12080
12081        /** HTTP referrer URI associated with the originatingURI. */
12082        final Uri referrer;
12083
12084        /** UID of the application that the install request originated from. */
12085        final int originatingUid;
12086
12087        /** UID of application requesting the install */
12088        final int installerUid;
12089
12090        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12091            this.originatingUri = originatingUri;
12092            this.referrer = referrer;
12093            this.originatingUid = originatingUid;
12094            this.installerUid = installerUid;
12095        }
12096    }
12097
12098    class InstallParams extends HandlerParams {
12099        final OriginInfo origin;
12100        final MoveInfo move;
12101        final IPackageInstallObserver2 observer;
12102        int installFlags;
12103        final String installerPackageName;
12104        final String volumeUuid;
12105        private InstallArgs mArgs;
12106        private int mRet;
12107        final String packageAbiOverride;
12108        final String[] grantedRuntimePermissions;
12109        final VerificationInfo verificationInfo;
12110
12111        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12112                int installFlags, String installerPackageName, String volumeUuid,
12113                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12114                String[] grantedPermissions) {
12115            super(user);
12116            this.origin = origin;
12117            this.move = move;
12118            this.observer = observer;
12119            this.installFlags = installFlags;
12120            this.installerPackageName = installerPackageName;
12121            this.volumeUuid = volumeUuid;
12122            this.verificationInfo = verificationInfo;
12123            this.packageAbiOverride = packageAbiOverride;
12124            this.grantedRuntimePermissions = grantedPermissions;
12125        }
12126
12127        @Override
12128        public String toString() {
12129            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12130                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12131        }
12132
12133        private int installLocationPolicy(PackageInfoLite pkgLite) {
12134            String packageName = pkgLite.packageName;
12135            int installLocation = pkgLite.installLocation;
12136            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12137            // reader
12138            synchronized (mPackages) {
12139                // Currently installed package which the new package is attempting to replace or
12140                // null if no such package is installed.
12141                PackageParser.Package installedPkg = mPackages.get(packageName);
12142                // Package which currently owns the data which the new package will own if installed.
12143                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12144                // will be null whereas dataOwnerPkg will contain information about the package
12145                // which was uninstalled while keeping its data.
12146                PackageParser.Package dataOwnerPkg = installedPkg;
12147                if (dataOwnerPkg  == null) {
12148                    PackageSetting ps = mSettings.mPackages.get(packageName);
12149                    if (ps != null) {
12150                        dataOwnerPkg = ps.pkg;
12151                    }
12152                }
12153
12154                if (dataOwnerPkg != null) {
12155                    // If installed, the package will get access to data left on the device by its
12156                    // predecessor. As a security measure, this is permited only if this is not a
12157                    // version downgrade or if the predecessor package is marked as debuggable and
12158                    // a downgrade is explicitly requested.
12159                    //
12160                    // On debuggable platform builds, downgrades are permitted even for
12161                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12162                    // not offer security guarantees and thus it's OK to disable some security
12163                    // mechanisms to make debugging/testing easier on those builds. However, even on
12164                    // debuggable builds downgrades of packages are permitted only if requested via
12165                    // installFlags. This is because we aim to keep the behavior of debuggable
12166                    // platform builds as close as possible to the behavior of non-debuggable
12167                    // platform builds.
12168                    final boolean downgradeRequested =
12169                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12170                    final boolean packageDebuggable =
12171                                (dataOwnerPkg.applicationInfo.flags
12172                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12173                    final boolean downgradePermitted =
12174                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12175                    if (!downgradePermitted) {
12176                        try {
12177                            checkDowngrade(dataOwnerPkg, pkgLite);
12178                        } catch (PackageManagerException e) {
12179                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12180                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12181                        }
12182                    }
12183                }
12184
12185                if (installedPkg != null) {
12186                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12187                        // Check for updated system application.
12188                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12189                            if (onSd) {
12190                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12191                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12192                            }
12193                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12194                        } else {
12195                            if (onSd) {
12196                                // Install flag overrides everything.
12197                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12198                            }
12199                            // If current upgrade specifies particular preference
12200                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12201                                // Application explicitly specified internal.
12202                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12203                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12204                                // App explictly prefers external. Let policy decide
12205                            } else {
12206                                // Prefer previous location
12207                                if (isExternal(installedPkg)) {
12208                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12209                                }
12210                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12211                            }
12212                        }
12213                    } else {
12214                        // Invalid install. Return error code
12215                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12216                    }
12217                }
12218            }
12219            // All the special cases have been taken care of.
12220            // Return result based on recommended install location.
12221            if (onSd) {
12222                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12223            }
12224            return pkgLite.recommendedInstallLocation;
12225        }
12226
12227        /*
12228         * Invoke remote method to get package information and install
12229         * location values. Override install location based on default
12230         * policy if needed and then create install arguments based
12231         * on the install location.
12232         */
12233        public void handleStartCopy() throws RemoteException {
12234            int ret = PackageManager.INSTALL_SUCCEEDED;
12235
12236            // If we're already staged, we've firmly committed to an install location
12237            if (origin.staged) {
12238                if (origin.file != null) {
12239                    installFlags |= PackageManager.INSTALL_INTERNAL;
12240                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12241                } else if (origin.cid != null) {
12242                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12243                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12244                } else {
12245                    throw new IllegalStateException("Invalid stage location");
12246                }
12247            }
12248
12249            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12250            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12251            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12252            PackageInfoLite pkgLite = null;
12253
12254            if (onInt && onSd) {
12255                // Check if both bits are set.
12256                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12257                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12258            } else if (onSd && ephemeral) {
12259                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12260                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12261            } else {
12262                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12263                        packageAbiOverride);
12264
12265                if (DEBUG_EPHEMERAL && ephemeral) {
12266                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12267                }
12268
12269                /*
12270                 * If we have too little free space, try to free cache
12271                 * before giving up.
12272                 */
12273                if (!origin.staged && pkgLite.recommendedInstallLocation
12274                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12275                    // TODO: focus freeing disk space on the target device
12276                    final StorageManager storage = StorageManager.from(mContext);
12277                    final long lowThreshold = storage.getStorageLowBytes(
12278                            Environment.getDataDirectory());
12279
12280                    final long sizeBytes = mContainerService.calculateInstalledSize(
12281                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12282
12283                    try {
12284                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12285                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12286                                installFlags, packageAbiOverride);
12287                    } catch (InstallerException e) {
12288                        Slog.w(TAG, "Failed to free cache", e);
12289                    }
12290
12291                    /*
12292                     * The cache free must have deleted the file we
12293                     * downloaded to install.
12294                     *
12295                     * TODO: fix the "freeCache" call to not delete
12296                     *       the file we care about.
12297                     */
12298                    if (pkgLite.recommendedInstallLocation
12299                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12300                        pkgLite.recommendedInstallLocation
12301                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12302                    }
12303                }
12304            }
12305
12306            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12307                int loc = pkgLite.recommendedInstallLocation;
12308                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12309                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12310                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12311                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12312                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12313                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12314                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12315                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12316                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12317                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12318                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12319                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12320                } else {
12321                    // Override with defaults if needed.
12322                    loc = installLocationPolicy(pkgLite);
12323                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12324                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12325                    } else if (!onSd && !onInt) {
12326                        // Override install location with flags
12327                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12328                            // Set the flag to install on external media.
12329                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12330                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12331                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12332                            if (DEBUG_EPHEMERAL) {
12333                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12334                            }
12335                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12336                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12337                                    |PackageManager.INSTALL_INTERNAL);
12338                        } else {
12339                            // Make sure the flag for installing on external
12340                            // media is unset
12341                            installFlags |= PackageManager.INSTALL_INTERNAL;
12342                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12343                        }
12344                    }
12345                }
12346            }
12347
12348            final InstallArgs args = createInstallArgs(this);
12349            mArgs = args;
12350
12351            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12352                // TODO: http://b/22976637
12353                // Apps installed for "all" users use the device owner to verify the app
12354                UserHandle verifierUser = getUser();
12355                if (verifierUser == UserHandle.ALL) {
12356                    verifierUser = UserHandle.SYSTEM;
12357                }
12358
12359                /*
12360                 * Determine if we have any installed package verifiers. If we
12361                 * do, then we'll defer to them to verify the packages.
12362                 */
12363                final int requiredUid = mRequiredVerifierPackage == null ? -1
12364                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12365                                verifierUser.getIdentifier());
12366                if (!origin.existing && requiredUid != -1
12367                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12368                    final Intent verification = new Intent(
12369                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12370                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12371                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12372                            PACKAGE_MIME_TYPE);
12373                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12374
12375                    // Query all live verifiers based on current user state
12376                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12377                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12378
12379                    if (DEBUG_VERIFY) {
12380                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12381                                + verification.toString() + " with " + pkgLite.verifiers.length
12382                                + " optional verifiers");
12383                    }
12384
12385                    final int verificationId = mPendingVerificationToken++;
12386
12387                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12388
12389                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12390                            installerPackageName);
12391
12392                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12393                            installFlags);
12394
12395                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12396                            pkgLite.packageName);
12397
12398                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12399                            pkgLite.versionCode);
12400
12401                    if (verificationInfo != null) {
12402                        if (verificationInfo.originatingUri != null) {
12403                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12404                                    verificationInfo.originatingUri);
12405                        }
12406                        if (verificationInfo.referrer != null) {
12407                            verification.putExtra(Intent.EXTRA_REFERRER,
12408                                    verificationInfo.referrer);
12409                        }
12410                        if (verificationInfo.originatingUid >= 0) {
12411                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12412                                    verificationInfo.originatingUid);
12413                        }
12414                        if (verificationInfo.installerUid >= 0) {
12415                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12416                                    verificationInfo.installerUid);
12417                        }
12418                    }
12419
12420                    final PackageVerificationState verificationState = new PackageVerificationState(
12421                            requiredUid, args);
12422
12423                    mPendingVerification.append(verificationId, verificationState);
12424
12425                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12426                            receivers, verificationState);
12427
12428                    /*
12429                     * If any sufficient verifiers were listed in the package
12430                     * manifest, attempt to ask them.
12431                     */
12432                    if (sufficientVerifiers != null) {
12433                        final int N = sufficientVerifiers.size();
12434                        if (N == 0) {
12435                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12436                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12437                        } else {
12438                            for (int i = 0; i < N; i++) {
12439                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12440
12441                                final Intent sufficientIntent = new Intent(verification);
12442                                sufficientIntent.setComponent(verifierComponent);
12443                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12444                            }
12445                        }
12446                    }
12447
12448                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12449                            mRequiredVerifierPackage, receivers);
12450                    if (ret == PackageManager.INSTALL_SUCCEEDED
12451                            && mRequiredVerifierPackage != null) {
12452                        Trace.asyncTraceBegin(
12453                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12454                        /*
12455                         * Send the intent to the required verification agent,
12456                         * but only start the verification timeout after the
12457                         * target BroadcastReceivers have run.
12458                         */
12459                        verification.setComponent(requiredVerifierComponent);
12460                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12461                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12462                                new BroadcastReceiver() {
12463                                    @Override
12464                                    public void onReceive(Context context, Intent intent) {
12465                                        final Message msg = mHandler
12466                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12467                                        msg.arg1 = verificationId;
12468                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12469                                    }
12470                                }, null, 0, null, null);
12471
12472                        /*
12473                         * We don't want the copy to proceed until verification
12474                         * succeeds, so null out this field.
12475                         */
12476                        mArgs = null;
12477                    }
12478                } else {
12479                    /*
12480                     * No package verification is enabled, so immediately start
12481                     * the remote call to initiate copy using temporary file.
12482                     */
12483                    ret = args.copyApk(mContainerService, true);
12484                }
12485            }
12486
12487            mRet = ret;
12488        }
12489
12490        @Override
12491        void handleReturnCode() {
12492            // If mArgs is null, then MCS couldn't be reached. When it
12493            // reconnects, it will try again to install. At that point, this
12494            // will succeed.
12495            if (mArgs != null) {
12496                processPendingInstall(mArgs, mRet);
12497            }
12498        }
12499
12500        @Override
12501        void handleServiceError() {
12502            mArgs = createInstallArgs(this);
12503            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12504        }
12505
12506        public boolean isForwardLocked() {
12507            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12508        }
12509    }
12510
12511    /**
12512     * Used during creation of InstallArgs
12513     *
12514     * @param installFlags package installation flags
12515     * @return true if should be installed on external storage
12516     */
12517    private static boolean installOnExternalAsec(int installFlags) {
12518        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12519            return false;
12520        }
12521        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12522            return true;
12523        }
12524        return false;
12525    }
12526
12527    /**
12528     * Used during creation of InstallArgs
12529     *
12530     * @param installFlags package installation flags
12531     * @return true if should be installed as forward locked
12532     */
12533    private static boolean installForwardLocked(int installFlags) {
12534        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12535    }
12536
12537    private InstallArgs createInstallArgs(InstallParams params) {
12538        if (params.move != null) {
12539            return new MoveInstallArgs(params);
12540        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
12541            return new AsecInstallArgs(params);
12542        } else {
12543            return new FileInstallArgs(params);
12544        }
12545    }
12546
12547    /**
12548     * Create args that describe an existing installed package. Typically used
12549     * when cleaning up old installs, or used as a move source.
12550     */
12551    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
12552            String resourcePath, String[] instructionSets) {
12553        final boolean isInAsec;
12554        if (installOnExternalAsec(installFlags)) {
12555            /* Apps on SD card are always in ASEC containers. */
12556            isInAsec = true;
12557        } else if (installForwardLocked(installFlags)
12558                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
12559            /*
12560             * Forward-locked apps are only in ASEC containers if they're the
12561             * new style
12562             */
12563            isInAsec = true;
12564        } else {
12565            isInAsec = false;
12566        }
12567
12568        if (isInAsec) {
12569            return new AsecInstallArgs(codePath, instructionSets,
12570                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
12571        } else {
12572            return new FileInstallArgs(codePath, resourcePath, instructionSets);
12573        }
12574    }
12575
12576    static abstract class InstallArgs {
12577        /** @see InstallParams#origin */
12578        final OriginInfo origin;
12579        /** @see InstallParams#move */
12580        final MoveInfo move;
12581
12582        final IPackageInstallObserver2 observer;
12583        // Always refers to PackageManager flags only
12584        final int installFlags;
12585        final String installerPackageName;
12586        final String volumeUuid;
12587        final UserHandle user;
12588        final String abiOverride;
12589        final String[] installGrantPermissions;
12590        /** If non-null, drop an async trace when the install completes */
12591        final String traceMethod;
12592        final int traceCookie;
12593
12594        // The list of instruction sets supported by this app. This is currently
12595        // only used during the rmdex() phase to clean up resources. We can get rid of this
12596        // if we move dex files under the common app path.
12597        /* nullable */ String[] instructionSets;
12598
12599        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12600                int installFlags, String installerPackageName, String volumeUuid,
12601                UserHandle user, String[] instructionSets,
12602                String abiOverride, String[] installGrantPermissions,
12603                String traceMethod, int traceCookie) {
12604            this.origin = origin;
12605            this.move = move;
12606            this.installFlags = installFlags;
12607            this.observer = observer;
12608            this.installerPackageName = installerPackageName;
12609            this.volumeUuid = volumeUuid;
12610            this.user = user;
12611            this.instructionSets = instructionSets;
12612            this.abiOverride = abiOverride;
12613            this.installGrantPermissions = installGrantPermissions;
12614            this.traceMethod = traceMethod;
12615            this.traceCookie = traceCookie;
12616        }
12617
12618        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
12619        abstract int doPreInstall(int status);
12620
12621        /**
12622         * Rename package into final resting place. All paths on the given
12623         * scanned package should be updated to reflect the rename.
12624         */
12625        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
12626        abstract int doPostInstall(int status, int uid);
12627
12628        /** @see PackageSettingBase#codePathString */
12629        abstract String getCodePath();
12630        /** @see PackageSettingBase#resourcePathString */
12631        abstract String getResourcePath();
12632
12633        // Need installer lock especially for dex file removal.
12634        abstract void cleanUpResourcesLI();
12635        abstract boolean doPostDeleteLI(boolean delete);
12636
12637        /**
12638         * Called before the source arguments are copied. This is used mostly
12639         * for MoveParams when it needs to read the source file to put it in the
12640         * destination.
12641         */
12642        int doPreCopy() {
12643            return PackageManager.INSTALL_SUCCEEDED;
12644        }
12645
12646        /**
12647         * Called after the source arguments are copied. This is used mostly for
12648         * MoveParams when it needs to read the source file to put it in the
12649         * destination.
12650         */
12651        int doPostCopy(int uid) {
12652            return PackageManager.INSTALL_SUCCEEDED;
12653        }
12654
12655        protected boolean isFwdLocked() {
12656            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12657        }
12658
12659        protected boolean isExternalAsec() {
12660            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12661        }
12662
12663        protected boolean isEphemeral() {
12664            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12665        }
12666
12667        UserHandle getUser() {
12668            return user;
12669        }
12670    }
12671
12672    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
12673        if (!allCodePaths.isEmpty()) {
12674            if (instructionSets == null) {
12675                throw new IllegalStateException("instructionSet == null");
12676            }
12677            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12678            for (String codePath : allCodePaths) {
12679                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12680                    try {
12681                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12682                    } catch (InstallerException ignored) {
12683                    }
12684                }
12685            }
12686        }
12687    }
12688
12689    /**
12690     * Logic to handle installation of non-ASEC applications, including copying
12691     * and renaming logic.
12692     */
12693    class FileInstallArgs extends InstallArgs {
12694        private File codeFile;
12695        private File resourceFile;
12696
12697        // Example topology:
12698        // /data/app/com.example/base.apk
12699        // /data/app/com.example/split_foo.apk
12700        // /data/app/com.example/lib/arm/libfoo.so
12701        // /data/app/com.example/lib/arm64/libfoo.so
12702        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
12703
12704        /** New install */
12705        FileInstallArgs(InstallParams params) {
12706            super(params.origin, params.move, params.observer, params.installFlags,
12707                    params.installerPackageName, params.volumeUuid,
12708                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12709                    params.grantedRuntimePermissions,
12710                    params.traceMethod, params.traceCookie);
12711            if (isFwdLocked()) {
12712                throw new IllegalArgumentException("Forward locking only supported in ASEC");
12713            }
12714        }
12715
12716        /** Existing install */
12717        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
12718            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
12719                    null, null, null, 0);
12720            this.codeFile = (codePath != null) ? new File(codePath) : null;
12721            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
12722        }
12723
12724        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12725            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
12726            try {
12727                return doCopyApk(imcs, temp);
12728            } finally {
12729                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12730            }
12731        }
12732
12733        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12734            if (origin.staged) {
12735                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12736                codeFile = origin.file;
12737                resourceFile = origin.file;
12738                return PackageManager.INSTALL_SUCCEEDED;
12739            }
12740
12741            try {
12742                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12743                final File tempDir =
12744                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12745                codeFile = tempDir;
12746                resourceFile = tempDir;
12747            } catch (IOException e) {
12748                Slog.w(TAG, "Failed to create copy file: " + e);
12749                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12750            }
12751
12752            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12753                @Override
12754                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12755                    if (!FileUtils.isValidExtFilename(name)) {
12756                        throw new IllegalArgumentException("Invalid filename: " + name);
12757                    }
12758                    try {
12759                        final File file = new File(codeFile, name);
12760                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12761                                O_RDWR | O_CREAT, 0644);
12762                        Os.chmod(file.getAbsolutePath(), 0644);
12763                        return new ParcelFileDescriptor(fd);
12764                    } catch (ErrnoException e) {
12765                        throw new RemoteException("Failed to open: " + e.getMessage());
12766                    }
12767                }
12768            };
12769
12770            int ret = PackageManager.INSTALL_SUCCEEDED;
12771            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
12772            if (ret != PackageManager.INSTALL_SUCCEEDED) {
12773                Slog.e(TAG, "Failed to copy package");
12774                return ret;
12775            }
12776
12777            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
12778            NativeLibraryHelper.Handle handle = null;
12779            try {
12780                handle = NativeLibraryHelper.Handle.create(codeFile);
12781                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
12782                        abiOverride);
12783            } catch (IOException e) {
12784                Slog.e(TAG, "Copying native libraries failed", e);
12785                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12786            } finally {
12787                IoUtils.closeQuietly(handle);
12788            }
12789
12790            return ret;
12791        }
12792
12793        int doPreInstall(int status) {
12794            if (status != PackageManager.INSTALL_SUCCEEDED) {
12795                cleanUp();
12796            }
12797            return status;
12798        }
12799
12800        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12801            if (status != PackageManager.INSTALL_SUCCEEDED) {
12802                cleanUp();
12803                return false;
12804            }
12805
12806            final File targetDir = codeFile.getParentFile();
12807            final File beforeCodeFile = codeFile;
12808            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
12809
12810            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
12811            try {
12812                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
12813            } catch (ErrnoException e) {
12814                Slog.w(TAG, "Failed to rename", e);
12815                return false;
12816            }
12817
12818            if (!SELinux.restoreconRecursive(afterCodeFile)) {
12819                Slog.w(TAG, "Failed to restorecon");
12820                return false;
12821            }
12822
12823            // Reflect the rename internally
12824            codeFile = afterCodeFile;
12825            resourceFile = afterCodeFile;
12826
12827            // Reflect the rename in scanned details
12828            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12829            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12830                    afterCodeFile, pkg.baseCodePath));
12831            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12832                    afterCodeFile, pkg.splitCodePaths));
12833
12834            // Reflect the rename in app info
12835            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12836            pkg.setApplicationInfoCodePath(pkg.codePath);
12837            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12838            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12839            pkg.setApplicationInfoResourcePath(pkg.codePath);
12840            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12841            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12842
12843            return true;
12844        }
12845
12846        int doPostInstall(int status, int uid) {
12847            if (status != PackageManager.INSTALL_SUCCEEDED) {
12848                cleanUp();
12849            }
12850            return status;
12851        }
12852
12853        @Override
12854        String getCodePath() {
12855            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12856        }
12857
12858        @Override
12859        String getResourcePath() {
12860            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12861        }
12862
12863        private boolean cleanUp() {
12864            if (codeFile == null || !codeFile.exists()) {
12865                return false;
12866            }
12867
12868            removeCodePathLI(codeFile);
12869
12870            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
12871                resourceFile.delete();
12872            }
12873
12874            return true;
12875        }
12876
12877        void cleanUpResourcesLI() {
12878            // Try enumerating all code paths before deleting
12879            List<String> allCodePaths = Collections.EMPTY_LIST;
12880            if (codeFile != null && codeFile.exists()) {
12881                try {
12882                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12883                    allCodePaths = pkg.getAllCodePaths();
12884                } catch (PackageParserException e) {
12885                    // Ignored; we tried our best
12886                }
12887            }
12888
12889            cleanUp();
12890            removeDexFiles(allCodePaths, instructionSets);
12891        }
12892
12893        boolean doPostDeleteLI(boolean delete) {
12894            // XXX err, shouldn't we respect the delete flag?
12895            cleanUpResourcesLI();
12896            return true;
12897        }
12898    }
12899
12900    private boolean isAsecExternal(String cid) {
12901        final String asecPath = PackageHelper.getSdFilesystem(cid);
12902        return !asecPath.startsWith(mAsecInternalPath);
12903    }
12904
12905    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
12906            PackageManagerException {
12907        if (copyRet < 0) {
12908            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
12909                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
12910                throw new PackageManagerException(copyRet, message);
12911            }
12912        }
12913    }
12914
12915    /**
12916     * Extract the MountService "container ID" from the full code path of an
12917     * .apk.
12918     */
12919    static String cidFromCodePath(String fullCodePath) {
12920        int eidx = fullCodePath.lastIndexOf("/");
12921        String subStr1 = fullCodePath.substring(0, eidx);
12922        int sidx = subStr1.lastIndexOf("/");
12923        return subStr1.substring(sidx+1, eidx);
12924    }
12925
12926    /**
12927     * Logic to handle installation of ASEC applications, including copying and
12928     * renaming logic.
12929     */
12930    class AsecInstallArgs extends InstallArgs {
12931        static final String RES_FILE_NAME = "pkg.apk";
12932        static final String PUBLIC_RES_FILE_NAME = "res.zip";
12933
12934        String cid;
12935        String packagePath;
12936        String resourcePath;
12937
12938        /** New install */
12939        AsecInstallArgs(InstallParams params) {
12940            super(params.origin, params.move, params.observer, params.installFlags,
12941                    params.installerPackageName, params.volumeUuid,
12942                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12943                    params.grantedRuntimePermissions,
12944                    params.traceMethod, params.traceCookie);
12945        }
12946
12947        /** Existing install */
12948        AsecInstallArgs(String fullCodePath, String[] instructionSets,
12949                        boolean isExternal, boolean isForwardLocked) {
12950            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
12951                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12952                    instructionSets, null, null, null, 0);
12953            // Hackily pretend we're still looking at a full code path
12954            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
12955                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
12956            }
12957
12958            // Extract cid from fullCodePath
12959            int eidx = fullCodePath.lastIndexOf("/");
12960            String subStr1 = fullCodePath.substring(0, eidx);
12961            int sidx = subStr1.lastIndexOf("/");
12962            cid = subStr1.substring(sidx+1, eidx);
12963            setMountPath(subStr1);
12964        }
12965
12966        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
12967            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
12968                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12969                    instructionSets, null, null, null, 0);
12970            this.cid = cid;
12971            setMountPath(PackageHelper.getSdDir(cid));
12972        }
12973
12974        void createCopyFile() {
12975            cid = mInstallerService.allocateExternalStageCidLegacy();
12976        }
12977
12978        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12979            if (origin.staged && origin.cid != null) {
12980                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
12981                cid = origin.cid;
12982                setMountPath(PackageHelper.getSdDir(cid));
12983                return PackageManager.INSTALL_SUCCEEDED;
12984            }
12985
12986            if (temp) {
12987                createCopyFile();
12988            } else {
12989                /*
12990                 * Pre-emptively destroy the container since it's destroyed if
12991                 * copying fails due to it existing anyway.
12992                 */
12993                PackageHelper.destroySdDir(cid);
12994            }
12995
12996            final String newMountPath = imcs.copyPackageToContainer(
12997                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
12998                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
12999
13000            if (newMountPath != null) {
13001                setMountPath(newMountPath);
13002                return PackageManager.INSTALL_SUCCEEDED;
13003            } else {
13004                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13005            }
13006        }
13007
13008        @Override
13009        String getCodePath() {
13010            return packagePath;
13011        }
13012
13013        @Override
13014        String getResourcePath() {
13015            return resourcePath;
13016        }
13017
13018        int doPreInstall(int status) {
13019            if (status != PackageManager.INSTALL_SUCCEEDED) {
13020                // Destroy container
13021                PackageHelper.destroySdDir(cid);
13022            } else {
13023                boolean mounted = PackageHelper.isContainerMounted(cid);
13024                if (!mounted) {
13025                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13026                            Process.SYSTEM_UID);
13027                    if (newMountPath != null) {
13028                        setMountPath(newMountPath);
13029                    } else {
13030                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13031                    }
13032                }
13033            }
13034            return status;
13035        }
13036
13037        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13038            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13039            String newMountPath = null;
13040            if (PackageHelper.isContainerMounted(cid)) {
13041                // Unmount the container
13042                if (!PackageHelper.unMountSdDir(cid)) {
13043                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13044                    return false;
13045                }
13046            }
13047            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13048                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13049                        " which might be stale. Will try to clean up.");
13050                // Clean up the stale container and proceed to recreate.
13051                if (!PackageHelper.destroySdDir(newCacheId)) {
13052                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13053                    return false;
13054                }
13055                // Successfully cleaned up stale container. Try to rename again.
13056                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13057                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13058                            + " inspite of cleaning it up.");
13059                    return false;
13060                }
13061            }
13062            if (!PackageHelper.isContainerMounted(newCacheId)) {
13063                Slog.w(TAG, "Mounting container " + newCacheId);
13064                newMountPath = PackageHelper.mountSdDir(newCacheId,
13065                        getEncryptKey(), Process.SYSTEM_UID);
13066            } else {
13067                newMountPath = PackageHelper.getSdDir(newCacheId);
13068            }
13069            if (newMountPath == null) {
13070                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13071                return false;
13072            }
13073            Log.i(TAG, "Succesfully renamed " + cid +
13074                    " to " + newCacheId +
13075                    " at new path: " + newMountPath);
13076            cid = newCacheId;
13077
13078            final File beforeCodeFile = new File(packagePath);
13079            setMountPath(newMountPath);
13080            final File afterCodeFile = new File(packagePath);
13081
13082            // Reflect the rename in scanned details
13083            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13084            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13085                    afterCodeFile, pkg.baseCodePath));
13086            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13087                    afterCodeFile, pkg.splitCodePaths));
13088
13089            // Reflect the rename in app info
13090            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13091            pkg.setApplicationInfoCodePath(pkg.codePath);
13092            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13093            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13094            pkg.setApplicationInfoResourcePath(pkg.codePath);
13095            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13096            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13097
13098            return true;
13099        }
13100
13101        private void setMountPath(String mountPath) {
13102            final File mountFile = new File(mountPath);
13103
13104            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13105            if (monolithicFile.exists()) {
13106                packagePath = monolithicFile.getAbsolutePath();
13107                if (isFwdLocked()) {
13108                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13109                } else {
13110                    resourcePath = packagePath;
13111                }
13112            } else {
13113                packagePath = mountFile.getAbsolutePath();
13114                resourcePath = packagePath;
13115            }
13116        }
13117
13118        int doPostInstall(int status, int uid) {
13119            if (status != PackageManager.INSTALL_SUCCEEDED) {
13120                cleanUp();
13121            } else {
13122                final int groupOwner;
13123                final String protectedFile;
13124                if (isFwdLocked()) {
13125                    groupOwner = UserHandle.getSharedAppGid(uid);
13126                    protectedFile = RES_FILE_NAME;
13127                } else {
13128                    groupOwner = -1;
13129                    protectedFile = null;
13130                }
13131
13132                if (uid < Process.FIRST_APPLICATION_UID
13133                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13134                    Slog.e(TAG, "Failed to finalize " + cid);
13135                    PackageHelper.destroySdDir(cid);
13136                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13137                }
13138
13139                boolean mounted = PackageHelper.isContainerMounted(cid);
13140                if (!mounted) {
13141                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13142                }
13143            }
13144            return status;
13145        }
13146
13147        private void cleanUp() {
13148            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13149
13150            // Destroy secure container
13151            PackageHelper.destroySdDir(cid);
13152        }
13153
13154        private List<String> getAllCodePaths() {
13155            final File codeFile = new File(getCodePath());
13156            if (codeFile != null && codeFile.exists()) {
13157                try {
13158                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13159                    return pkg.getAllCodePaths();
13160                } catch (PackageParserException e) {
13161                    // Ignored; we tried our best
13162                }
13163            }
13164            return Collections.EMPTY_LIST;
13165        }
13166
13167        void cleanUpResourcesLI() {
13168            // Enumerate all code paths before deleting
13169            cleanUpResourcesLI(getAllCodePaths());
13170        }
13171
13172        private void cleanUpResourcesLI(List<String> allCodePaths) {
13173            cleanUp();
13174            removeDexFiles(allCodePaths, instructionSets);
13175        }
13176
13177        String getPackageName() {
13178            return getAsecPackageName(cid);
13179        }
13180
13181        boolean doPostDeleteLI(boolean delete) {
13182            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13183            final List<String> allCodePaths = getAllCodePaths();
13184            boolean mounted = PackageHelper.isContainerMounted(cid);
13185            if (mounted) {
13186                // Unmount first
13187                if (PackageHelper.unMountSdDir(cid)) {
13188                    mounted = false;
13189                }
13190            }
13191            if (!mounted && delete) {
13192                cleanUpResourcesLI(allCodePaths);
13193            }
13194            return !mounted;
13195        }
13196
13197        @Override
13198        int doPreCopy() {
13199            if (isFwdLocked()) {
13200                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13201                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13202                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13203                }
13204            }
13205
13206            return PackageManager.INSTALL_SUCCEEDED;
13207        }
13208
13209        @Override
13210        int doPostCopy(int uid) {
13211            if (isFwdLocked()) {
13212                if (uid < Process.FIRST_APPLICATION_UID
13213                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13214                                RES_FILE_NAME)) {
13215                    Slog.e(TAG, "Failed to finalize " + cid);
13216                    PackageHelper.destroySdDir(cid);
13217                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13218                }
13219            }
13220
13221            return PackageManager.INSTALL_SUCCEEDED;
13222        }
13223    }
13224
13225    /**
13226     * Logic to handle movement of existing installed applications.
13227     */
13228    class MoveInstallArgs extends InstallArgs {
13229        private File codeFile;
13230        private File resourceFile;
13231
13232        /** New install */
13233        MoveInstallArgs(InstallParams params) {
13234            super(params.origin, params.move, params.observer, params.installFlags,
13235                    params.installerPackageName, params.volumeUuid,
13236                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13237                    params.grantedRuntimePermissions,
13238                    params.traceMethod, params.traceCookie);
13239        }
13240
13241        int copyApk(IMediaContainerService imcs, boolean temp) {
13242            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13243                    + move.fromUuid + " to " + move.toUuid);
13244            synchronized (mInstaller) {
13245                try {
13246                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13247                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13248                } catch (InstallerException e) {
13249                    Slog.w(TAG, "Failed to move app", e);
13250                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13251                }
13252            }
13253
13254            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13255            resourceFile = codeFile;
13256            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13257
13258            return PackageManager.INSTALL_SUCCEEDED;
13259        }
13260
13261        int doPreInstall(int status) {
13262            if (status != PackageManager.INSTALL_SUCCEEDED) {
13263                cleanUp(move.toUuid);
13264            }
13265            return status;
13266        }
13267
13268        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13269            if (status != PackageManager.INSTALL_SUCCEEDED) {
13270                cleanUp(move.toUuid);
13271                return false;
13272            }
13273
13274            // Reflect the move in app info
13275            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13276            pkg.setApplicationInfoCodePath(pkg.codePath);
13277            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13278            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13279            pkg.setApplicationInfoResourcePath(pkg.codePath);
13280            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13281            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13282
13283            return true;
13284        }
13285
13286        int doPostInstall(int status, int uid) {
13287            if (status == PackageManager.INSTALL_SUCCEEDED) {
13288                cleanUp(move.fromUuid);
13289            } else {
13290                cleanUp(move.toUuid);
13291            }
13292            return status;
13293        }
13294
13295        @Override
13296        String getCodePath() {
13297            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13298        }
13299
13300        @Override
13301        String getResourcePath() {
13302            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13303        }
13304
13305        private boolean cleanUp(String volumeUuid) {
13306            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13307                    move.dataAppName);
13308            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13309            synchronized (mInstallLock) {
13310                // Clean up both app data and code
13311                removeDataDirsLI(volumeUuid, move.packageName);
13312                removeCodePathLI(codeFile);
13313            }
13314            return true;
13315        }
13316
13317        void cleanUpResourcesLI() {
13318            throw new UnsupportedOperationException();
13319        }
13320
13321        boolean doPostDeleteLI(boolean delete) {
13322            throw new UnsupportedOperationException();
13323        }
13324    }
13325
13326    static String getAsecPackageName(String packageCid) {
13327        int idx = packageCid.lastIndexOf("-");
13328        if (idx == -1) {
13329            return packageCid;
13330        }
13331        return packageCid.substring(0, idx);
13332    }
13333
13334    // Utility method used to create code paths based on package name and available index.
13335    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13336        String idxStr = "";
13337        int idx = 1;
13338        // Fall back to default value of idx=1 if prefix is not
13339        // part of oldCodePath
13340        if (oldCodePath != null) {
13341            String subStr = oldCodePath;
13342            // Drop the suffix right away
13343            if (suffix != null && subStr.endsWith(suffix)) {
13344                subStr = subStr.substring(0, subStr.length() - suffix.length());
13345            }
13346            // If oldCodePath already contains prefix find out the
13347            // ending index to either increment or decrement.
13348            int sidx = subStr.lastIndexOf(prefix);
13349            if (sidx != -1) {
13350                subStr = subStr.substring(sidx + prefix.length());
13351                if (subStr != null) {
13352                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13353                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13354                    }
13355                    try {
13356                        idx = Integer.parseInt(subStr);
13357                        if (idx <= 1) {
13358                            idx++;
13359                        } else {
13360                            idx--;
13361                        }
13362                    } catch(NumberFormatException e) {
13363                    }
13364                }
13365            }
13366        }
13367        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13368        return prefix + idxStr;
13369    }
13370
13371    private File getNextCodePath(File targetDir, String packageName) {
13372        int suffix = 1;
13373        File result;
13374        do {
13375            result = new File(targetDir, packageName + "-" + suffix);
13376            suffix++;
13377        } while (result.exists());
13378        return result;
13379    }
13380
13381    // Utility method that returns the relative package path with respect
13382    // to the installation directory. Like say for /data/data/com.test-1.apk
13383    // string com.test-1 is returned.
13384    static String deriveCodePathName(String codePath) {
13385        if (codePath == null) {
13386            return null;
13387        }
13388        final File codeFile = new File(codePath);
13389        final String name = codeFile.getName();
13390        if (codeFile.isDirectory()) {
13391            return name;
13392        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13393            final int lastDot = name.lastIndexOf('.');
13394            return name.substring(0, lastDot);
13395        } else {
13396            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13397            return null;
13398        }
13399    }
13400
13401    static class PackageInstalledInfo {
13402        String name;
13403        int uid;
13404        // The set of users that originally had this package installed.
13405        int[] origUsers;
13406        // The set of users that now have this package installed.
13407        int[] newUsers;
13408        PackageParser.Package pkg;
13409        int returnCode;
13410        String returnMsg;
13411        PackageRemovedInfo removedInfo;
13412        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13413
13414        public void setError(int code, String msg) {
13415            setReturnCode(code);
13416            setReturnMessage(msg);
13417            Slog.w(TAG, msg);
13418        }
13419
13420        public void setError(String msg, PackageParserException e) {
13421            setReturnCode(e.error);
13422            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13423            Slog.w(TAG, msg, e);
13424        }
13425
13426        public void setError(String msg, PackageManagerException e) {
13427            returnCode = e.error;
13428            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13429            Slog.w(TAG, msg, e);
13430        }
13431
13432        public void setReturnCode(int returnCode) {
13433            this.returnCode = returnCode;
13434            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13435            for (int i = 0; i < childCount; i++) {
13436                addedChildPackages.valueAt(i).returnCode = returnCode;
13437            }
13438        }
13439
13440        private void setReturnMessage(String returnMsg) {
13441            this.returnMsg = returnMsg;
13442            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13443            for (int i = 0; i < childCount; i++) {
13444                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13445            }
13446        }
13447
13448        // In some error cases we want to convey more info back to the observer
13449        String origPackage;
13450        String origPermission;
13451    }
13452
13453    /*
13454     * Install a non-existing package.
13455     */
13456    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
13457            UserHandle user, String installerPackageName, String volumeUuid,
13458            PackageInstalledInfo res) {
13459        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13460
13461        // Remember this for later, in case we need to rollback this install
13462        String pkgName = pkg.packageName;
13463
13464        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13465
13466        synchronized(mPackages) {
13467            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13468                // A package with the same name is already installed, though
13469                // it has been renamed to an older name.  The package we
13470                // are trying to install should be installed as an update to
13471                // the existing one, but that has not been requested, so bail.
13472                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13473                        + " without first uninstalling package running as "
13474                        + mSettings.mRenamedPackages.get(pkgName));
13475                return;
13476            }
13477            if (mPackages.containsKey(pkgName)) {
13478                // Don't allow installation over an existing package with the same name.
13479                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13480                        + " without first uninstalling.");
13481                return;
13482            }
13483        }
13484
13485        try {
13486            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
13487                    System.currentTimeMillis(), user);
13488
13489            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13490
13491            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13492                prepareAppDataAfterInstall(newPackage);
13493
13494            } else {
13495                // Remove package from internal structures, but keep around any
13496                // data that might have already existed
13497                deletePackageLI(pkgName, UserHandle.ALL, false, null,
13498                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13499            }
13500        } catch (PackageManagerException e) {
13501            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13502        }
13503
13504        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13505    }
13506
13507    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13508        // Can't rotate keys during boot or if sharedUser.
13509        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13510                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
13511            return false;
13512        }
13513        // app is using upgradeKeySets; make sure all are valid
13514        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13515        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
13516        for (int i = 0; i < upgradeKeySets.length; i++) {
13517            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
13518                Slog.wtf(TAG, "Package "
13519                         + (oldPs.name != null ? oldPs.name : "<null>")
13520                         + " contains upgrade-key-set reference to unknown key-set: "
13521                         + upgradeKeySets[i]
13522                         + " reverting to signatures check.");
13523                return false;
13524            }
13525        }
13526        return true;
13527    }
13528
13529    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
13530        // Upgrade keysets are being used.  Determine if new package has a superset of the
13531        // required keys.
13532        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
13533        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13534        for (int i = 0; i < upgradeKeySets.length; i++) {
13535            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
13536            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
13537                return true;
13538            }
13539        }
13540        return false;
13541    }
13542
13543    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
13544            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
13545        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
13546
13547        final PackageParser.Package oldPackage;
13548        final String pkgName = pkg.packageName;
13549        final int[] allUsers;
13550        final boolean weFroze;
13551
13552        // First find the old package info and check signatures
13553        synchronized(mPackages) {
13554            oldPackage = mPackages.get(pkgName);
13555            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
13556            if (isEphemeral && !oldIsEphemeral) {
13557                // can't downgrade from full to ephemeral
13558                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
13559                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13560                return;
13561            }
13562            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
13563            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13564            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13565                if (!checkUpgradeKeySetLP(ps, pkg)) {
13566                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13567                            "New package not signed by keys specified by upgrade-keysets: "
13568                                    + pkgName);
13569                    return;
13570                }
13571            } else {
13572                // default to original signature matching
13573                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
13574                        != PackageManager.SIGNATURE_MATCH) {
13575                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13576                            "New package has a different signature: " + pkgName);
13577                    return;
13578                }
13579            }
13580
13581            // In case of rollback, remember per-user/profile install state
13582            allUsers = sUserManager.getUserIds();
13583
13584            // Mark the app as frozen to prevent launching during the upgrade
13585            // process, and then kill all running instances
13586            if (!ps.frozen) {
13587                ps.frozen = true;
13588                weFroze = true;
13589            } else {
13590                weFroze = false;
13591            }
13592        }
13593
13594        try {
13595            replacePackageDirtyLI(pkg, oldPackage, parseFlags, scanFlags, user, allUsers,
13596                    installerPackageName, res);
13597        } finally {
13598            // Regardless of success or failure of upgrade steps above, always
13599            // unfreeze the package if we froze it
13600            if (weFroze) {
13601                unfreezePackage(pkgName);
13602            }
13603        }
13604    }
13605
13606    private void replacePackageDirtyLI(PackageParser.Package pkg, PackageParser.Package oldPackage,
13607            int parseFlags, int scanFlags, UserHandle user, int[] allUsers,
13608            String installerPackageName, PackageInstalledInfo res) {
13609        // Update what is removed
13610        res.removedInfo = new PackageRemovedInfo();
13611        res.removedInfo.uid = oldPackage.applicationInfo.uid;
13612        res.removedInfo.removedPackage = oldPackage.packageName;
13613        res.removedInfo.isUpdate = true;
13614        final int childCount = (oldPackage.childPackages != null)
13615                ? oldPackage.childPackages.size() : 0;
13616        for (int i = 0; i < childCount; i++) {
13617            boolean childPackageUpdated = false;
13618            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
13619            if (res.addedChildPackages != null) {
13620                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13621                if (childRes != null) {
13622                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
13623                    childRes.removedInfo.removedPackage = childPkg.packageName;
13624                    childRes.removedInfo.isUpdate = true;
13625                    childPackageUpdated = true;
13626                }
13627            }
13628            if (!childPackageUpdated) {
13629                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
13630                childRemovedRes.removedPackage = childPkg.packageName;
13631                childRemovedRes.isUpdate = false;
13632                childRemovedRes.dataRemoved = true;
13633                synchronized (mPackages) {
13634                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13635                    if (childPs != null) {
13636                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
13637                    }
13638                }
13639                if (res.removedInfo.removedChildPackages == null) {
13640                    res.removedInfo.removedChildPackages = new ArrayMap<>();
13641                }
13642                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
13643            }
13644        }
13645
13646        boolean sysPkg = (isSystemApp(oldPackage));
13647        if (sysPkg) {
13648            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13649                    user, allUsers, installerPackageName, res);
13650        } else {
13651            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13652                    user, allUsers, installerPackageName, res);
13653        }
13654    }
13655
13656    public List<String> getPreviousCodePaths(String packageName) {
13657        final PackageSetting ps = mSettings.mPackages.get(packageName);
13658        final List<String> result = new ArrayList<String>();
13659        if (ps != null && ps.oldCodePaths != null) {
13660            result.addAll(ps.oldCodePaths);
13661        }
13662        return result;
13663    }
13664
13665    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
13666            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13667            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13668        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
13669                + deletedPackage);
13670
13671        String pkgName = deletedPackage.packageName;
13672        boolean deletedPkg = true;
13673        boolean addedPkg = false;
13674        boolean updatedSettings = false;
13675        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
13676        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
13677                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
13678
13679        final long origUpdateTime = (pkg.mExtras != null)
13680                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
13681
13682        // First delete the existing package while retaining the data directory
13683        if (!deletePackageLI(pkgName, null, true, allUsers, deleteFlags,
13684                res.removedInfo, true, pkg)) {
13685            // If the existing package wasn't successfully deleted
13686            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
13687            deletedPkg = false;
13688        } else {
13689            // Successfully deleted the old package; proceed with replace.
13690
13691            // If deleted package lived in a container, give users a chance to
13692            // relinquish resources before killing.
13693            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
13694                if (DEBUG_INSTALL) {
13695                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
13696                }
13697                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
13698                final ArrayList<String> pkgList = new ArrayList<String>(1);
13699                pkgList.add(deletedPackage.applicationInfo.packageName);
13700                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
13701            }
13702
13703            deleteCodeCacheDirsLI(pkg);
13704            deleteProfilesLI(pkg, /*destroy*/ false);
13705
13706            try {
13707                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
13708                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
13709                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13710
13711                // Update the in-memory copy of the previous code paths.
13712                PackageSetting ps = mSettings.mPackages.get(pkgName);
13713                if (!killApp) {
13714                    if (ps.oldCodePaths == null) {
13715                        ps.oldCodePaths = new ArraySet<>();
13716                    }
13717                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
13718                    if (deletedPackage.splitCodePaths != null) {
13719                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
13720                    }
13721                } else {
13722                    ps.oldCodePaths = null;
13723                }
13724                if (ps.childPackageNames != null) {
13725                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
13726                        final String childPkgName = ps.childPackageNames.get(i);
13727                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
13728                        childPs.oldCodePaths = ps.oldCodePaths;
13729                    }
13730                }
13731                prepareAppDataAfterInstall(newPackage);
13732                addedPkg = true;
13733            } catch (PackageManagerException e) {
13734                res.setError("Package couldn't be installed in " + pkg.codePath, e);
13735            }
13736        }
13737
13738        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13739            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
13740
13741            // Revert all internal state mutations and added folders for the failed install
13742            if (addedPkg) {
13743                deletePackageLI(pkgName, null, true, allUsers, deleteFlags,
13744                        res.removedInfo, true, null);
13745            }
13746
13747            // Restore the old package
13748            if (deletedPkg) {
13749                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
13750                File restoreFile = new File(deletedPackage.codePath);
13751                // Parse old package
13752                boolean oldExternal = isExternal(deletedPackage);
13753                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
13754                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
13755                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
13756                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
13757                try {
13758                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
13759                            null);
13760                } catch (PackageManagerException e) {
13761                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
13762                            + e.getMessage());
13763                    return;
13764                }
13765
13766                synchronized (mPackages) {
13767                    // Ensure the installer package name up to date
13768                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13769
13770                    // Update permissions for restored package
13771                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13772
13773                    mSettings.writeLPr();
13774                }
13775
13776                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
13777            }
13778        } else {
13779            synchronized (mPackages) {
13780                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
13781                if (ps != null) {
13782                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
13783                    if (res.removedInfo.removedChildPackages != null) {
13784                        final int childCount = res.removedInfo.removedChildPackages.size();
13785                        // Iterate in reverse as we may modify the collection
13786                        for (int i = childCount - 1; i >= 0; i--) {
13787                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
13788                            if (res.addedChildPackages.containsKey(childPackageName)) {
13789                                res.removedInfo.removedChildPackages.removeAt(i);
13790                            } else {
13791                                PackageRemovedInfo childInfo = res.removedInfo
13792                                        .removedChildPackages.valueAt(i);
13793                                childInfo.removedForAllUsers = mPackages.get(
13794                                        childInfo.removedPackage) == null;
13795                            }
13796                        }
13797                    }
13798                }
13799            }
13800        }
13801    }
13802
13803    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
13804            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13805            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13806        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
13807                + ", old=" + deletedPackage);
13808
13809        final boolean disabledSystem;
13810
13811        // Set the system/privileged flags as needed
13812        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
13813        if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
13814                != 0) {
13815            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13816        }
13817
13818        // Kill package processes including services, providers, etc.
13819        killPackage(deletedPackage, "replace sys pkg");
13820
13821        // Remove existing system package
13822        removePackageLI(deletedPackage, true);
13823
13824        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
13825        if (!disabledSystem) {
13826            // We didn't need to disable the .apk as a current system package,
13827            // which means we are replacing another update that is already
13828            // installed.  We need to make sure to delete the older one's .apk.
13829            res.removedInfo.args = createInstallArgsForExisting(0,
13830                    deletedPackage.applicationInfo.getCodePath(),
13831                    deletedPackage.applicationInfo.getResourcePath(),
13832                    getAppDexInstructionSets(deletedPackage.applicationInfo));
13833        } else {
13834            res.removedInfo.args = null;
13835        }
13836
13837        // Successfully disabled the old package. Now proceed with re-installation
13838        deleteCodeCacheDirsLI(pkg);
13839        deleteProfilesLI(pkg, /*destroy*/ false);
13840
13841        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13842        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
13843                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
13844
13845        PackageParser.Package newPackage = null;
13846        try {
13847            // Add the package to the internal data structures
13848            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
13849
13850            // Set the update and install times
13851            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
13852            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
13853                    System.currentTimeMillis());
13854
13855            // Check for shared user id changes
13856            String invalidPackageName = getParentOrChildPackageChangedSharedUser(
13857                    deletedPackage, newPackage);
13858            if (invalidPackageName != null) {
13859                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13860                        "Forbidding shared user change from " + deletedPkgSetting.sharedUser
13861                                + " to " + invalidPackageName);
13862            }
13863
13864            // Update the package dynamic state if succeeded
13865            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13866                // Now that the install succeeded make sure we remove data
13867                // directories for any child package the update removed.
13868                final int deletedChildCount = (deletedPackage.childPackages != null)
13869                        ? deletedPackage.childPackages.size() : 0;
13870                final int newChildCount = (newPackage.childPackages != null)
13871                        ? newPackage.childPackages.size() : 0;
13872                for (int i = 0; i < deletedChildCount; i++) {
13873                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
13874                    boolean childPackageDeleted = true;
13875                    for (int j = 0; j < newChildCount; j++) {
13876                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
13877                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
13878                            childPackageDeleted = false;
13879                            break;
13880                        }
13881                    }
13882                    if (childPackageDeleted) {
13883                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
13884                                deletedChildPkg.packageName);
13885                        if (ps != null && res.removedInfo.removedChildPackages != null) {
13886                            PackageRemovedInfo removedChildRes = res.removedInfo
13887                                    .removedChildPackages.get(deletedChildPkg.packageName);
13888                            removePackageDataLI(ps, allUsers, removedChildRes, 0, false);
13889                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
13890                        }
13891                    }
13892                }
13893
13894                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13895                prepareAppDataAfterInstall(newPackage);
13896            }
13897        } catch (PackageManagerException e) {
13898            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
13899            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13900        }
13901
13902        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13903            // Re installation failed. Restore old information
13904            // Remove new pkg information
13905            if (newPackage != null) {
13906                removeInstalledPackageLI(newPackage, true);
13907            }
13908            // Add back the old system package
13909            try {
13910                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
13911            } catch (PackageManagerException e) {
13912                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
13913            }
13914
13915            synchronized (mPackages) {
13916                if (disabledSystem) {
13917                    enableSystemPackageLPw(deletedPackage);
13918                }
13919
13920                // Ensure the installer package name up to date
13921                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13922
13923                // Update permissions for restored package
13924                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13925
13926                mSettings.writeLPr();
13927            }
13928
13929            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
13930                    + " after failed upgrade");
13931        }
13932    }
13933
13934    /**
13935     * Checks whether the parent or any of the child packages have a change shared
13936     * user. For a package to be a valid update the shred users of the parent and
13937     * the children should match. We may later support changing child shared users.
13938     * @param oldPkg The updated package.
13939     * @param newPkg The update package.
13940     * @return The shared user that change between the versions.
13941     */
13942    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
13943            PackageParser.Package newPkg) {
13944        // Check parent shared user
13945        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
13946            return newPkg.packageName;
13947        }
13948        // Check child shared users
13949        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13950        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
13951        for (int i = 0; i < newChildCount; i++) {
13952            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
13953            // If this child was present, did it have the same shared user?
13954            for (int j = 0; j < oldChildCount; j++) {
13955                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
13956                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
13957                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
13958                    return newChildPkg.packageName;
13959                }
13960            }
13961        }
13962        return null;
13963    }
13964
13965    private void removeNativeBinariesLI(PackageSetting ps) {
13966        // Remove the lib path for the parent package
13967        if (ps != null) {
13968            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13969            // Remove the lib path for the child packages
13970            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
13971            for (int i = 0; i < childCount; i++) {
13972                PackageSetting childPs = null;
13973                synchronized (mPackages) {
13974                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
13975                }
13976                if (childPs != null) {
13977                    NativeLibraryHelper.removeNativeBinariesLI(childPs
13978                            .legacyNativeLibraryPathString);
13979                }
13980            }
13981        }
13982    }
13983
13984    private void enableSystemPackageLPw(PackageParser.Package pkg) {
13985        // Enable the parent package
13986        mSettings.enableSystemPackageLPw(pkg.packageName);
13987        // Enable the child packages
13988        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13989        for (int i = 0; i < childCount; i++) {
13990            PackageParser.Package childPkg = pkg.childPackages.get(i);
13991            mSettings.enableSystemPackageLPw(childPkg.packageName);
13992        }
13993    }
13994
13995    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
13996            PackageParser.Package newPkg) {
13997        // Disable the parent package (parent always replaced)
13998        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
13999        // Disable the child packages
14000        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14001        for (int i = 0; i < childCount; i++) {
14002            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14003            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14004            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14005        }
14006        return disabled;
14007    }
14008
14009    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14010            String installerPackageName) {
14011        // Enable the parent package
14012        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14013        // Enable the child packages
14014        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14015        for (int i = 0; i < childCount; i++) {
14016            PackageParser.Package childPkg = pkg.childPackages.get(i);
14017            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14018        }
14019    }
14020
14021    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14022        // Collect all used permissions in the UID
14023        ArraySet<String> usedPermissions = new ArraySet<>();
14024        final int packageCount = su.packages.size();
14025        for (int i = 0; i < packageCount; i++) {
14026            PackageSetting ps = su.packages.valueAt(i);
14027            if (ps.pkg == null) {
14028                continue;
14029            }
14030            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14031            for (int j = 0; j < requestedPermCount; j++) {
14032                String permission = ps.pkg.requestedPermissions.get(j);
14033                BasePermission bp = mSettings.mPermissions.get(permission);
14034                if (bp != null) {
14035                    usedPermissions.add(permission);
14036                }
14037            }
14038        }
14039
14040        PermissionsState permissionsState = su.getPermissionsState();
14041        // Prune install permissions
14042        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14043        final int installPermCount = installPermStates.size();
14044        for (int i = installPermCount - 1; i >= 0;  i--) {
14045            PermissionState permissionState = installPermStates.get(i);
14046            if (!usedPermissions.contains(permissionState.getName())) {
14047                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14048                if (bp != null) {
14049                    permissionsState.revokeInstallPermission(bp);
14050                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14051                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14052                }
14053            }
14054        }
14055
14056        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14057
14058        // Prune runtime permissions
14059        for (int userId : allUserIds) {
14060            List<PermissionState> runtimePermStates = permissionsState
14061                    .getRuntimePermissionStates(userId);
14062            final int runtimePermCount = runtimePermStates.size();
14063            for (int i = runtimePermCount - 1; i >= 0; i--) {
14064                PermissionState permissionState = runtimePermStates.get(i);
14065                if (!usedPermissions.contains(permissionState.getName())) {
14066                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14067                    if (bp != null) {
14068                        permissionsState.revokeRuntimePermission(bp, userId);
14069                        permissionsState.updatePermissionFlags(bp, userId,
14070                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14071                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14072                                runtimePermissionChangedUserIds, userId);
14073                    }
14074                }
14075            }
14076        }
14077
14078        return runtimePermissionChangedUserIds;
14079    }
14080
14081    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14082            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14083        // Update the parent package setting
14084        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14085                res, user);
14086        // Update the child packages setting
14087        final int childCount = (newPackage.childPackages != null)
14088                ? newPackage.childPackages.size() : 0;
14089        for (int i = 0; i < childCount; i++) {
14090            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14091            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14092            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14093                    childRes.origUsers, childRes, user);
14094        }
14095    }
14096
14097    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14098            String installerPackageName, int[] allUsers, int[] installedForUsers,
14099            PackageInstalledInfo res, UserHandle user) {
14100        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14101
14102        String pkgName = newPackage.packageName;
14103        synchronized (mPackages) {
14104            //write settings. the installStatus will be incomplete at this stage.
14105            //note that the new package setting would have already been
14106            //added to mPackages. It hasn't been persisted yet.
14107            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14108            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14109            mSettings.writeLPr();
14110            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14111        }
14112
14113        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14114        synchronized (mPackages) {
14115            updatePermissionsLPw(newPackage.packageName, newPackage,
14116                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14117                            ? UPDATE_PERMISSIONS_ALL : 0));
14118            // For system-bundled packages, we assume that installing an upgraded version
14119            // of the package implies that the user actually wants to run that new code,
14120            // so we enable the package.
14121            PackageSetting ps = mSettings.mPackages.get(pkgName);
14122            final int userId = user.getIdentifier();
14123            if (ps != null) {
14124                if (isSystemApp(newPackage)) {
14125                    if (DEBUG_INSTALL) {
14126                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14127                    }
14128                    // Enable system package for requested users
14129                    if (res.origUsers != null) {
14130                        for (int origUserId : res.origUsers) {
14131                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14132                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14133                                        origUserId, installerPackageName);
14134                            }
14135                        }
14136                    }
14137                    // Also convey the prior install/uninstall state
14138                    if (allUsers != null && installedForUsers != null) {
14139                        for (int currentUserId : allUsers) {
14140                            final boolean installed = ArrayUtils.contains(
14141                                    installedForUsers, currentUserId);
14142                            if (DEBUG_INSTALL) {
14143                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14144                            }
14145                            ps.setInstalled(installed, currentUserId);
14146                        }
14147                        // these install state changes will be persisted in the
14148                        // upcoming call to mSettings.writeLPr().
14149                    }
14150                }
14151                // It's implied that when a user requests installation, they want the app to be
14152                // installed and enabled.
14153                if (userId != UserHandle.USER_ALL) {
14154                    ps.setInstalled(true, userId);
14155                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14156                }
14157            }
14158            res.name = pkgName;
14159            res.uid = newPackage.applicationInfo.uid;
14160            res.pkg = newPackage;
14161            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14162            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14163            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14164            //to update install status
14165            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14166            mSettings.writeLPr();
14167            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14168        }
14169
14170        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14171    }
14172
14173    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14174        try {
14175            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14176            installPackageLI(args, res);
14177        } finally {
14178            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14179        }
14180    }
14181
14182    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14183        final int installFlags = args.installFlags;
14184        final String installerPackageName = args.installerPackageName;
14185        final String volumeUuid = args.volumeUuid;
14186        final File tmpPackageFile = new File(args.getCodePath());
14187        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14188        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14189                || (args.volumeUuid != null));
14190        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14191        boolean replace = false;
14192        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14193        if (args.move != null) {
14194            // moving a complete application; perform an initial scan on the new install location
14195            scanFlags |= SCAN_INITIAL;
14196        }
14197        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14198            scanFlags |= SCAN_DONT_KILL_APP;
14199        }
14200
14201        // Result object to be returned
14202        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14203
14204        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14205
14206        // Sanity check
14207        if (ephemeral && (forwardLocked || onExternal)) {
14208            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14209                    + " external=" + onExternal);
14210            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14211            return;
14212        }
14213
14214        // Retrieve PackageSettings and parse package
14215        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14216                | PackageParser.PARSE_ENFORCE_CODE
14217                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14218                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14219                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
14220        PackageParser pp = new PackageParser();
14221        pp.setSeparateProcesses(mSeparateProcesses);
14222        pp.setDisplayMetrics(mMetrics);
14223
14224        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14225        final PackageParser.Package pkg;
14226        try {
14227            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14228        } catch (PackageParserException e) {
14229            res.setError("Failed parse during installPackageLI", e);
14230            return;
14231        } finally {
14232            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14233        }
14234
14235        // If we are installing a clustered package add results for the children
14236        if (pkg.childPackages != null) {
14237            synchronized (mPackages) {
14238                final int childCount = pkg.childPackages.size();
14239                for (int i = 0; i < childCount; i++) {
14240                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14241                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14242                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14243                    childRes.pkg = childPkg;
14244                    childRes.name = childPkg.packageName;
14245                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14246                    if (childPs != null) {
14247                        childRes.origUsers = childPs.queryInstalledUsers(
14248                                sUserManager.getUserIds(), true);
14249                    }
14250                    if ((mPackages.containsKey(childPkg.packageName))) {
14251                        childRes.removedInfo = new PackageRemovedInfo();
14252                        childRes.removedInfo.removedPackage = childPkg.packageName;
14253                    }
14254                    if (res.addedChildPackages == null) {
14255                        res.addedChildPackages = new ArrayMap<>();
14256                    }
14257                    res.addedChildPackages.put(childPkg.packageName, childRes);
14258                }
14259            }
14260        }
14261
14262        // If package doesn't declare API override, mark that we have an install
14263        // time CPU ABI override.
14264        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14265            pkg.cpuAbiOverride = args.abiOverride;
14266        }
14267
14268        String pkgName = res.name = pkg.packageName;
14269        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14270            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14271                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14272                return;
14273            }
14274        }
14275
14276        try {
14277            PackageParser.collectCertificates(pkg, parseFlags);
14278        } catch (PackageParserException e) {
14279            res.setError("Failed collect during installPackageLI", e);
14280            return;
14281        }
14282
14283        // Get rid of all references to package scan path via parser.
14284        pp = null;
14285        String oldCodePath = null;
14286        boolean systemApp = false;
14287        synchronized (mPackages) {
14288            // Check if installing already existing package
14289            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14290                String oldName = mSettings.mRenamedPackages.get(pkgName);
14291                if (pkg.mOriginalPackages != null
14292                        && pkg.mOriginalPackages.contains(oldName)
14293                        && mPackages.containsKey(oldName)) {
14294                    // This package is derived from an original package,
14295                    // and this device has been updating from that original
14296                    // name.  We must continue using the original name, so
14297                    // rename the new package here.
14298                    pkg.setPackageName(oldName);
14299                    pkgName = pkg.packageName;
14300                    replace = true;
14301                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14302                            + oldName + " pkgName=" + pkgName);
14303                } else if (mPackages.containsKey(pkgName)) {
14304                    // This package, under its official name, already exists
14305                    // on the device; we should replace it.
14306                    replace = true;
14307                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14308                }
14309
14310                // Child packages are installed through the parent package
14311                if (pkg.parentPackage != null) {
14312                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14313                            "Package " + pkg.packageName + " is child of package "
14314                                    + pkg.parentPackage.parentPackage + ". Child packages "
14315                                    + "can be updated only through the parent package.");
14316                    return;
14317                }
14318
14319                if (replace) {
14320                    // Prevent apps opting out from runtime permissions
14321                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14322                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14323                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14324                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14325                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14326                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14327                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14328                                        + " doesn't support runtime permissions but the old"
14329                                        + " target SDK " + oldTargetSdk + " does.");
14330                        return;
14331                    }
14332
14333                    // Prevent installing of child packages
14334                    if (oldPackage.parentPackage != null) {
14335                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14336                                "Package " + pkg.packageName + " is child of package "
14337                                        + oldPackage.parentPackage + ". Child packages "
14338                                        + "can be updated only through the parent package.");
14339                        return;
14340                    }
14341                }
14342            }
14343
14344            PackageSetting ps = mSettings.mPackages.get(pkgName);
14345            if (ps != null) {
14346                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14347
14348                // Quick sanity check that we're signed correctly if updating;
14349                // we'll check this again later when scanning, but we want to
14350                // bail early here before tripping over redefined permissions.
14351                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14352                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14353                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14354                                + pkg.packageName + " upgrade keys do not match the "
14355                                + "previously installed version");
14356                        return;
14357                    }
14358                } else {
14359                    try {
14360                        verifySignaturesLP(ps, pkg);
14361                    } catch (PackageManagerException e) {
14362                        res.setError(e.error, e.getMessage());
14363                        return;
14364                    }
14365                }
14366
14367                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14368                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14369                    systemApp = (ps.pkg.applicationInfo.flags &
14370                            ApplicationInfo.FLAG_SYSTEM) != 0;
14371                }
14372                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14373            }
14374
14375            // Check whether the newly-scanned package wants to define an already-defined perm
14376            int N = pkg.permissions.size();
14377            for (int i = N-1; i >= 0; i--) {
14378                PackageParser.Permission perm = pkg.permissions.get(i);
14379                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14380                if (bp != null) {
14381                    // If the defining package is signed with our cert, it's okay.  This
14382                    // also includes the "updating the same package" case, of course.
14383                    // "updating same package" could also involve key-rotation.
14384                    final boolean sigsOk;
14385                    if (bp.sourcePackage.equals(pkg.packageName)
14386                            && (bp.packageSetting instanceof PackageSetting)
14387                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14388                                    scanFlags))) {
14389                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14390                    } else {
14391                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14392                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14393                    }
14394                    if (!sigsOk) {
14395                        // If the owning package is the system itself, we log but allow
14396                        // install to proceed; we fail the install on all other permission
14397                        // redefinitions.
14398                        if (!bp.sourcePackage.equals("android")) {
14399                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14400                                    + pkg.packageName + " attempting to redeclare permission "
14401                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14402                            res.origPermission = perm.info.name;
14403                            res.origPackage = bp.sourcePackage;
14404                            return;
14405                        } else {
14406                            Slog.w(TAG, "Package " + pkg.packageName
14407                                    + " attempting to redeclare system permission "
14408                                    + perm.info.name + "; ignoring new declaration");
14409                            pkg.permissions.remove(i);
14410                        }
14411                    }
14412                }
14413            }
14414        }
14415
14416        if (systemApp) {
14417            if (onExternal) {
14418                // Abort update; system app can't be replaced with app on sdcard
14419                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14420                        "Cannot install updates to system apps on sdcard");
14421                return;
14422            } else if (ephemeral) {
14423                // Abort update; system app can't be replaced with an ephemeral app
14424                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14425                        "Cannot update a system app with an ephemeral app");
14426                return;
14427            }
14428        }
14429
14430        if (args.move != null) {
14431            // We did an in-place move, so dex is ready to roll
14432            scanFlags |= SCAN_NO_DEX;
14433            scanFlags |= SCAN_MOVE;
14434
14435            synchronized (mPackages) {
14436                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14437                if (ps == null) {
14438                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
14439                            "Missing settings for moved package " + pkgName);
14440                }
14441
14442                // We moved the entire application as-is, so bring over the
14443                // previously derived ABI information.
14444                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
14445                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
14446            }
14447
14448        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
14449            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
14450            scanFlags |= SCAN_NO_DEX;
14451
14452            try {
14453                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
14454                    args.abiOverride : pkg.cpuAbiOverride);
14455                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
14456                        true /* extract libs */);
14457            } catch (PackageManagerException pme) {
14458                Slog.e(TAG, "Error deriving application ABI", pme);
14459                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
14460                return;
14461            }
14462
14463
14464            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
14465            // Do not run PackageDexOptimizer through the local performDexOpt
14466            // method because `pkg` is not in `mPackages` yet.
14467            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
14468                    false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL));
14469            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14470            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
14471                String msg = "Extracking package failed for " + pkgName;
14472                res.setError(INSTALL_FAILED_DEXOPT, msg);
14473                return;
14474            }
14475        }
14476
14477        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
14478            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
14479            return;
14480        }
14481
14482        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
14483
14484        if (replace) {
14485            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
14486                    installerPackageName, res);
14487        } else {
14488            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
14489                    args.user, installerPackageName, volumeUuid, res);
14490        }
14491        synchronized (mPackages) {
14492            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14493            if (ps != null) {
14494                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14495            }
14496
14497            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14498            for (int i = 0; i < childCount; i++) {
14499                PackageParser.Package childPkg = pkg.childPackages.get(i);
14500                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14501                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14502                if (childPs != null) {
14503                    childRes.newUsers = childPs.queryInstalledUsers(
14504                            sUserManager.getUserIds(), true);
14505                }
14506            }
14507        }
14508    }
14509
14510    private void startIntentFilterVerifications(int userId, boolean replacing,
14511            PackageParser.Package pkg) {
14512        if (mIntentFilterVerifierComponent == null) {
14513            Slog.w(TAG, "No IntentFilter verification will not be done as "
14514                    + "there is no IntentFilterVerifier available!");
14515            return;
14516        }
14517
14518        final int verifierUid = getPackageUid(
14519                mIntentFilterVerifierComponent.getPackageName(),
14520                MATCH_DEBUG_TRIAGED_MISSING,
14521                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
14522
14523        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14524        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
14525        mHandler.sendMessage(msg);
14526
14527        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14528        for (int i = 0; i < childCount; i++) {
14529            PackageParser.Package childPkg = pkg.childPackages.get(i);
14530            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14531            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
14532            mHandler.sendMessage(msg);
14533        }
14534    }
14535
14536    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
14537            PackageParser.Package pkg) {
14538        int size = pkg.activities.size();
14539        if (size == 0) {
14540            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14541                    "No activity, so no need to verify any IntentFilter!");
14542            return;
14543        }
14544
14545        final boolean hasDomainURLs = hasDomainURLs(pkg);
14546        if (!hasDomainURLs) {
14547            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14548                    "No domain URLs, so no need to verify any IntentFilter!");
14549            return;
14550        }
14551
14552        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
14553                + " if any IntentFilter from the " + size
14554                + " Activities needs verification ...");
14555
14556        int count = 0;
14557        final String packageName = pkg.packageName;
14558
14559        synchronized (mPackages) {
14560            // If this is a new install and we see that we've already run verification for this
14561            // package, we have nothing to do: it means the state was restored from backup.
14562            if (!replacing) {
14563                IntentFilterVerificationInfo ivi =
14564                        mSettings.getIntentFilterVerificationLPr(packageName);
14565                if (ivi != null) {
14566                    if (DEBUG_DOMAIN_VERIFICATION) {
14567                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
14568                                + ivi.getStatusString());
14569                    }
14570                    return;
14571                }
14572            }
14573
14574            // If any filters need to be verified, then all need to be.
14575            boolean needToVerify = false;
14576            for (PackageParser.Activity a : pkg.activities) {
14577                for (ActivityIntentInfo filter : a.intents) {
14578                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
14579                        if (DEBUG_DOMAIN_VERIFICATION) {
14580                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
14581                        }
14582                        needToVerify = true;
14583                        break;
14584                    }
14585                }
14586            }
14587
14588            if (needToVerify) {
14589                final int verificationId = mIntentFilterVerificationToken++;
14590                for (PackageParser.Activity a : pkg.activities) {
14591                    for (ActivityIntentInfo filter : a.intents) {
14592                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
14593                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14594                                    "Verification needed for IntentFilter:" + filter.toString());
14595                            mIntentFilterVerifier.addOneIntentFilterVerification(
14596                                    verifierUid, userId, verificationId, filter, packageName);
14597                            count++;
14598                        }
14599                    }
14600                }
14601            }
14602        }
14603
14604        if (count > 0) {
14605            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
14606                    + " IntentFilter verification" + (count > 1 ? "s" : "")
14607                    +  " for userId:" + userId);
14608            mIntentFilterVerifier.startVerifications(userId);
14609        } else {
14610            if (DEBUG_DOMAIN_VERIFICATION) {
14611                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
14612            }
14613        }
14614    }
14615
14616    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
14617        final ComponentName cn  = filter.activity.getComponentName();
14618        final String packageName = cn.getPackageName();
14619
14620        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
14621                packageName);
14622        if (ivi == null) {
14623            return true;
14624        }
14625        int status = ivi.getStatus();
14626        switch (status) {
14627            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
14628            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
14629                return true;
14630
14631            default:
14632                // Nothing to do
14633                return false;
14634        }
14635    }
14636
14637    private static boolean isMultiArch(ApplicationInfo info) {
14638        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
14639    }
14640
14641    private static boolean isExternal(PackageParser.Package pkg) {
14642        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14643    }
14644
14645    private static boolean isExternal(PackageSetting ps) {
14646        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14647    }
14648
14649    private static boolean isEphemeral(PackageParser.Package pkg) {
14650        return pkg.applicationInfo.isEphemeralApp();
14651    }
14652
14653    private static boolean isEphemeral(PackageSetting ps) {
14654        return ps.pkg != null && isEphemeral(ps.pkg);
14655    }
14656
14657    private static boolean isSystemApp(PackageParser.Package pkg) {
14658        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
14659    }
14660
14661    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
14662        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14663    }
14664
14665    private static boolean hasDomainURLs(PackageParser.Package pkg) {
14666        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
14667    }
14668
14669    private static boolean isSystemApp(PackageSetting ps) {
14670        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
14671    }
14672
14673    private static boolean isUpdatedSystemApp(PackageSetting ps) {
14674        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
14675    }
14676
14677    private int packageFlagsToInstallFlags(PackageSetting ps) {
14678        int installFlags = 0;
14679        if (isEphemeral(ps)) {
14680            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14681        }
14682        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
14683            // This existing package was an external ASEC install when we have
14684            // the external flag without a UUID
14685            installFlags |= PackageManager.INSTALL_EXTERNAL;
14686        }
14687        if (ps.isForwardLocked()) {
14688            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
14689        }
14690        return installFlags;
14691    }
14692
14693    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
14694        if (isExternal(pkg)) {
14695            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14696                return StorageManager.UUID_PRIMARY_PHYSICAL;
14697            } else {
14698                return pkg.volumeUuid;
14699            }
14700        } else {
14701            return StorageManager.UUID_PRIVATE_INTERNAL;
14702        }
14703    }
14704
14705    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
14706        if (isExternal(pkg)) {
14707            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14708                return mSettings.getExternalVersion();
14709            } else {
14710                return mSettings.findOrCreateVersion(pkg.volumeUuid);
14711            }
14712        } else {
14713            return mSettings.getInternalVersion();
14714        }
14715    }
14716
14717    private void deleteTempPackageFiles() {
14718        final FilenameFilter filter = new FilenameFilter() {
14719            public boolean accept(File dir, String name) {
14720                return name.startsWith("vmdl") && name.endsWith(".tmp");
14721            }
14722        };
14723        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
14724            file.delete();
14725        }
14726    }
14727
14728    @Override
14729    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
14730            int flags) {
14731        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
14732                flags);
14733    }
14734
14735    @Override
14736    public void deletePackage(final String packageName,
14737            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
14738        mContext.enforceCallingOrSelfPermission(
14739                android.Manifest.permission.DELETE_PACKAGES, null);
14740        Preconditions.checkNotNull(packageName);
14741        Preconditions.checkNotNull(observer);
14742        final int uid = Binder.getCallingUid();
14743        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
14744        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
14745        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
14746            mContext.enforceCallingOrSelfPermission(
14747                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14748                    "deletePackage for user " + userId);
14749        }
14750
14751        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
14752            try {
14753                observer.onPackageDeleted(packageName,
14754                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
14755            } catch (RemoteException re) {
14756            }
14757            return;
14758        }
14759
14760        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
14761            try {
14762                observer.onPackageDeleted(packageName,
14763                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
14764            } catch (RemoteException re) {
14765            }
14766            return;
14767        }
14768
14769        if (DEBUG_REMOVE) {
14770            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
14771                    + " deleteAllUsers: " + deleteAllUsers );
14772        }
14773        // Queue up an async operation since the package deletion may take a little while.
14774        mHandler.post(new Runnable() {
14775            public void run() {
14776                mHandler.removeCallbacks(this);
14777                int returnCode;
14778                if (!deleteAllUsers) {
14779                    returnCode = deletePackageX(packageName, userId, flags);
14780                } else {
14781                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
14782                    // If nobody is blocking uninstall, proceed with delete for all users
14783                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
14784                        returnCode = deletePackageX(packageName, userId, flags);
14785                    } else {
14786                        // Otherwise uninstall individually for users with blockUninstalls=false
14787                        final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS;
14788                        for (int userId : users) {
14789                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
14790                                returnCode = deletePackageX(packageName, userId, userFlags);
14791                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
14792                                    Slog.w(TAG, "Package delete failed for user " + userId
14793                                            + ", returnCode " + returnCode);
14794                                }
14795                            }
14796                        }
14797                        // The app has only been marked uninstalled for certain users.
14798                        // We still need to report that delete was blocked
14799                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
14800                    }
14801                }
14802                try {
14803                    observer.onPackageDeleted(packageName, returnCode, null);
14804                } catch (RemoteException e) {
14805                    Log.i(TAG, "Observer no longer exists.");
14806                } //end catch
14807            } //end run
14808        });
14809    }
14810
14811    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
14812        int[] result = EMPTY_INT_ARRAY;
14813        for (int userId : userIds) {
14814            if (getBlockUninstallForUser(packageName, userId)) {
14815                result = ArrayUtils.appendInt(result, userId);
14816            }
14817        }
14818        return result;
14819    }
14820
14821    @Override
14822    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
14823        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
14824    }
14825
14826    private boolean isPackageDeviceAdmin(String packageName, int userId) {
14827        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14828                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14829        try {
14830            if (dpm != null) {
14831                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
14832                        /* callingUserOnly =*/ false);
14833                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
14834                        : deviceOwnerComponentName.getPackageName();
14835                // Does the package contains the device owner?
14836                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
14837                // this check is probably not needed, since DO should be registered as a device
14838                // admin on some user too. (Original bug for this: b/17657954)
14839                if (packageName.equals(deviceOwnerPackageName)) {
14840                    return true;
14841                }
14842                // Does it contain a device admin for any user?
14843                int[] users;
14844                if (userId == UserHandle.USER_ALL) {
14845                    users = sUserManager.getUserIds();
14846                } else {
14847                    users = new int[]{userId};
14848                }
14849                for (int i = 0; i < users.length; ++i) {
14850                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
14851                        return true;
14852                    }
14853                }
14854            }
14855        } catch (RemoteException e) {
14856        }
14857        return false;
14858    }
14859
14860    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
14861        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
14862    }
14863
14864    /**
14865     *  This method is an internal method that could be get invoked either
14866     *  to delete an installed package or to clean up a failed installation.
14867     *  After deleting an installed package, a broadcast is sent to notify any
14868     *  listeners that the package has been installed. For cleaning up a failed
14869     *  installation, the broadcast is not necessary since the package's
14870     *  installation wouldn't have sent the initial broadcast either
14871     *  The key steps in deleting a package are
14872     *  deleting the package information in internal structures like mPackages,
14873     *  deleting the packages base directories through installd
14874     *  updating mSettings to reflect current status
14875     *  persisting settings for later use
14876     *  sending a broadcast if necessary
14877     */
14878    private int deletePackageX(String packageName, int userId, int flags) {
14879        final PackageRemovedInfo info = new PackageRemovedInfo();
14880        final boolean res;
14881
14882        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
14883                ? UserHandle.ALL : new UserHandle(userId);
14884
14885        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
14886            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
14887            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
14888        }
14889
14890        PackageSetting uninstalledPs = null;
14891
14892        // for the uninstall-updates case and restricted profiles, remember the per-
14893        // user handle installed state
14894        int[] allUsers;
14895        synchronized (mPackages) {
14896            uninstalledPs = mSettings.mPackages.get(packageName);
14897            if (uninstalledPs == null) {
14898                Slog.w(TAG, "Not removing non-existent package " + packageName);
14899                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14900            }
14901            allUsers = sUserManager.getUserIds();
14902            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
14903        }
14904
14905        synchronized (mInstallLock) {
14906            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
14907            res = deletePackageLI(packageName, removeForUser, true, allUsers,
14908                    flags | REMOVE_CHATTY, info, true, null);
14909            synchronized (mPackages) {
14910                if (res) {
14911                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
14912                }
14913            }
14914        }
14915
14916        if (res) {
14917            final boolean killApp = (flags & PackageManager.INSTALL_DONT_KILL_APP) == 0;
14918            info.sendPackageRemovedBroadcasts(killApp);
14919            info.sendSystemPackageUpdatedBroadcasts();
14920            info.sendSystemPackageAppearedBroadcasts();
14921        }
14922        // Force a gc here.
14923        Runtime.getRuntime().gc();
14924        // Delete the resources here after sending the broadcast to let
14925        // other processes clean up before deleting resources.
14926        if (info.args != null) {
14927            synchronized (mInstallLock) {
14928                info.args.doPostDeleteLI(true);
14929            }
14930        }
14931
14932        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14933    }
14934
14935    class PackageRemovedInfo {
14936        String removedPackage;
14937        int uid = -1;
14938        int removedAppId = -1;
14939        int[] origUsers;
14940        int[] removedUsers = null;
14941        boolean isRemovedPackageSystemUpdate = false;
14942        boolean isUpdate;
14943        boolean dataRemoved;
14944        boolean removedForAllUsers;
14945        // Clean up resources deleted packages.
14946        InstallArgs args = null;
14947        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
14948        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
14949
14950        void sendPackageRemovedBroadcasts(boolean killApp) {
14951            sendPackageRemovedBroadcastInternal(killApp);
14952            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
14953            for (int i = 0; i < childCount; i++) {
14954                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14955                childInfo.sendPackageRemovedBroadcastInternal(killApp);
14956            }
14957        }
14958
14959        void sendSystemPackageUpdatedBroadcasts() {
14960            if (isRemovedPackageSystemUpdate) {
14961                sendSystemPackageUpdatedBroadcastsInternal();
14962                final int childCount = (removedChildPackages != null)
14963                        ? removedChildPackages.size() : 0;
14964                for (int i = 0; i < childCount; i++) {
14965                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14966                    if (childInfo.isRemovedPackageSystemUpdate) {
14967                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
14968                    }
14969                }
14970            }
14971        }
14972
14973        void sendSystemPackageAppearedBroadcasts() {
14974            final int packageCount = (appearedChildPackages != null)
14975                    ? appearedChildPackages.size() : 0;
14976            for (int i = 0; i < packageCount; i++) {
14977                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
14978                for (int userId : installedInfo.newUsers) {
14979                    sendPackageAddedForUser(installedInfo.name, true,
14980                            UserHandle.getAppId(installedInfo.uid), userId);
14981                }
14982            }
14983        }
14984
14985        private void sendSystemPackageUpdatedBroadcastsInternal() {
14986            Bundle extras = new Bundle(2);
14987            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
14988            extras.putBoolean(Intent.EXTRA_REPLACING, true);
14989            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
14990                    extras, 0, null, null, null);
14991            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
14992                    extras, 0, null, null, null);
14993            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
14994                    null, 0, removedPackage, null, null);
14995        }
14996
14997        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
14998            Bundle extras = new Bundle(2);
14999            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15000            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15001            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15002            if (isUpdate || isRemovedPackageSystemUpdate) {
15003                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15004            }
15005            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15006            if (removedPackage != null) {
15007                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15008                        extras, 0, null, null, removedUsers);
15009                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15010                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15011                            removedPackage, extras, 0, null, null, removedUsers);
15012                }
15013            }
15014            if (removedAppId >= 0) {
15015                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15016                        removedUsers);
15017            }
15018        }
15019    }
15020
15021    /*
15022     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15023     * flag is not set, the data directory is removed as well.
15024     * make sure this flag is set for partially installed apps. If not its meaningless to
15025     * delete a partially installed application.
15026     */
15027    private void removePackageDataLI(PackageSetting ps, int[] allUserHandles,
15028            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15029        String packageName = ps.name;
15030        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15031        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
15032        // Retrieve object to delete permissions for shared user later on
15033        final PackageSetting deletedPs;
15034        // reader
15035        synchronized (mPackages) {
15036            deletedPs = mSettings.mPackages.get(packageName);
15037            if (outInfo != null) {
15038                outInfo.removedPackage = packageName;
15039                outInfo.removedUsers = deletedPs != null
15040                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15041                        : null;
15042            }
15043        }
15044        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15045            removeDataDirsLI(ps.volumeUuid, packageName);
15046            if (outInfo != null) {
15047                outInfo.dataRemoved = true;
15048            }
15049            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15050        }
15051        // writer
15052        synchronized (mPackages) {
15053            if (deletedPs != null) {
15054                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15055                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15056                    clearDefaultBrowserIfNeeded(packageName);
15057                    if (outInfo != null) {
15058                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15059                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15060                    }
15061                    updatePermissionsLPw(deletedPs.name, null, 0);
15062                    if (deletedPs.sharedUser != null) {
15063                        // Remove permissions associated with package. Since runtime
15064                        // permissions are per user we have to kill the removed package
15065                        // or packages running under the shared user of the removed
15066                        // package if revoking the permissions requested only by the removed
15067                        // package is successful and this causes a change in gids.
15068                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15069                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15070                                    userId);
15071                            if (userIdToKill == UserHandle.USER_ALL
15072                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15073                                // If gids changed for this user, kill all affected packages.
15074                                mHandler.post(new Runnable() {
15075                                    @Override
15076                                    public void run() {
15077                                        // This has to happen with no lock held.
15078                                        killApplication(deletedPs.name, deletedPs.appId,
15079                                                KILL_APP_REASON_GIDS_CHANGED);
15080                                    }
15081                                });
15082                                break;
15083                            }
15084                        }
15085                    }
15086                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15087                }
15088                // make sure to preserve per-user disabled state if this removal was just
15089                // a downgrade of a system app to the factory package
15090                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15091                    if (DEBUG_REMOVE) {
15092                        Slog.d(TAG, "Propagating install state across downgrade");
15093                    }
15094                    for (int userId : allUserHandles) {
15095                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15096                        if (DEBUG_REMOVE) {
15097                            Slog.d(TAG, "    user " + userId + " => " + installed);
15098                        }
15099                        ps.setInstalled(installed, userId);
15100                    }
15101                }
15102            }
15103            // can downgrade to reader
15104            if (writeSettings) {
15105                // Save settings now
15106                mSettings.writeLPr();
15107            }
15108        }
15109        if (outInfo != null) {
15110            // A user ID was deleted here. Go through all users and remove it
15111            // from KeyStore.
15112            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15113        }
15114    }
15115
15116    static boolean locationIsPrivileged(File path) {
15117        try {
15118            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15119                    .getCanonicalPath();
15120            return path.getCanonicalPath().startsWith(privilegedAppDir);
15121        } catch (IOException e) {
15122            Slog.e(TAG, "Unable to access code path " + path);
15123        }
15124        return false;
15125    }
15126
15127    /*
15128     * Tries to delete system package.
15129     */
15130    private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg,
15131            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15132            boolean writeSettings) {
15133        if (deletedPs.parentPackageName != null) {
15134            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15135            return false;
15136        }
15137
15138        final boolean applyUserRestrictions
15139                = (allUserHandles != null) && (outInfo.origUsers != null);
15140        final PackageSetting disabledPs;
15141        // Confirm if the system package has been updated
15142        // An updated system app can be deleted. This will also have to restore
15143        // the system pkg from system partition
15144        // reader
15145        synchronized (mPackages) {
15146            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15147        }
15148
15149        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15150                + " disabledPs=" + disabledPs);
15151
15152        if (disabledPs == null) {
15153            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15154            return false;
15155        } else if (DEBUG_REMOVE) {
15156            Slog.d(TAG, "Deleting system pkg from data partition");
15157        }
15158
15159        if (DEBUG_REMOVE) {
15160            if (applyUserRestrictions) {
15161                Slog.d(TAG, "Remembering install states:");
15162                for (int userId : allUserHandles) {
15163                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15164                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15165                }
15166            }
15167        }
15168
15169        // Delete the updated package
15170        outInfo.isRemovedPackageSystemUpdate = true;
15171        if (outInfo.removedChildPackages != null) {
15172            final int childCount = (deletedPs.childPackageNames != null)
15173                    ? deletedPs.childPackageNames.size() : 0;
15174            for (int i = 0; i < childCount; i++) {
15175                String childPackageName = deletedPs.childPackageNames.get(i);
15176                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15177                        .contains(childPackageName)) {
15178                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15179                            childPackageName);
15180                    if (childInfo != null) {
15181                        childInfo.isRemovedPackageSystemUpdate = true;
15182                    }
15183                }
15184            }
15185        }
15186
15187        if (disabledPs.versionCode < deletedPs.versionCode) {
15188            // Delete data for downgrades
15189            flags &= ~PackageManager.DELETE_KEEP_DATA;
15190        } else {
15191            // Preserve data by setting flag
15192            flags |= PackageManager.DELETE_KEEP_DATA;
15193        }
15194
15195        boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles,
15196                outInfo, writeSettings, disabledPs.pkg);
15197        if (!ret) {
15198            return false;
15199        }
15200
15201        // writer
15202        synchronized (mPackages) {
15203            // Reinstate the old system package
15204            enableSystemPackageLPw(disabledPs.pkg);
15205            // Remove any native libraries from the upgraded package.
15206            removeNativeBinariesLI(deletedPs);
15207        }
15208
15209        // Install the system package
15210        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15211        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
15212        if (locationIsPrivileged(disabledPs.codePath)) {
15213            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15214        }
15215
15216        final PackageParser.Package newPkg;
15217        try {
15218            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15219        } catch (PackageManagerException e) {
15220            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15221                    + e.getMessage());
15222            return false;
15223        }
15224
15225        prepareAppDataAfterInstall(newPkg);
15226
15227        // writer
15228        synchronized (mPackages) {
15229            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15230
15231            // Propagate the permissions state as we do not want to drop on the floor
15232            // runtime permissions. The update permissions method below will take
15233            // care of removing obsolete permissions and grant install permissions.
15234            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15235            updatePermissionsLPw(newPkg.packageName, newPkg,
15236                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15237
15238            if (applyUserRestrictions) {
15239                if (DEBUG_REMOVE) {
15240                    Slog.d(TAG, "Propagating install state across reinstall");
15241                }
15242                for (int userId : allUserHandles) {
15243                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15244                    if (DEBUG_REMOVE) {
15245                        Slog.d(TAG, "    user " + userId + " => " + installed);
15246                    }
15247                    ps.setInstalled(installed, userId);
15248
15249                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15250                }
15251                // Regardless of writeSettings we need to ensure that this restriction
15252                // state propagation is persisted
15253                mSettings.writeAllUsersPackageRestrictionsLPr();
15254            }
15255            // can downgrade to reader here
15256            if (writeSettings) {
15257                mSettings.writeLPr();
15258            }
15259        }
15260        return true;
15261    }
15262
15263    private boolean deleteInstalledPackageLI(PackageSetting ps,
15264            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15265            PackageRemovedInfo outInfo, boolean writeSettings,
15266            PackageParser.Package replacingPackage) {
15267        synchronized (mPackages) {
15268            if (outInfo != null) {
15269                outInfo.uid = ps.appId;
15270            }
15271
15272            if (outInfo != null && outInfo.removedChildPackages != null) {
15273                final int childCount = (ps.childPackageNames != null)
15274                        ? ps.childPackageNames.size() : 0;
15275                for (int i = 0; i < childCount; i++) {
15276                    String childPackageName = ps.childPackageNames.get(i);
15277                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15278                    if (childPs == null) {
15279                        return false;
15280                    }
15281                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15282                            childPackageName);
15283                    if (childInfo != null) {
15284                        childInfo.uid = childPs.appId;
15285                    }
15286                }
15287            }
15288        }
15289
15290        // Delete package data from internal structures and also remove data if flag is set
15291        removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings);
15292
15293        // Delete the child packages data
15294        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15295        for (int i = 0; i < childCount; i++) {
15296            PackageSetting childPs;
15297            synchronized (mPackages) {
15298                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15299            }
15300            if (childPs != null) {
15301                PackageRemovedInfo childOutInfo = (outInfo != null
15302                        && outInfo.removedChildPackages != null)
15303                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15304                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15305                        && (replacingPackage != null
15306                        && !replacingPackage.hasChildPackage(childPs.name))
15307                        ? flags & ~DELETE_KEEP_DATA : flags;
15308                removePackageDataLI(childPs, allUserHandles, childOutInfo,
15309                        deleteFlags, writeSettings);
15310            }
15311        }
15312
15313        // Delete application code and resources only for parent packages
15314        if (ps.parentPackageName == null) {
15315            if (deleteCodeAndResources && (outInfo != null)) {
15316                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15317                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15318                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15319            }
15320        }
15321
15322        return true;
15323    }
15324
15325    @Override
15326    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15327            int userId) {
15328        mContext.enforceCallingOrSelfPermission(
15329                android.Manifest.permission.DELETE_PACKAGES, null);
15330        synchronized (mPackages) {
15331            PackageSetting ps = mSettings.mPackages.get(packageName);
15332            if (ps == null) {
15333                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15334                return false;
15335            }
15336            if (!ps.getInstalled(userId)) {
15337                // Can't block uninstall for an app that is not installed or enabled.
15338                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15339                return false;
15340            }
15341            ps.setBlockUninstall(blockUninstall, userId);
15342            mSettings.writePackageRestrictionsLPr(userId);
15343        }
15344        return true;
15345    }
15346
15347    @Override
15348    public boolean getBlockUninstallForUser(String packageName, int userId) {
15349        synchronized (mPackages) {
15350            PackageSetting ps = mSettings.mPackages.get(packageName);
15351            if (ps == null) {
15352                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15353                return false;
15354            }
15355            return ps.getBlockUninstall(userId);
15356        }
15357    }
15358
15359    @Override
15360    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15361        int callingUid = Binder.getCallingUid();
15362        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15363            throw new SecurityException(
15364                    "setRequiredForSystemUser can only be run by the system or root");
15365        }
15366        synchronized (mPackages) {
15367            PackageSetting ps = mSettings.mPackages.get(packageName);
15368            if (ps == null) {
15369                Log.w(TAG, "Package doesn't exist: " + packageName);
15370                return false;
15371            }
15372            if (systemUserApp) {
15373                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15374            } else {
15375                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15376            }
15377            mSettings.writeLPr();
15378        }
15379        return true;
15380    }
15381
15382    /*
15383     * This method handles package deletion in general
15384     */
15385    private boolean deletePackageLI(String packageName, UserHandle user,
15386            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
15387            PackageRemovedInfo outInfo, boolean writeSettings,
15388            PackageParser.Package replacingPackage) {
15389        if (packageName == null) {
15390            Slog.w(TAG, "Attempt to delete null packageName.");
15391            return false;
15392        }
15393
15394        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
15395
15396        PackageSetting ps;
15397
15398        synchronized (mPackages) {
15399            ps = mSettings.mPackages.get(packageName);
15400            if (ps == null) {
15401                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15402                return false;
15403            }
15404
15405            if (ps.parentPackageName != null && (!isSystemApp(ps)
15406                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
15407                if (DEBUG_REMOVE) {
15408                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
15409                            + ((user == null) ? UserHandle.USER_ALL : user));
15410                }
15411                final int removedUserId = (user != null) ? user.getIdentifier()
15412                        : UserHandle.USER_ALL;
15413                if (!clearPackageStateForUser(ps, removedUserId, outInfo)) {
15414                    return false;
15415                }
15416                markPackageUninstalledForUserLPw(ps, user);
15417                scheduleWritePackageRestrictionsLocked(user);
15418                return true;
15419            }
15420        }
15421
15422        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
15423                && user.getIdentifier() != UserHandle.USER_ALL)) {
15424            // The caller is asking that the package only be deleted for a single
15425            // user.  To do this, we just mark its uninstalled state and delete
15426            // its data. If this is a system app, we only allow this to happen if
15427            // they have set the special DELETE_SYSTEM_APP which requests different
15428            // semantics than normal for uninstalling system apps.
15429            markPackageUninstalledForUserLPw(ps, user);
15430
15431            if (!isSystemApp(ps)) {
15432                // Do not uninstall the APK if an app should be cached
15433                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
15434                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
15435                    // Other user still have this package installed, so all
15436                    // we need to do is clear this user's data and save that
15437                    // it is uninstalled.
15438                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
15439                    if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
15440                        return false;
15441                    }
15442                    scheduleWritePackageRestrictionsLocked(user);
15443                    return true;
15444                } else {
15445                    // We need to set it back to 'installed' so the uninstall
15446                    // broadcasts will be sent correctly.
15447                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
15448                    ps.setInstalled(true, user.getIdentifier());
15449                }
15450            } else {
15451                // This is a system app, so we assume that the
15452                // other users still have this package installed, so all
15453                // we need to do is clear this user's data and save that
15454                // it is uninstalled.
15455                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
15456                if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
15457                    return false;
15458                }
15459                scheduleWritePackageRestrictionsLocked(user);
15460                return true;
15461            }
15462        }
15463
15464        // If we are deleting a composite package for all users, keep track
15465        // of result for each child.
15466        if (ps.childPackageNames != null && outInfo != null) {
15467            synchronized (mPackages) {
15468                final int childCount = ps.childPackageNames.size();
15469                outInfo.removedChildPackages = new ArrayMap<>(childCount);
15470                for (int i = 0; i < childCount; i++) {
15471                    String childPackageName = ps.childPackageNames.get(i);
15472                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
15473                    childInfo.removedPackage = childPackageName;
15474                    outInfo.removedChildPackages.put(childPackageName, childInfo);
15475                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15476                    if (childPs != null) {
15477                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
15478                    }
15479                }
15480            }
15481        }
15482
15483        boolean ret = false;
15484        if (isSystemApp(ps)) {
15485            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
15486            // When an updated system application is deleted we delete the existing resources
15487            // as well and fall back to existing code in system partition
15488            ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
15489        } else {
15490            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
15491            // Kill application pre-emptively especially for apps on sd.
15492            final boolean killApp = (flags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15493            if (killApp) {
15494                killApplication(packageName, ps.appId, "uninstall pkg");
15495            }
15496            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles,
15497                    outInfo, writeSettings, replacingPackage);
15498        }
15499
15500        // Take a note whether we deleted the package for all users
15501        if (outInfo != null) {
15502            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15503            if (outInfo.removedChildPackages != null) {
15504                synchronized (mPackages) {
15505                    final int childCount = outInfo.removedChildPackages.size();
15506                    for (int i = 0; i < childCount; i++) {
15507                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
15508                        if (childInfo != null) {
15509                            childInfo.removedForAllUsers = mPackages.get(
15510                                    childInfo.removedPackage) == null;
15511                        }
15512                    }
15513                }
15514            }
15515            // If we uninstalled an update to a system app there may be some
15516            // child packages that appeared as they are declared in the system
15517            // app but were not declared in the update.
15518            if (isSystemApp(ps)) {
15519                synchronized (mPackages) {
15520                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
15521                    final int childCount = (updatedPs.childPackageNames != null)
15522                            ? updatedPs.childPackageNames.size() : 0;
15523                    for (int i = 0; i < childCount; i++) {
15524                        String childPackageName = updatedPs.childPackageNames.get(i);
15525                        if (outInfo.removedChildPackages == null
15526                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
15527                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15528                            if (childPs == null) {
15529                                continue;
15530                            }
15531                            PackageInstalledInfo installRes = new PackageInstalledInfo();
15532                            installRes.name = childPackageName;
15533                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
15534                            installRes.pkg = mPackages.get(childPackageName);
15535                            installRes.uid = childPs.pkg.applicationInfo.uid;
15536                            if (outInfo.appearedChildPackages == null) {
15537                                outInfo.appearedChildPackages = new ArrayMap<>();
15538                            }
15539                            outInfo.appearedChildPackages.put(childPackageName, installRes);
15540                        }
15541                    }
15542                }
15543            }
15544        }
15545
15546        return ret;
15547    }
15548
15549    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
15550        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
15551                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
15552        for (int nextUserId : userIds) {
15553            if (DEBUG_REMOVE) {
15554                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
15555            }
15556            ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT,
15557                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
15558                    false /*hidden*/, false /*suspended*/, null, null, null,
15559                    false /*blockUninstall*/,
15560                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
15561        }
15562    }
15563
15564    private boolean clearPackageStateForUser(PackageSetting ps, int userId,
15565            PackageRemovedInfo outInfo) {
15566        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
15567                : new int[] {userId};
15568        for (int nextUserId : userIds) {
15569            if (DEBUG_REMOVE) {
15570                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
15571                        + nextUserId);
15572            }
15573            final int flags =  StorageManager.FLAG_STORAGE_CE|  StorageManager.FLAG_STORAGE_DE;
15574            try {
15575                mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags);
15576            } catch (InstallerException e) {
15577                Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e);
15578                return false;
15579            }
15580            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
15581            schedulePackageCleaning(ps.name, nextUserId, false);
15582            synchronized (mPackages) {
15583                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
15584                    scheduleWritePackageRestrictionsLocked(nextUserId);
15585                }
15586                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
15587            }
15588        }
15589
15590        if (outInfo != null) {
15591            outInfo.removedPackage = ps.name;
15592            outInfo.removedAppId = ps.appId;
15593            outInfo.removedUsers = userIds;
15594        }
15595
15596        return true;
15597    }
15598
15599    private final class ClearStorageConnection implements ServiceConnection {
15600        IMediaContainerService mContainerService;
15601
15602        @Override
15603        public void onServiceConnected(ComponentName name, IBinder service) {
15604            synchronized (this) {
15605                mContainerService = IMediaContainerService.Stub.asInterface(service);
15606                notifyAll();
15607            }
15608        }
15609
15610        @Override
15611        public void onServiceDisconnected(ComponentName name) {
15612        }
15613    }
15614
15615    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
15616        final boolean mounted;
15617        if (Environment.isExternalStorageEmulated()) {
15618            mounted = true;
15619        } else {
15620            final String status = Environment.getExternalStorageState();
15621
15622            mounted = status.equals(Environment.MEDIA_MOUNTED)
15623                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
15624        }
15625
15626        if (!mounted) {
15627            return;
15628        }
15629
15630        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
15631        int[] users;
15632        if (userId == UserHandle.USER_ALL) {
15633            users = sUserManager.getUserIds();
15634        } else {
15635            users = new int[] { userId };
15636        }
15637        final ClearStorageConnection conn = new ClearStorageConnection();
15638        if (mContext.bindServiceAsUser(
15639                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
15640            try {
15641                for (int curUser : users) {
15642                    long timeout = SystemClock.uptimeMillis() + 5000;
15643                    synchronized (conn) {
15644                        long now = SystemClock.uptimeMillis();
15645                        while (conn.mContainerService == null && now < timeout) {
15646                            try {
15647                                conn.wait(timeout - now);
15648                            } catch (InterruptedException e) {
15649                            }
15650                        }
15651                    }
15652                    if (conn.mContainerService == null) {
15653                        return;
15654                    }
15655
15656                    final UserEnvironment userEnv = new UserEnvironment(curUser);
15657                    clearDirectory(conn.mContainerService,
15658                            userEnv.buildExternalStorageAppCacheDirs(packageName));
15659                    if (allData) {
15660                        clearDirectory(conn.mContainerService,
15661                                userEnv.buildExternalStorageAppDataDirs(packageName));
15662                        clearDirectory(conn.mContainerService,
15663                                userEnv.buildExternalStorageAppMediaDirs(packageName));
15664                    }
15665                }
15666            } finally {
15667                mContext.unbindService(conn);
15668            }
15669        }
15670    }
15671
15672    @Override
15673    public void clearApplicationProfileData(String packageName) {
15674        enforceSystemOrRoot("Only the system can clear all profile data");
15675        try {
15676            mInstaller.clearAppProfiles(packageName);
15677        } catch (InstallerException ex) {
15678            Log.e(TAG, "Could not clear profile data of package " + packageName);
15679        }
15680    }
15681
15682    @Override
15683    public void clearApplicationUserData(final String packageName,
15684            final IPackageDataObserver observer, final int userId) {
15685        mContext.enforceCallingOrSelfPermission(
15686                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
15687
15688        enforceCrossUserPermission(Binder.getCallingUid(), userId,
15689                true /* requireFullPermission */, false /* checkShell */, "clear application data");
15690
15691        final DevicePolicyManagerInternal dpmi = LocalServices
15692                .getService(DevicePolicyManagerInternal.class);
15693        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
15694            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
15695        }
15696        // Queue up an async operation since the package deletion may take a little while.
15697        mHandler.post(new Runnable() {
15698            public void run() {
15699                mHandler.removeCallbacks(this);
15700                final boolean succeeded;
15701                synchronized (mInstallLock) {
15702                    succeeded = clearApplicationUserDataLI(packageName, userId);
15703                }
15704                clearExternalStorageDataSync(packageName, userId, true);
15705                if (succeeded) {
15706                    // invoke DeviceStorageMonitor's update method to clear any notifications
15707                    DeviceStorageMonitorInternal dsm = LocalServices
15708                            .getService(DeviceStorageMonitorInternal.class);
15709                    if (dsm != null) {
15710                        dsm.checkMemory();
15711                    }
15712                }
15713                if(observer != null) {
15714                    try {
15715                        observer.onRemoveCompleted(packageName, succeeded);
15716                    } catch (RemoteException e) {
15717                        Log.i(TAG, "Observer no longer exists.");
15718                    }
15719                } //end if observer
15720            } //end run
15721        });
15722    }
15723
15724    private boolean clearApplicationUserDataLI(String packageName, int userId) {
15725        if (packageName == null) {
15726            Slog.w(TAG, "Attempt to delete null packageName.");
15727            return false;
15728        }
15729
15730        // Try finding details about the requested package
15731        PackageParser.Package pkg;
15732        synchronized (mPackages) {
15733            pkg = mPackages.get(packageName);
15734            if (pkg == null) {
15735                final PackageSetting ps = mSettings.mPackages.get(packageName);
15736                if (ps != null) {
15737                    pkg = ps.pkg;
15738                }
15739            }
15740
15741            if (pkg == null) {
15742                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15743                return false;
15744            }
15745
15746            PackageSetting ps = (PackageSetting) pkg.mExtras;
15747            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15748        }
15749
15750        // Always delete data directories for package, even if we found no other
15751        // record of app. This helps users recover from UID mismatches without
15752        // resorting to a full data wipe.
15753        // TODO: triage flags as part of 26466827
15754        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15755        try {
15756            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
15757        } catch (InstallerException e) {
15758            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
15759            return false;
15760        }
15761
15762        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15763        removeKeystoreDataIfNeeded(userId, appId);
15764
15765        // Create a native library symlink only if we have native libraries
15766        // and if the native libraries are 32 bit libraries. We do not provide
15767        // this symlink for 64 bit libraries.
15768        if (pkg.applicationInfo.primaryCpuAbi != null &&
15769                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
15770            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
15771            try {
15772                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
15773                        nativeLibPath, userId);
15774            } catch (InstallerException e) {
15775                Slog.w(TAG, "Failed linking native library dir", e);
15776                return false;
15777            }
15778        }
15779
15780        return true;
15781    }
15782
15783    /**
15784     * Reverts user permission state changes (permissions and flags) in
15785     * all packages for a given user.
15786     *
15787     * @param userId The device user for which to do a reset.
15788     */
15789    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
15790        final int packageCount = mPackages.size();
15791        for (int i = 0; i < packageCount; i++) {
15792            PackageParser.Package pkg = mPackages.valueAt(i);
15793            PackageSetting ps = (PackageSetting) pkg.mExtras;
15794            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15795        }
15796    }
15797
15798    /**
15799     * Reverts user permission state changes (permissions and flags).
15800     *
15801     * @param ps The package for which to reset.
15802     * @param userId The device user for which to do a reset.
15803     */
15804    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
15805            final PackageSetting ps, final int userId) {
15806        if (ps.pkg == null) {
15807            return;
15808        }
15809
15810        // These are flags that can change base on user actions.
15811        final int userSettableMask = FLAG_PERMISSION_USER_SET
15812                | FLAG_PERMISSION_USER_FIXED
15813                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
15814                | FLAG_PERMISSION_REVIEW_REQUIRED;
15815
15816        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
15817                | FLAG_PERMISSION_POLICY_FIXED;
15818
15819        boolean writeInstallPermissions = false;
15820        boolean writeRuntimePermissions = false;
15821
15822        final int permissionCount = ps.pkg.requestedPermissions.size();
15823        for (int i = 0; i < permissionCount; i++) {
15824            String permission = ps.pkg.requestedPermissions.get(i);
15825
15826            BasePermission bp = mSettings.mPermissions.get(permission);
15827            if (bp == null) {
15828                continue;
15829            }
15830
15831            // If shared user we just reset the state to which only this app contributed.
15832            if (ps.sharedUser != null) {
15833                boolean used = false;
15834                final int packageCount = ps.sharedUser.packages.size();
15835                for (int j = 0; j < packageCount; j++) {
15836                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
15837                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
15838                            && pkg.pkg.requestedPermissions.contains(permission)) {
15839                        used = true;
15840                        break;
15841                    }
15842                }
15843                if (used) {
15844                    continue;
15845                }
15846            }
15847
15848            PermissionsState permissionsState = ps.getPermissionsState();
15849
15850            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
15851
15852            // Always clear the user settable flags.
15853            final boolean hasInstallState = permissionsState.getInstallPermissionState(
15854                    bp.name) != null;
15855            // If permission review is enabled and this is a legacy app, mark the
15856            // permission as requiring a review as this is the initial state.
15857            int flags = 0;
15858            if (Build.PERMISSIONS_REVIEW_REQUIRED
15859                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
15860                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
15861            }
15862            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
15863                if (hasInstallState) {
15864                    writeInstallPermissions = true;
15865                } else {
15866                    writeRuntimePermissions = true;
15867                }
15868            }
15869
15870            // Below is only runtime permission handling.
15871            if (!bp.isRuntime()) {
15872                continue;
15873            }
15874
15875            // Never clobber system or policy.
15876            if ((oldFlags & policyOrSystemFlags) != 0) {
15877                continue;
15878            }
15879
15880            // If this permission was granted by default, make sure it is.
15881            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
15882                if (permissionsState.grantRuntimePermission(bp, userId)
15883                        != PERMISSION_OPERATION_FAILURE) {
15884                    writeRuntimePermissions = true;
15885                }
15886            // If permission review is enabled the permissions for a legacy apps
15887            // are represented as constantly granted runtime ones, so don't revoke.
15888            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
15889                // Otherwise, reset the permission.
15890                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
15891                switch (revokeResult) {
15892                    case PERMISSION_OPERATION_SUCCESS:
15893                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
15894                        writeRuntimePermissions = true;
15895                        final int appId = ps.appId;
15896                        mHandler.post(new Runnable() {
15897                            @Override
15898                            public void run() {
15899                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
15900                            }
15901                        });
15902                    } break;
15903                }
15904            }
15905        }
15906
15907        // Synchronously write as we are taking permissions away.
15908        if (writeRuntimePermissions) {
15909            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
15910        }
15911
15912        // Synchronously write as we are taking permissions away.
15913        if (writeInstallPermissions) {
15914            mSettings.writeLPr();
15915        }
15916    }
15917
15918    /**
15919     * Remove entries from the keystore daemon. Will only remove it if the
15920     * {@code appId} is valid.
15921     */
15922    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
15923        if (appId < 0) {
15924            return;
15925        }
15926
15927        final KeyStore keyStore = KeyStore.getInstance();
15928        if (keyStore != null) {
15929            if (userId == UserHandle.USER_ALL) {
15930                for (final int individual : sUserManager.getUserIds()) {
15931                    keyStore.clearUid(UserHandle.getUid(individual, appId));
15932                }
15933            } else {
15934                keyStore.clearUid(UserHandle.getUid(userId, appId));
15935            }
15936        } else {
15937            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
15938        }
15939    }
15940
15941    @Override
15942    public void deleteApplicationCacheFiles(final String packageName,
15943            final IPackageDataObserver observer) {
15944        mContext.enforceCallingOrSelfPermission(
15945                android.Manifest.permission.DELETE_CACHE_FILES, null);
15946        // Queue up an async operation since the package deletion may take a little while.
15947        final int userId = UserHandle.getCallingUserId();
15948        mHandler.post(new Runnable() {
15949            public void run() {
15950                mHandler.removeCallbacks(this);
15951                final boolean succeded;
15952                synchronized (mInstallLock) {
15953                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
15954                }
15955                clearExternalStorageDataSync(packageName, userId, false);
15956                if (observer != null) {
15957                    try {
15958                        observer.onRemoveCompleted(packageName, succeded);
15959                    } catch (RemoteException e) {
15960                        Log.i(TAG, "Observer no longer exists.");
15961                    }
15962                } //end if observer
15963            } //end run
15964        });
15965    }
15966
15967    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
15968        if (packageName == null) {
15969            Slog.w(TAG, "Attempt to delete null packageName.");
15970            return false;
15971        }
15972        PackageParser.Package p;
15973        synchronized (mPackages) {
15974            p = mPackages.get(packageName);
15975        }
15976        if (p == null) {
15977            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15978            return false;
15979        }
15980        final ApplicationInfo applicationInfo = p.applicationInfo;
15981        if (applicationInfo == null) {
15982            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15983            return false;
15984        }
15985        // TODO: triage flags as part of 26466827
15986        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15987        try {
15988            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
15989                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
15990        } catch (InstallerException e) {
15991            Slog.w(TAG, "Couldn't remove cache files for package "
15992                    + packageName + " u" + userId, e);
15993            return false;
15994        }
15995        return true;
15996    }
15997
15998    @Override
15999    public void getPackageSizeInfo(final String packageName, int userHandle,
16000            final IPackageStatsObserver observer) {
16001        mContext.enforceCallingOrSelfPermission(
16002                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16003        if (packageName == null) {
16004            throw new IllegalArgumentException("Attempt to get size of null packageName");
16005        }
16006
16007        PackageStats stats = new PackageStats(packageName, userHandle);
16008
16009        /*
16010         * Queue up an async operation since the package measurement may take a
16011         * little while.
16012         */
16013        Message msg = mHandler.obtainMessage(INIT_COPY);
16014        msg.obj = new MeasureParams(stats, observer);
16015        mHandler.sendMessage(msg);
16016    }
16017
16018    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
16019            PackageStats pStats) {
16020        if (packageName == null) {
16021            Slog.w(TAG, "Attempt to get size of null packageName.");
16022            return false;
16023        }
16024        PackageParser.Package p;
16025        boolean dataOnly = false;
16026        String libDirRoot = null;
16027        String asecPath = null;
16028        PackageSetting ps = null;
16029        synchronized (mPackages) {
16030            p = mPackages.get(packageName);
16031            ps = mSettings.mPackages.get(packageName);
16032            if(p == null) {
16033                dataOnly = true;
16034                if((ps == null) || (ps.pkg == null)) {
16035                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
16036                    return false;
16037                }
16038                p = ps.pkg;
16039            }
16040            if (ps != null) {
16041                libDirRoot = ps.legacyNativeLibraryPathString;
16042            }
16043            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
16044                final long token = Binder.clearCallingIdentity();
16045                try {
16046                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
16047                    if (secureContainerId != null) {
16048                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
16049                    }
16050                } finally {
16051                    Binder.restoreCallingIdentity(token);
16052                }
16053            }
16054        }
16055        String publicSrcDir = null;
16056        if(!dataOnly) {
16057            final ApplicationInfo applicationInfo = p.applicationInfo;
16058            if (applicationInfo == null) {
16059                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
16060                return false;
16061            }
16062            if (p.isForwardLocked()) {
16063                publicSrcDir = applicationInfo.getBaseResourcePath();
16064            }
16065        }
16066        // TODO: extend to measure size of split APKs
16067        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
16068        // not just the first level.
16069        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
16070        // just the primary.
16071        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
16072
16073        String apkPath;
16074        File packageDir = new File(p.codePath);
16075
16076        if (packageDir.isDirectory() && p.canHaveOatDir()) {
16077            apkPath = packageDir.getAbsolutePath();
16078            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
16079            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
16080                libDirRoot = null;
16081            }
16082        } else {
16083            apkPath = p.baseCodePath;
16084        }
16085
16086        // TODO: triage flags as part of 26466827
16087        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
16088        try {
16089            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
16090                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
16091        } catch (InstallerException e) {
16092            return false;
16093        }
16094
16095        // Fix-up for forward-locked applications in ASEC containers.
16096        if (!isExternal(p)) {
16097            pStats.codeSize += pStats.externalCodeSize;
16098            pStats.externalCodeSize = 0L;
16099        }
16100
16101        return true;
16102    }
16103
16104    private int getUidTargetSdkVersionLockedLPr(int uid) {
16105        Object obj = mSettings.getUserIdLPr(uid);
16106        if (obj instanceof SharedUserSetting) {
16107            final SharedUserSetting sus = (SharedUserSetting) obj;
16108            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16109            final Iterator<PackageSetting> it = sus.packages.iterator();
16110            while (it.hasNext()) {
16111                final PackageSetting ps = it.next();
16112                if (ps.pkg != null) {
16113                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16114                    if (v < vers) vers = v;
16115                }
16116            }
16117            return vers;
16118        } else if (obj instanceof PackageSetting) {
16119            final PackageSetting ps = (PackageSetting) obj;
16120            if (ps.pkg != null) {
16121                return ps.pkg.applicationInfo.targetSdkVersion;
16122            }
16123        }
16124        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16125    }
16126
16127    @Override
16128    public void addPreferredActivity(IntentFilter filter, int match,
16129            ComponentName[] set, ComponentName activity, int userId) {
16130        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16131                "Adding preferred");
16132    }
16133
16134    private void addPreferredActivityInternal(IntentFilter filter, int match,
16135            ComponentName[] set, ComponentName activity, boolean always, int userId,
16136            String opname) {
16137        // writer
16138        int callingUid = Binder.getCallingUid();
16139        enforceCrossUserPermission(callingUid, userId,
16140                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16141        if (filter.countActions() == 0) {
16142            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16143            return;
16144        }
16145        synchronized (mPackages) {
16146            if (mContext.checkCallingOrSelfPermission(
16147                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16148                    != PackageManager.PERMISSION_GRANTED) {
16149                if (getUidTargetSdkVersionLockedLPr(callingUid)
16150                        < Build.VERSION_CODES.FROYO) {
16151                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16152                            + callingUid);
16153                    return;
16154                }
16155                mContext.enforceCallingOrSelfPermission(
16156                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16157            }
16158
16159            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16160            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16161                    + userId + ":");
16162            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16163            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16164            scheduleWritePackageRestrictionsLocked(userId);
16165        }
16166    }
16167
16168    @Override
16169    public void replacePreferredActivity(IntentFilter filter, int match,
16170            ComponentName[] set, ComponentName activity, int userId) {
16171        if (filter.countActions() != 1) {
16172            throw new IllegalArgumentException(
16173                    "replacePreferredActivity expects filter to have only 1 action.");
16174        }
16175        if (filter.countDataAuthorities() != 0
16176                || filter.countDataPaths() != 0
16177                || filter.countDataSchemes() > 1
16178                || filter.countDataTypes() != 0) {
16179            throw new IllegalArgumentException(
16180                    "replacePreferredActivity expects filter to have no data authorities, " +
16181                    "paths, or types; and at most one scheme.");
16182        }
16183
16184        final int callingUid = Binder.getCallingUid();
16185        enforceCrossUserPermission(callingUid, userId,
16186                true /* requireFullPermission */, false /* checkShell */,
16187                "replace preferred activity");
16188        synchronized (mPackages) {
16189            if (mContext.checkCallingOrSelfPermission(
16190                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16191                    != PackageManager.PERMISSION_GRANTED) {
16192                if (getUidTargetSdkVersionLockedLPr(callingUid)
16193                        < Build.VERSION_CODES.FROYO) {
16194                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16195                            + Binder.getCallingUid());
16196                    return;
16197                }
16198                mContext.enforceCallingOrSelfPermission(
16199                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16200            }
16201
16202            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16203            if (pir != null) {
16204                // Get all of the existing entries that exactly match this filter.
16205                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16206                if (existing != null && existing.size() == 1) {
16207                    PreferredActivity cur = existing.get(0);
16208                    if (DEBUG_PREFERRED) {
16209                        Slog.i(TAG, "Checking replace of preferred:");
16210                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16211                        if (!cur.mPref.mAlways) {
16212                            Slog.i(TAG, "  -- CUR; not mAlways!");
16213                        } else {
16214                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16215                            Slog.i(TAG, "  -- CUR: mSet="
16216                                    + Arrays.toString(cur.mPref.mSetComponents));
16217                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16218                            Slog.i(TAG, "  -- NEW: mMatch="
16219                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16220                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16221                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16222                        }
16223                    }
16224                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16225                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16226                            && cur.mPref.sameSet(set)) {
16227                        // Setting the preferred activity to what it happens to be already
16228                        if (DEBUG_PREFERRED) {
16229                            Slog.i(TAG, "Replacing with same preferred activity "
16230                                    + cur.mPref.mShortComponent + " for user "
16231                                    + userId + ":");
16232                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16233                        }
16234                        return;
16235                    }
16236                }
16237
16238                if (existing != null) {
16239                    if (DEBUG_PREFERRED) {
16240                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16241                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16242                    }
16243                    for (int i = 0; i < existing.size(); i++) {
16244                        PreferredActivity pa = existing.get(i);
16245                        if (DEBUG_PREFERRED) {
16246                            Slog.i(TAG, "Removing existing preferred activity "
16247                                    + pa.mPref.mComponent + ":");
16248                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16249                        }
16250                        pir.removeFilter(pa);
16251                    }
16252                }
16253            }
16254            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16255                    "Replacing preferred");
16256        }
16257    }
16258
16259    @Override
16260    public void clearPackagePreferredActivities(String packageName) {
16261        final int uid = Binder.getCallingUid();
16262        // writer
16263        synchronized (mPackages) {
16264            PackageParser.Package pkg = mPackages.get(packageName);
16265            if (pkg == null || pkg.applicationInfo.uid != uid) {
16266                if (mContext.checkCallingOrSelfPermission(
16267                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16268                        != PackageManager.PERMISSION_GRANTED) {
16269                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16270                            < Build.VERSION_CODES.FROYO) {
16271                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16272                                + Binder.getCallingUid());
16273                        return;
16274                    }
16275                    mContext.enforceCallingOrSelfPermission(
16276                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16277                }
16278            }
16279
16280            int user = UserHandle.getCallingUserId();
16281            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16282                scheduleWritePackageRestrictionsLocked(user);
16283            }
16284        }
16285    }
16286
16287    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16288    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16289        ArrayList<PreferredActivity> removed = null;
16290        boolean changed = false;
16291        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16292            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16293            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16294            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16295                continue;
16296            }
16297            Iterator<PreferredActivity> it = pir.filterIterator();
16298            while (it.hasNext()) {
16299                PreferredActivity pa = it.next();
16300                // Mark entry for removal only if it matches the package name
16301                // and the entry is of type "always".
16302                if (packageName == null ||
16303                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16304                                && pa.mPref.mAlways)) {
16305                    if (removed == null) {
16306                        removed = new ArrayList<PreferredActivity>();
16307                    }
16308                    removed.add(pa);
16309                }
16310            }
16311            if (removed != null) {
16312                for (int j=0; j<removed.size(); j++) {
16313                    PreferredActivity pa = removed.get(j);
16314                    pir.removeFilter(pa);
16315                }
16316                changed = true;
16317            }
16318        }
16319        return changed;
16320    }
16321
16322    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16323    private void clearIntentFilterVerificationsLPw(int userId) {
16324        final int packageCount = mPackages.size();
16325        for (int i = 0; i < packageCount; i++) {
16326            PackageParser.Package pkg = mPackages.valueAt(i);
16327            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16328        }
16329    }
16330
16331    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16332    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16333        if (userId == UserHandle.USER_ALL) {
16334            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16335                    sUserManager.getUserIds())) {
16336                for (int oneUserId : sUserManager.getUserIds()) {
16337                    scheduleWritePackageRestrictionsLocked(oneUserId);
16338                }
16339            }
16340        } else {
16341            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16342                scheduleWritePackageRestrictionsLocked(userId);
16343            }
16344        }
16345    }
16346
16347    void clearDefaultBrowserIfNeeded(String packageName) {
16348        for (int oneUserId : sUserManager.getUserIds()) {
16349            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16350            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16351            if (packageName.equals(defaultBrowserPackageName)) {
16352                setDefaultBrowserPackageName(null, oneUserId);
16353            }
16354        }
16355    }
16356
16357    @Override
16358    public void resetApplicationPreferences(int userId) {
16359        mContext.enforceCallingOrSelfPermission(
16360                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16361        // writer
16362        synchronized (mPackages) {
16363            final long identity = Binder.clearCallingIdentity();
16364            try {
16365                clearPackagePreferredActivitiesLPw(null, userId);
16366                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16367                // TODO: We have to reset the default SMS and Phone. This requires
16368                // significant refactoring to keep all default apps in the package
16369                // manager (cleaner but more work) or have the services provide
16370                // callbacks to the package manager to request a default app reset.
16371                applyFactoryDefaultBrowserLPw(userId);
16372                clearIntentFilterVerificationsLPw(userId);
16373                primeDomainVerificationsLPw(userId);
16374                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16375                scheduleWritePackageRestrictionsLocked(userId);
16376            } finally {
16377                Binder.restoreCallingIdentity(identity);
16378            }
16379        }
16380    }
16381
16382    @Override
16383    public int getPreferredActivities(List<IntentFilter> outFilters,
16384            List<ComponentName> outActivities, String packageName) {
16385
16386        int num = 0;
16387        final int userId = UserHandle.getCallingUserId();
16388        // reader
16389        synchronized (mPackages) {
16390            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16391            if (pir != null) {
16392                final Iterator<PreferredActivity> it = pir.filterIterator();
16393                while (it.hasNext()) {
16394                    final PreferredActivity pa = it.next();
16395                    if (packageName == null
16396                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16397                                    && pa.mPref.mAlways)) {
16398                        if (outFilters != null) {
16399                            outFilters.add(new IntentFilter(pa));
16400                        }
16401                        if (outActivities != null) {
16402                            outActivities.add(pa.mPref.mComponent);
16403                        }
16404                    }
16405                }
16406            }
16407        }
16408
16409        return num;
16410    }
16411
16412    @Override
16413    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16414            int userId) {
16415        int callingUid = Binder.getCallingUid();
16416        if (callingUid != Process.SYSTEM_UID) {
16417            throw new SecurityException(
16418                    "addPersistentPreferredActivity can only be run by the system");
16419        }
16420        if (filter.countActions() == 0) {
16421            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16422            return;
16423        }
16424        synchronized (mPackages) {
16425            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16426                    ":");
16427            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16428            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16429                    new PersistentPreferredActivity(filter, activity));
16430            scheduleWritePackageRestrictionsLocked(userId);
16431        }
16432    }
16433
16434    @Override
16435    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16436        int callingUid = Binder.getCallingUid();
16437        if (callingUid != Process.SYSTEM_UID) {
16438            throw new SecurityException(
16439                    "clearPackagePersistentPreferredActivities can only be run by the system");
16440        }
16441        ArrayList<PersistentPreferredActivity> removed = null;
16442        boolean changed = false;
16443        synchronized (mPackages) {
16444            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
16445                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
16446                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
16447                        .valueAt(i);
16448                if (userId != thisUserId) {
16449                    continue;
16450                }
16451                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
16452                while (it.hasNext()) {
16453                    PersistentPreferredActivity ppa = it.next();
16454                    // Mark entry for removal only if it matches the package name.
16455                    if (ppa.mComponent.getPackageName().equals(packageName)) {
16456                        if (removed == null) {
16457                            removed = new ArrayList<PersistentPreferredActivity>();
16458                        }
16459                        removed.add(ppa);
16460                    }
16461                }
16462                if (removed != null) {
16463                    for (int j=0; j<removed.size(); j++) {
16464                        PersistentPreferredActivity ppa = removed.get(j);
16465                        ppir.removeFilter(ppa);
16466                    }
16467                    changed = true;
16468                }
16469            }
16470
16471            if (changed) {
16472                scheduleWritePackageRestrictionsLocked(userId);
16473            }
16474        }
16475    }
16476
16477    /**
16478     * Common machinery for picking apart a restored XML blob and passing
16479     * it to a caller-supplied functor to be applied to the running system.
16480     */
16481    private void restoreFromXml(XmlPullParser parser, int userId,
16482            String expectedStartTag, BlobXmlRestorer functor)
16483            throws IOException, XmlPullParserException {
16484        int type;
16485        while ((type = parser.next()) != XmlPullParser.START_TAG
16486                && type != XmlPullParser.END_DOCUMENT) {
16487        }
16488        if (type != XmlPullParser.START_TAG) {
16489            // oops didn't find a start tag?!
16490            if (DEBUG_BACKUP) {
16491                Slog.e(TAG, "Didn't find start tag during restore");
16492            }
16493            return;
16494        }
16495Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
16496        // this is supposed to be TAG_PREFERRED_BACKUP
16497        if (!expectedStartTag.equals(parser.getName())) {
16498            if (DEBUG_BACKUP) {
16499                Slog.e(TAG, "Found unexpected tag " + parser.getName());
16500            }
16501            return;
16502        }
16503
16504        // skip interfering stuff, then we're aligned with the backing implementation
16505        while ((type = parser.next()) == XmlPullParser.TEXT) { }
16506Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
16507        functor.apply(parser, userId);
16508    }
16509
16510    private interface BlobXmlRestorer {
16511        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
16512    }
16513
16514    /**
16515     * Non-Binder method, support for the backup/restore mechanism: write the
16516     * full set of preferred activities in its canonical XML format.  Returns the
16517     * XML output as a byte array, or null if there is none.
16518     */
16519    @Override
16520    public byte[] getPreferredActivityBackup(int userId) {
16521        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16522            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
16523        }
16524
16525        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16526        try {
16527            final XmlSerializer serializer = new FastXmlSerializer();
16528            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16529            serializer.startDocument(null, true);
16530            serializer.startTag(null, TAG_PREFERRED_BACKUP);
16531
16532            synchronized (mPackages) {
16533                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
16534            }
16535
16536            serializer.endTag(null, TAG_PREFERRED_BACKUP);
16537            serializer.endDocument();
16538            serializer.flush();
16539        } catch (Exception e) {
16540            if (DEBUG_BACKUP) {
16541                Slog.e(TAG, "Unable to write preferred activities for backup", e);
16542            }
16543            return null;
16544        }
16545
16546        return dataStream.toByteArray();
16547    }
16548
16549    @Override
16550    public void restorePreferredActivities(byte[] backup, int userId) {
16551        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16552            throw new SecurityException("Only the system may call restorePreferredActivities()");
16553        }
16554
16555        try {
16556            final XmlPullParser parser = Xml.newPullParser();
16557            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16558            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
16559                    new BlobXmlRestorer() {
16560                        @Override
16561                        public void apply(XmlPullParser parser, int userId)
16562                                throws XmlPullParserException, IOException {
16563                            synchronized (mPackages) {
16564                                mSettings.readPreferredActivitiesLPw(parser, userId);
16565                            }
16566                        }
16567                    } );
16568        } catch (Exception e) {
16569            if (DEBUG_BACKUP) {
16570                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16571            }
16572        }
16573    }
16574
16575    /**
16576     * Non-Binder method, support for the backup/restore mechanism: write the
16577     * default browser (etc) settings in its canonical XML format.  Returns the default
16578     * browser XML representation as a byte array, or null if there is none.
16579     */
16580    @Override
16581    public byte[] getDefaultAppsBackup(int userId) {
16582        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16583            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
16584        }
16585
16586        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16587        try {
16588            final XmlSerializer serializer = new FastXmlSerializer();
16589            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16590            serializer.startDocument(null, true);
16591            serializer.startTag(null, TAG_DEFAULT_APPS);
16592
16593            synchronized (mPackages) {
16594                mSettings.writeDefaultAppsLPr(serializer, userId);
16595            }
16596
16597            serializer.endTag(null, TAG_DEFAULT_APPS);
16598            serializer.endDocument();
16599            serializer.flush();
16600        } catch (Exception e) {
16601            if (DEBUG_BACKUP) {
16602                Slog.e(TAG, "Unable to write default apps for backup", e);
16603            }
16604            return null;
16605        }
16606
16607        return dataStream.toByteArray();
16608    }
16609
16610    @Override
16611    public void restoreDefaultApps(byte[] backup, int userId) {
16612        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16613            throw new SecurityException("Only the system may call restoreDefaultApps()");
16614        }
16615
16616        try {
16617            final XmlPullParser parser = Xml.newPullParser();
16618            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16619            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
16620                    new BlobXmlRestorer() {
16621                        @Override
16622                        public void apply(XmlPullParser parser, int userId)
16623                                throws XmlPullParserException, IOException {
16624                            synchronized (mPackages) {
16625                                mSettings.readDefaultAppsLPw(parser, userId);
16626                            }
16627                        }
16628                    } );
16629        } catch (Exception e) {
16630            if (DEBUG_BACKUP) {
16631                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
16632            }
16633        }
16634    }
16635
16636    @Override
16637    public byte[] getIntentFilterVerificationBackup(int userId) {
16638        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16639            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
16640        }
16641
16642        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16643        try {
16644            final XmlSerializer serializer = new FastXmlSerializer();
16645            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16646            serializer.startDocument(null, true);
16647            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
16648
16649            synchronized (mPackages) {
16650                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
16651            }
16652
16653            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
16654            serializer.endDocument();
16655            serializer.flush();
16656        } catch (Exception e) {
16657            if (DEBUG_BACKUP) {
16658                Slog.e(TAG, "Unable to write default apps for backup", e);
16659            }
16660            return null;
16661        }
16662
16663        return dataStream.toByteArray();
16664    }
16665
16666    @Override
16667    public void restoreIntentFilterVerification(byte[] backup, int userId) {
16668        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16669            throw new SecurityException("Only the system may call restorePreferredActivities()");
16670        }
16671
16672        try {
16673            final XmlPullParser parser = Xml.newPullParser();
16674            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16675            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
16676                    new BlobXmlRestorer() {
16677                        @Override
16678                        public void apply(XmlPullParser parser, int userId)
16679                                throws XmlPullParserException, IOException {
16680                            synchronized (mPackages) {
16681                                mSettings.readAllDomainVerificationsLPr(parser, userId);
16682                                mSettings.writeLPr();
16683                            }
16684                        }
16685                    } );
16686        } catch (Exception e) {
16687            if (DEBUG_BACKUP) {
16688                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16689            }
16690        }
16691    }
16692
16693    @Override
16694    public byte[] getPermissionGrantBackup(int userId) {
16695        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16696            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
16697        }
16698
16699        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16700        try {
16701            final XmlSerializer serializer = new FastXmlSerializer();
16702            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16703            serializer.startDocument(null, true);
16704            serializer.startTag(null, TAG_PERMISSION_BACKUP);
16705
16706            synchronized (mPackages) {
16707                serializeRuntimePermissionGrantsLPr(serializer, userId);
16708            }
16709
16710            serializer.endTag(null, TAG_PERMISSION_BACKUP);
16711            serializer.endDocument();
16712            serializer.flush();
16713        } catch (Exception e) {
16714            if (DEBUG_BACKUP) {
16715                Slog.e(TAG, "Unable to write default apps for backup", e);
16716            }
16717            return null;
16718        }
16719
16720        return dataStream.toByteArray();
16721    }
16722
16723    @Override
16724    public void restorePermissionGrants(byte[] backup, int userId) {
16725        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16726            throw new SecurityException("Only the system may call restorePermissionGrants()");
16727        }
16728
16729        try {
16730            final XmlPullParser parser = Xml.newPullParser();
16731            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16732            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
16733                    new BlobXmlRestorer() {
16734                        @Override
16735                        public void apply(XmlPullParser parser, int userId)
16736                                throws XmlPullParserException, IOException {
16737                            synchronized (mPackages) {
16738                                processRestoredPermissionGrantsLPr(parser, userId);
16739                            }
16740                        }
16741                    } );
16742        } catch (Exception e) {
16743            if (DEBUG_BACKUP) {
16744                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16745            }
16746        }
16747    }
16748
16749    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
16750            throws IOException {
16751        serializer.startTag(null, TAG_ALL_GRANTS);
16752
16753        final int N = mSettings.mPackages.size();
16754        for (int i = 0; i < N; i++) {
16755            final PackageSetting ps = mSettings.mPackages.valueAt(i);
16756            boolean pkgGrantsKnown = false;
16757
16758            PermissionsState packagePerms = ps.getPermissionsState();
16759
16760            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
16761                final int grantFlags = state.getFlags();
16762                // only look at grants that are not system/policy fixed
16763                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
16764                    final boolean isGranted = state.isGranted();
16765                    // And only back up the user-twiddled state bits
16766                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
16767                        final String packageName = mSettings.mPackages.keyAt(i);
16768                        if (!pkgGrantsKnown) {
16769                            serializer.startTag(null, TAG_GRANT);
16770                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
16771                            pkgGrantsKnown = true;
16772                        }
16773
16774                        final boolean userSet =
16775                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
16776                        final boolean userFixed =
16777                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
16778                        final boolean revoke =
16779                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
16780
16781                        serializer.startTag(null, TAG_PERMISSION);
16782                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
16783                        if (isGranted) {
16784                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
16785                        }
16786                        if (userSet) {
16787                            serializer.attribute(null, ATTR_USER_SET, "true");
16788                        }
16789                        if (userFixed) {
16790                            serializer.attribute(null, ATTR_USER_FIXED, "true");
16791                        }
16792                        if (revoke) {
16793                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
16794                        }
16795                        serializer.endTag(null, TAG_PERMISSION);
16796                    }
16797                }
16798            }
16799
16800            if (pkgGrantsKnown) {
16801                serializer.endTag(null, TAG_GRANT);
16802            }
16803        }
16804
16805        serializer.endTag(null, TAG_ALL_GRANTS);
16806    }
16807
16808    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
16809            throws XmlPullParserException, IOException {
16810        String pkgName = null;
16811        int outerDepth = parser.getDepth();
16812        int type;
16813        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
16814                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
16815            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
16816                continue;
16817            }
16818
16819            final String tagName = parser.getName();
16820            if (tagName.equals(TAG_GRANT)) {
16821                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
16822                if (DEBUG_BACKUP) {
16823                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
16824                }
16825            } else if (tagName.equals(TAG_PERMISSION)) {
16826
16827                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
16828                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
16829
16830                int newFlagSet = 0;
16831                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
16832                    newFlagSet |= FLAG_PERMISSION_USER_SET;
16833                }
16834                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
16835                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
16836                }
16837                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
16838                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
16839                }
16840                if (DEBUG_BACKUP) {
16841                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
16842                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
16843                }
16844                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16845                if (ps != null) {
16846                    // Already installed so we apply the grant immediately
16847                    if (DEBUG_BACKUP) {
16848                        Slog.v(TAG, "        + already installed; applying");
16849                    }
16850                    PermissionsState perms = ps.getPermissionsState();
16851                    BasePermission bp = mSettings.mPermissions.get(permName);
16852                    if (bp != null) {
16853                        if (isGranted) {
16854                            perms.grantRuntimePermission(bp, userId);
16855                        }
16856                        if (newFlagSet != 0) {
16857                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
16858                        }
16859                    }
16860                } else {
16861                    // Need to wait for post-restore install to apply the grant
16862                    if (DEBUG_BACKUP) {
16863                        Slog.v(TAG, "        - not yet installed; saving for later");
16864                    }
16865                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
16866                            isGranted, newFlagSet, userId);
16867                }
16868            } else {
16869                PackageManagerService.reportSettingsProblem(Log.WARN,
16870                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
16871                XmlUtils.skipCurrentTag(parser);
16872            }
16873        }
16874
16875        scheduleWriteSettingsLocked();
16876        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16877    }
16878
16879    @Override
16880    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
16881            int sourceUserId, int targetUserId, int flags) {
16882        mContext.enforceCallingOrSelfPermission(
16883                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16884        int callingUid = Binder.getCallingUid();
16885        enforceOwnerRights(ownerPackage, callingUid);
16886        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16887        if (intentFilter.countActions() == 0) {
16888            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
16889            return;
16890        }
16891        synchronized (mPackages) {
16892            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
16893                    ownerPackage, targetUserId, flags);
16894            CrossProfileIntentResolver resolver =
16895                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16896            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
16897            // We have all those whose filter is equal. Now checking if the rest is equal as well.
16898            if (existing != null) {
16899                int size = existing.size();
16900                for (int i = 0; i < size; i++) {
16901                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
16902                        return;
16903                    }
16904                }
16905            }
16906            resolver.addFilter(newFilter);
16907            scheduleWritePackageRestrictionsLocked(sourceUserId);
16908        }
16909    }
16910
16911    @Override
16912    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
16913        mContext.enforceCallingOrSelfPermission(
16914                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16915        int callingUid = Binder.getCallingUid();
16916        enforceOwnerRights(ownerPackage, callingUid);
16917        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16918        synchronized (mPackages) {
16919            CrossProfileIntentResolver resolver =
16920                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16921            ArraySet<CrossProfileIntentFilter> set =
16922                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
16923            for (CrossProfileIntentFilter filter : set) {
16924                if (filter.getOwnerPackage().equals(ownerPackage)) {
16925                    resolver.removeFilter(filter);
16926                }
16927            }
16928            scheduleWritePackageRestrictionsLocked(sourceUserId);
16929        }
16930    }
16931
16932    // Enforcing that callingUid is owning pkg on userId
16933    private void enforceOwnerRights(String pkg, int callingUid) {
16934        // The system owns everything.
16935        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
16936            return;
16937        }
16938        int callingUserId = UserHandle.getUserId(callingUid);
16939        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
16940        if (pi == null) {
16941            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
16942                    + callingUserId);
16943        }
16944        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
16945            throw new SecurityException("Calling uid " + callingUid
16946                    + " does not own package " + pkg);
16947        }
16948    }
16949
16950    @Override
16951    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
16952        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
16953    }
16954
16955    private Intent getHomeIntent() {
16956        Intent intent = new Intent(Intent.ACTION_MAIN);
16957        intent.addCategory(Intent.CATEGORY_HOME);
16958        return intent;
16959    }
16960
16961    private IntentFilter getHomeFilter() {
16962        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
16963        filter.addCategory(Intent.CATEGORY_HOME);
16964        filter.addCategory(Intent.CATEGORY_DEFAULT);
16965        return filter;
16966    }
16967
16968    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
16969            int userId) {
16970        Intent intent  = getHomeIntent();
16971        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
16972                PackageManager.GET_META_DATA, userId);
16973        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
16974                true, false, false, userId);
16975
16976        allHomeCandidates.clear();
16977        if (list != null) {
16978            for (ResolveInfo ri : list) {
16979                allHomeCandidates.add(ri);
16980            }
16981        }
16982        return (preferred == null || preferred.activityInfo == null)
16983                ? null
16984                : new ComponentName(preferred.activityInfo.packageName,
16985                        preferred.activityInfo.name);
16986    }
16987
16988    @Override
16989    public void setHomeActivity(ComponentName comp, int userId) {
16990        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
16991        getHomeActivitiesAsUser(homeActivities, userId);
16992
16993        boolean found = false;
16994
16995        final int size = homeActivities.size();
16996        final ComponentName[] set = new ComponentName[size];
16997        for (int i = 0; i < size; i++) {
16998            final ResolveInfo candidate = homeActivities.get(i);
16999            final ActivityInfo info = candidate.activityInfo;
17000            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17001            set[i] = activityName;
17002            if (!found && activityName.equals(comp)) {
17003                found = true;
17004            }
17005        }
17006        if (!found) {
17007            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17008                    + userId);
17009        }
17010        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17011                set, comp, userId);
17012    }
17013
17014    private @Nullable String getSetupWizardPackageName() {
17015        final Intent intent = new Intent(Intent.ACTION_MAIN);
17016        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17017
17018        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17019                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17020                        | MATCH_DISABLED_COMPONENTS,
17021                UserHandle.myUserId());
17022        if (matches.size() == 1) {
17023            return matches.get(0).getComponentInfo().packageName;
17024        } else {
17025            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17026                    + ": matches=" + matches);
17027            return null;
17028        }
17029    }
17030
17031    @Override
17032    public void setApplicationEnabledSetting(String appPackageName,
17033            int newState, int flags, int userId, String callingPackage) {
17034        if (!sUserManager.exists(userId)) return;
17035        if (callingPackage == null) {
17036            callingPackage = Integer.toString(Binder.getCallingUid());
17037        }
17038        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17039    }
17040
17041    @Override
17042    public void setComponentEnabledSetting(ComponentName componentName,
17043            int newState, int flags, int userId) {
17044        if (!sUserManager.exists(userId)) return;
17045        setEnabledSetting(componentName.getPackageName(),
17046                componentName.getClassName(), newState, flags, userId, null);
17047    }
17048
17049    private void setEnabledSetting(final String packageName, String className, int newState,
17050            final int flags, int userId, String callingPackage) {
17051        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17052              || newState == COMPONENT_ENABLED_STATE_ENABLED
17053              || newState == COMPONENT_ENABLED_STATE_DISABLED
17054              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17055              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17056            throw new IllegalArgumentException("Invalid new component state: "
17057                    + newState);
17058        }
17059        PackageSetting pkgSetting;
17060        final int uid = Binder.getCallingUid();
17061        final int permission = mContext.checkCallingOrSelfPermission(
17062                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17063        enforceCrossUserPermission(uid, userId,
17064                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17065        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17066        boolean sendNow = false;
17067        boolean isApp = (className == null);
17068        String componentName = isApp ? packageName : className;
17069        int packageUid = -1;
17070        ArrayList<String> components;
17071
17072        // writer
17073        synchronized (mPackages) {
17074            pkgSetting = mSettings.mPackages.get(packageName);
17075            if (pkgSetting == null) {
17076                if (className == null) {
17077                    throw new IllegalArgumentException("Unknown package: " + packageName);
17078                }
17079                throw new IllegalArgumentException(
17080                        "Unknown component: " + packageName + "/" + className);
17081            }
17082            // Allow root and verify that userId is not being specified by a different user
17083            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
17084                throw new SecurityException(
17085                        "Permission Denial: attempt to change component state from pid="
17086                        + Binder.getCallingPid()
17087                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17088            }
17089            if (className == null) {
17090                // We're dealing with an application/package level state change
17091                if (pkgSetting.getEnabled(userId) == newState) {
17092                    // Nothing to do
17093                    return;
17094                }
17095                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17096                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17097                    // Don't care about who enables an app.
17098                    callingPackage = null;
17099                }
17100                pkgSetting.setEnabled(newState, userId, callingPackage);
17101                // pkgSetting.pkg.mSetEnabled = newState;
17102            } else {
17103                // We're dealing with a component level state change
17104                // First, verify that this is a valid class name.
17105                PackageParser.Package pkg = pkgSetting.pkg;
17106                if (pkg == null || !pkg.hasComponentClassName(className)) {
17107                    if (pkg != null &&
17108                            pkg.applicationInfo.targetSdkVersion >=
17109                                    Build.VERSION_CODES.JELLY_BEAN) {
17110                        throw new IllegalArgumentException("Component class " + className
17111                                + " does not exist in " + packageName);
17112                    } else {
17113                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17114                                + className + " does not exist in " + packageName);
17115                    }
17116                }
17117                switch (newState) {
17118                case COMPONENT_ENABLED_STATE_ENABLED:
17119                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17120                        return;
17121                    }
17122                    break;
17123                case COMPONENT_ENABLED_STATE_DISABLED:
17124                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17125                        return;
17126                    }
17127                    break;
17128                case COMPONENT_ENABLED_STATE_DEFAULT:
17129                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17130                        return;
17131                    }
17132                    break;
17133                default:
17134                    Slog.e(TAG, "Invalid new component state: " + newState);
17135                    return;
17136                }
17137            }
17138            scheduleWritePackageRestrictionsLocked(userId);
17139            components = mPendingBroadcasts.get(userId, packageName);
17140            final boolean newPackage = components == null;
17141            if (newPackage) {
17142                components = new ArrayList<String>();
17143            }
17144            if (!components.contains(componentName)) {
17145                components.add(componentName);
17146            }
17147            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17148                sendNow = true;
17149                // Purge entry from pending broadcast list if another one exists already
17150                // since we are sending one right away.
17151                mPendingBroadcasts.remove(userId, packageName);
17152            } else {
17153                if (newPackage) {
17154                    mPendingBroadcasts.put(userId, packageName, components);
17155                }
17156                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17157                    // Schedule a message
17158                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17159                }
17160            }
17161        }
17162
17163        long callingId = Binder.clearCallingIdentity();
17164        try {
17165            if (sendNow) {
17166                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17167                sendPackageChangedBroadcast(packageName,
17168                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17169            }
17170        } finally {
17171            Binder.restoreCallingIdentity(callingId);
17172        }
17173    }
17174
17175    @Override
17176    public void flushPackageRestrictionsAsUser(int userId) {
17177        if (!sUserManager.exists(userId)) {
17178            return;
17179        }
17180        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17181                false /* checkShell */, "flushPackageRestrictions");
17182        synchronized (mPackages) {
17183            mSettings.writePackageRestrictionsLPr(userId);
17184            mDirtyUsers.remove(userId);
17185            if (mDirtyUsers.isEmpty()) {
17186                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17187            }
17188        }
17189    }
17190
17191    private void sendPackageChangedBroadcast(String packageName,
17192            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17193        if (DEBUG_INSTALL)
17194            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17195                    + componentNames);
17196        Bundle extras = new Bundle(4);
17197        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17198        String nameList[] = new String[componentNames.size()];
17199        componentNames.toArray(nameList);
17200        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17201        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17202        extras.putInt(Intent.EXTRA_UID, packageUid);
17203        // If this is not reporting a change of the overall package, then only send it
17204        // to registered receivers.  We don't want to launch a swath of apps for every
17205        // little component state change.
17206        final int flags = !componentNames.contains(packageName)
17207                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17208        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17209                new int[] {UserHandle.getUserId(packageUid)});
17210    }
17211
17212    @Override
17213    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17214        if (!sUserManager.exists(userId)) return;
17215        final int uid = Binder.getCallingUid();
17216        final int permission = mContext.checkCallingOrSelfPermission(
17217                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17218        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17219        enforceCrossUserPermission(uid, userId,
17220                true /* requireFullPermission */, true /* checkShell */, "stop package");
17221        // writer
17222        synchronized (mPackages) {
17223            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17224                    allowedByPermission, uid, userId)) {
17225                scheduleWritePackageRestrictionsLocked(userId);
17226            }
17227        }
17228    }
17229
17230    @Override
17231    public String getInstallerPackageName(String packageName) {
17232        // reader
17233        synchronized (mPackages) {
17234            return mSettings.getInstallerPackageNameLPr(packageName);
17235        }
17236    }
17237
17238    @Override
17239    public int getApplicationEnabledSetting(String packageName, int userId) {
17240        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17241        int uid = Binder.getCallingUid();
17242        enforceCrossUserPermission(uid, userId,
17243                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17244        // reader
17245        synchronized (mPackages) {
17246            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17247        }
17248    }
17249
17250    @Override
17251    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17252        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17253        int uid = Binder.getCallingUid();
17254        enforceCrossUserPermission(uid, userId,
17255                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17256        // reader
17257        synchronized (mPackages) {
17258            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17259        }
17260    }
17261
17262    @Override
17263    public void enterSafeMode() {
17264        enforceSystemOrRoot("Only the system can request entering safe mode");
17265
17266        if (!mSystemReady) {
17267            mSafeMode = true;
17268        }
17269    }
17270
17271    @Override
17272    public void systemReady() {
17273        mSystemReady = true;
17274
17275        // Read the compatibilty setting when the system is ready.
17276        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17277                mContext.getContentResolver(),
17278                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17279        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17280        if (DEBUG_SETTINGS) {
17281            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17282        }
17283
17284        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17285
17286        synchronized (mPackages) {
17287            // Verify that all of the preferred activity components actually
17288            // exist.  It is possible for applications to be updated and at
17289            // that point remove a previously declared activity component that
17290            // had been set as a preferred activity.  We try to clean this up
17291            // the next time we encounter that preferred activity, but it is
17292            // possible for the user flow to never be able to return to that
17293            // situation so here we do a sanity check to make sure we haven't
17294            // left any junk around.
17295            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17296            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17297                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17298                removed.clear();
17299                for (PreferredActivity pa : pir.filterSet()) {
17300                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17301                        removed.add(pa);
17302                    }
17303                }
17304                if (removed.size() > 0) {
17305                    for (int r=0; r<removed.size(); r++) {
17306                        PreferredActivity pa = removed.get(r);
17307                        Slog.w(TAG, "Removing dangling preferred activity: "
17308                                + pa.mPref.mComponent);
17309                        pir.removeFilter(pa);
17310                    }
17311                    mSettings.writePackageRestrictionsLPr(
17312                            mSettings.mPreferredActivities.keyAt(i));
17313                }
17314            }
17315
17316            for (int userId : UserManagerService.getInstance().getUserIds()) {
17317                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17318                    grantPermissionsUserIds = ArrayUtils.appendInt(
17319                            grantPermissionsUserIds, userId);
17320                }
17321            }
17322        }
17323        sUserManager.systemReady();
17324
17325        // If we upgraded grant all default permissions before kicking off.
17326        for (int userId : grantPermissionsUserIds) {
17327            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17328        }
17329
17330        // Kick off any messages waiting for system ready
17331        if (mPostSystemReadyMessages != null) {
17332            for (Message msg : mPostSystemReadyMessages) {
17333                msg.sendToTarget();
17334            }
17335            mPostSystemReadyMessages = null;
17336        }
17337
17338        // Watch for external volumes that come and go over time
17339        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17340        storage.registerListener(mStorageListener);
17341
17342        mInstallerService.systemReady();
17343        mPackageDexOptimizer.systemReady();
17344
17345        MountServiceInternal mountServiceInternal = LocalServices.getService(
17346                MountServiceInternal.class);
17347        mountServiceInternal.addExternalStoragePolicy(
17348                new MountServiceInternal.ExternalStorageMountPolicy() {
17349            @Override
17350            public int getMountMode(int uid, String packageName) {
17351                if (Process.isIsolated(uid)) {
17352                    return Zygote.MOUNT_EXTERNAL_NONE;
17353                }
17354                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17355                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17356                }
17357                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17358                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17359                }
17360                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17361                    return Zygote.MOUNT_EXTERNAL_READ;
17362                }
17363                return Zygote.MOUNT_EXTERNAL_WRITE;
17364            }
17365
17366            @Override
17367            public boolean hasExternalStorage(int uid, String packageName) {
17368                return true;
17369            }
17370        });
17371    }
17372
17373    @Override
17374    public boolean isSafeMode() {
17375        return mSafeMode;
17376    }
17377
17378    @Override
17379    public boolean hasSystemUidErrors() {
17380        return mHasSystemUidErrors;
17381    }
17382
17383    static String arrayToString(int[] array) {
17384        StringBuffer buf = new StringBuffer(128);
17385        buf.append('[');
17386        if (array != null) {
17387            for (int i=0; i<array.length; i++) {
17388                if (i > 0) buf.append(", ");
17389                buf.append(array[i]);
17390            }
17391        }
17392        buf.append(']');
17393        return buf.toString();
17394    }
17395
17396    static class DumpState {
17397        public static final int DUMP_LIBS = 1 << 0;
17398        public static final int DUMP_FEATURES = 1 << 1;
17399        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
17400        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
17401        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
17402        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
17403        public static final int DUMP_PERMISSIONS = 1 << 6;
17404        public static final int DUMP_PACKAGES = 1 << 7;
17405        public static final int DUMP_SHARED_USERS = 1 << 8;
17406        public static final int DUMP_MESSAGES = 1 << 9;
17407        public static final int DUMP_PROVIDERS = 1 << 10;
17408        public static final int DUMP_VERIFIERS = 1 << 11;
17409        public static final int DUMP_PREFERRED = 1 << 12;
17410        public static final int DUMP_PREFERRED_XML = 1 << 13;
17411        public static final int DUMP_KEYSETS = 1 << 14;
17412        public static final int DUMP_VERSION = 1 << 15;
17413        public static final int DUMP_INSTALLS = 1 << 16;
17414        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
17415        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
17416
17417        public static final int OPTION_SHOW_FILTERS = 1 << 0;
17418
17419        private int mTypes;
17420
17421        private int mOptions;
17422
17423        private boolean mTitlePrinted;
17424
17425        private SharedUserSetting mSharedUser;
17426
17427        public boolean isDumping(int type) {
17428            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
17429                return true;
17430            }
17431
17432            return (mTypes & type) != 0;
17433        }
17434
17435        public void setDump(int type) {
17436            mTypes |= type;
17437        }
17438
17439        public boolean isOptionEnabled(int option) {
17440            return (mOptions & option) != 0;
17441        }
17442
17443        public void setOptionEnabled(int option) {
17444            mOptions |= option;
17445        }
17446
17447        public boolean onTitlePrinted() {
17448            final boolean printed = mTitlePrinted;
17449            mTitlePrinted = true;
17450            return printed;
17451        }
17452
17453        public boolean getTitlePrinted() {
17454            return mTitlePrinted;
17455        }
17456
17457        public void setTitlePrinted(boolean enabled) {
17458            mTitlePrinted = enabled;
17459        }
17460
17461        public SharedUserSetting getSharedUser() {
17462            return mSharedUser;
17463        }
17464
17465        public void setSharedUser(SharedUserSetting user) {
17466            mSharedUser = user;
17467        }
17468    }
17469
17470    @Override
17471    public void onShellCommand(FileDescriptor in, FileDescriptor out,
17472            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
17473        (new PackageManagerShellCommand(this)).exec(
17474                this, in, out, err, args, resultReceiver);
17475    }
17476
17477    @Override
17478    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
17479        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
17480                != PackageManager.PERMISSION_GRANTED) {
17481            pw.println("Permission Denial: can't dump ActivityManager from from pid="
17482                    + Binder.getCallingPid()
17483                    + ", uid=" + Binder.getCallingUid()
17484                    + " without permission "
17485                    + android.Manifest.permission.DUMP);
17486            return;
17487        }
17488
17489        DumpState dumpState = new DumpState();
17490        boolean fullPreferred = false;
17491        boolean checkin = false;
17492
17493        String packageName = null;
17494        ArraySet<String> permissionNames = null;
17495
17496        int opti = 0;
17497        while (opti < args.length) {
17498            String opt = args[opti];
17499            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
17500                break;
17501            }
17502            opti++;
17503
17504            if ("-a".equals(opt)) {
17505                // Right now we only know how to print all.
17506            } else if ("-h".equals(opt)) {
17507                pw.println("Package manager dump options:");
17508                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
17509                pw.println("    --checkin: dump for a checkin");
17510                pw.println("    -f: print details of intent filters");
17511                pw.println("    -h: print this help");
17512                pw.println("  cmd may be one of:");
17513                pw.println("    l[ibraries]: list known shared libraries");
17514                pw.println("    f[eatures]: list device features");
17515                pw.println("    k[eysets]: print known keysets");
17516                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
17517                pw.println("    perm[issions]: dump permissions");
17518                pw.println("    permission [name ...]: dump declaration and use of given permission");
17519                pw.println("    pref[erred]: print preferred package settings");
17520                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
17521                pw.println("    prov[iders]: dump content providers");
17522                pw.println("    p[ackages]: dump installed packages");
17523                pw.println("    s[hared-users]: dump shared user IDs");
17524                pw.println("    m[essages]: print collected runtime messages");
17525                pw.println("    v[erifiers]: print package verifier info");
17526                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
17527                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
17528                pw.println("    version: print database version info");
17529                pw.println("    write: write current settings now");
17530                pw.println("    installs: details about install sessions");
17531                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
17532                pw.println("    <package.name>: info about given package");
17533                return;
17534            } else if ("--checkin".equals(opt)) {
17535                checkin = true;
17536            } else if ("-f".equals(opt)) {
17537                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17538            } else {
17539                pw.println("Unknown argument: " + opt + "; use -h for help");
17540            }
17541        }
17542
17543        // Is the caller requesting to dump a particular piece of data?
17544        if (opti < args.length) {
17545            String cmd = args[opti];
17546            opti++;
17547            // Is this a package name?
17548            if ("android".equals(cmd) || cmd.contains(".")) {
17549                packageName = cmd;
17550                // When dumping a single package, we always dump all of its
17551                // filter information since the amount of data will be reasonable.
17552                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17553            } else if ("check-permission".equals(cmd)) {
17554                if (opti >= args.length) {
17555                    pw.println("Error: check-permission missing permission argument");
17556                    return;
17557                }
17558                String perm = args[opti];
17559                opti++;
17560                if (opti >= args.length) {
17561                    pw.println("Error: check-permission missing package argument");
17562                    return;
17563                }
17564                String pkg = args[opti];
17565                opti++;
17566                int user = UserHandle.getUserId(Binder.getCallingUid());
17567                if (opti < args.length) {
17568                    try {
17569                        user = Integer.parseInt(args[opti]);
17570                    } catch (NumberFormatException e) {
17571                        pw.println("Error: check-permission user argument is not a number: "
17572                                + args[opti]);
17573                        return;
17574                    }
17575                }
17576                pw.println(checkPermission(perm, pkg, user));
17577                return;
17578            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
17579                dumpState.setDump(DumpState.DUMP_LIBS);
17580            } else if ("f".equals(cmd) || "features".equals(cmd)) {
17581                dumpState.setDump(DumpState.DUMP_FEATURES);
17582            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
17583                if (opti >= args.length) {
17584                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
17585                            | DumpState.DUMP_SERVICE_RESOLVERS
17586                            | DumpState.DUMP_RECEIVER_RESOLVERS
17587                            | DumpState.DUMP_CONTENT_RESOLVERS);
17588                } else {
17589                    while (opti < args.length) {
17590                        String name = args[opti];
17591                        if ("a".equals(name) || "activity".equals(name)) {
17592                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
17593                        } else if ("s".equals(name) || "service".equals(name)) {
17594                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
17595                        } else if ("r".equals(name) || "receiver".equals(name)) {
17596                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
17597                        } else if ("c".equals(name) || "content".equals(name)) {
17598                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
17599                        } else {
17600                            pw.println("Error: unknown resolver table type: " + name);
17601                            return;
17602                        }
17603                        opti++;
17604                    }
17605                }
17606            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
17607                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
17608            } else if ("permission".equals(cmd)) {
17609                if (opti >= args.length) {
17610                    pw.println("Error: permission requires permission name");
17611                    return;
17612                }
17613                permissionNames = new ArraySet<>();
17614                while (opti < args.length) {
17615                    permissionNames.add(args[opti]);
17616                    opti++;
17617                }
17618                dumpState.setDump(DumpState.DUMP_PERMISSIONS
17619                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
17620            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
17621                dumpState.setDump(DumpState.DUMP_PREFERRED);
17622            } else if ("preferred-xml".equals(cmd)) {
17623                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
17624                if (opti < args.length && "--full".equals(args[opti])) {
17625                    fullPreferred = true;
17626                    opti++;
17627                }
17628            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
17629                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
17630            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
17631                dumpState.setDump(DumpState.DUMP_PACKAGES);
17632            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
17633                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
17634            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
17635                dumpState.setDump(DumpState.DUMP_PROVIDERS);
17636            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
17637                dumpState.setDump(DumpState.DUMP_MESSAGES);
17638            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
17639                dumpState.setDump(DumpState.DUMP_VERIFIERS);
17640            } else if ("i".equals(cmd) || "ifv".equals(cmd)
17641                    || "intent-filter-verifiers".equals(cmd)) {
17642                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
17643            } else if ("version".equals(cmd)) {
17644                dumpState.setDump(DumpState.DUMP_VERSION);
17645            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
17646                dumpState.setDump(DumpState.DUMP_KEYSETS);
17647            } else if ("installs".equals(cmd)) {
17648                dumpState.setDump(DumpState.DUMP_INSTALLS);
17649            } else if ("write".equals(cmd)) {
17650                synchronized (mPackages) {
17651                    mSettings.writeLPr();
17652                    pw.println("Settings written.");
17653                    return;
17654                }
17655            }
17656        }
17657
17658        if (checkin) {
17659            pw.println("vers,1");
17660        }
17661
17662        // reader
17663        synchronized (mPackages) {
17664            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
17665                if (!checkin) {
17666                    if (dumpState.onTitlePrinted())
17667                        pw.println();
17668                    pw.println("Database versions:");
17669                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
17670                }
17671            }
17672
17673            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
17674                if (!checkin) {
17675                    if (dumpState.onTitlePrinted())
17676                        pw.println();
17677                    pw.println("Verifiers:");
17678                    pw.print("  Required: ");
17679                    pw.print(mRequiredVerifierPackage);
17680                    pw.print(" (uid=");
17681                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17682                            UserHandle.USER_SYSTEM));
17683                    pw.println(")");
17684                } else if (mRequiredVerifierPackage != null) {
17685                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
17686                    pw.print(",");
17687                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17688                            UserHandle.USER_SYSTEM));
17689                }
17690            }
17691
17692            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
17693                    packageName == null) {
17694                if (mIntentFilterVerifierComponent != null) {
17695                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
17696                    if (!checkin) {
17697                        if (dumpState.onTitlePrinted())
17698                            pw.println();
17699                        pw.println("Intent Filter Verifier:");
17700                        pw.print("  Using: ");
17701                        pw.print(verifierPackageName);
17702                        pw.print(" (uid=");
17703                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17704                                UserHandle.USER_SYSTEM));
17705                        pw.println(")");
17706                    } else if (verifierPackageName != null) {
17707                        pw.print("ifv,"); pw.print(verifierPackageName);
17708                        pw.print(",");
17709                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17710                                UserHandle.USER_SYSTEM));
17711                    }
17712                } else {
17713                    pw.println();
17714                    pw.println("No Intent Filter Verifier available!");
17715                }
17716            }
17717
17718            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
17719                boolean printedHeader = false;
17720                final Iterator<String> it = mSharedLibraries.keySet().iterator();
17721                while (it.hasNext()) {
17722                    String name = it.next();
17723                    SharedLibraryEntry ent = mSharedLibraries.get(name);
17724                    if (!checkin) {
17725                        if (!printedHeader) {
17726                            if (dumpState.onTitlePrinted())
17727                                pw.println();
17728                            pw.println("Libraries:");
17729                            printedHeader = true;
17730                        }
17731                        pw.print("  ");
17732                    } else {
17733                        pw.print("lib,");
17734                    }
17735                    pw.print(name);
17736                    if (!checkin) {
17737                        pw.print(" -> ");
17738                    }
17739                    if (ent.path != null) {
17740                        if (!checkin) {
17741                            pw.print("(jar) ");
17742                            pw.print(ent.path);
17743                        } else {
17744                            pw.print(",jar,");
17745                            pw.print(ent.path);
17746                        }
17747                    } else {
17748                        if (!checkin) {
17749                            pw.print("(apk) ");
17750                            pw.print(ent.apk);
17751                        } else {
17752                            pw.print(",apk,");
17753                            pw.print(ent.apk);
17754                        }
17755                    }
17756                    pw.println();
17757                }
17758            }
17759
17760            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
17761                if (dumpState.onTitlePrinted())
17762                    pw.println();
17763                if (!checkin) {
17764                    pw.println("Features:");
17765                }
17766
17767                for (FeatureInfo feat : mAvailableFeatures.values()) {
17768                    if (checkin) {
17769                        pw.print("feat,");
17770                        pw.print(feat.name);
17771                        pw.print(",");
17772                        pw.println(feat.version);
17773                    } else {
17774                        pw.print("  ");
17775                        pw.print(feat.name);
17776                        if (feat.version > 0) {
17777                            pw.print(" version=");
17778                            pw.print(feat.version);
17779                        }
17780                        pw.println();
17781                    }
17782                }
17783            }
17784
17785            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
17786                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
17787                        : "Activity Resolver Table:", "  ", packageName,
17788                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17789                    dumpState.setTitlePrinted(true);
17790                }
17791            }
17792            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
17793                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
17794                        : "Receiver Resolver Table:", "  ", packageName,
17795                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17796                    dumpState.setTitlePrinted(true);
17797                }
17798            }
17799            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
17800                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
17801                        : "Service Resolver Table:", "  ", packageName,
17802                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17803                    dumpState.setTitlePrinted(true);
17804                }
17805            }
17806            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
17807                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
17808                        : "Provider Resolver Table:", "  ", packageName,
17809                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17810                    dumpState.setTitlePrinted(true);
17811                }
17812            }
17813
17814            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
17815                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17816                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17817                    int user = mSettings.mPreferredActivities.keyAt(i);
17818                    if (pir.dump(pw,
17819                            dumpState.getTitlePrinted()
17820                                ? "\nPreferred Activities User " + user + ":"
17821                                : "Preferred Activities User " + user + ":", "  ",
17822                            packageName, true, false)) {
17823                        dumpState.setTitlePrinted(true);
17824                    }
17825                }
17826            }
17827
17828            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
17829                pw.flush();
17830                FileOutputStream fout = new FileOutputStream(fd);
17831                BufferedOutputStream str = new BufferedOutputStream(fout);
17832                XmlSerializer serializer = new FastXmlSerializer();
17833                try {
17834                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
17835                    serializer.startDocument(null, true);
17836                    serializer.setFeature(
17837                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
17838                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
17839                    serializer.endDocument();
17840                    serializer.flush();
17841                } catch (IllegalArgumentException e) {
17842                    pw.println("Failed writing: " + e);
17843                } catch (IllegalStateException e) {
17844                    pw.println("Failed writing: " + e);
17845                } catch (IOException e) {
17846                    pw.println("Failed writing: " + e);
17847                }
17848            }
17849
17850            if (!checkin
17851                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
17852                    && packageName == null) {
17853                pw.println();
17854                int count = mSettings.mPackages.size();
17855                if (count == 0) {
17856                    pw.println("No applications!");
17857                    pw.println();
17858                } else {
17859                    final String prefix = "  ";
17860                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
17861                    if (allPackageSettings.size() == 0) {
17862                        pw.println("No domain preferred apps!");
17863                        pw.println();
17864                    } else {
17865                        pw.println("App verification status:");
17866                        pw.println();
17867                        count = 0;
17868                        for (PackageSetting ps : allPackageSettings) {
17869                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
17870                            if (ivi == null || ivi.getPackageName() == null) continue;
17871                            pw.println(prefix + "Package: " + ivi.getPackageName());
17872                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
17873                            pw.println(prefix + "Status:  " + ivi.getStatusString());
17874                            pw.println();
17875                            count++;
17876                        }
17877                        if (count == 0) {
17878                            pw.println(prefix + "No app verification established.");
17879                            pw.println();
17880                        }
17881                        for (int userId : sUserManager.getUserIds()) {
17882                            pw.println("App linkages for user " + userId + ":");
17883                            pw.println();
17884                            count = 0;
17885                            for (PackageSetting ps : allPackageSettings) {
17886                                final long status = ps.getDomainVerificationStatusForUser(userId);
17887                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
17888                                    continue;
17889                                }
17890                                pw.println(prefix + "Package: " + ps.name);
17891                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
17892                                String statusStr = IntentFilterVerificationInfo.
17893                                        getStatusStringFromValue(status);
17894                                pw.println(prefix + "Status:  " + statusStr);
17895                                pw.println();
17896                                count++;
17897                            }
17898                            if (count == 0) {
17899                                pw.println(prefix + "No configured app linkages.");
17900                                pw.println();
17901                            }
17902                        }
17903                    }
17904                }
17905            }
17906
17907            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
17908                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
17909                if (packageName == null && permissionNames == null) {
17910                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
17911                        if (iperm == 0) {
17912                            if (dumpState.onTitlePrinted())
17913                                pw.println();
17914                            pw.println("AppOp Permissions:");
17915                        }
17916                        pw.print("  AppOp Permission ");
17917                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
17918                        pw.println(":");
17919                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
17920                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
17921                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
17922                        }
17923                    }
17924                }
17925            }
17926
17927            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
17928                boolean printedSomething = false;
17929                for (PackageParser.Provider p : mProviders.mProviders.values()) {
17930                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17931                        continue;
17932                    }
17933                    if (!printedSomething) {
17934                        if (dumpState.onTitlePrinted())
17935                            pw.println();
17936                        pw.println("Registered ContentProviders:");
17937                        printedSomething = true;
17938                    }
17939                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
17940                    pw.print("    "); pw.println(p.toString());
17941                }
17942                printedSomething = false;
17943                for (Map.Entry<String, PackageParser.Provider> entry :
17944                        mProvidersByAuthority.entrySet()) {
17945                    PackageParser.Provider p = entry.getValue();
17946                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17947                        continue;
17948                    }
17949                    if (!printedSomething) {
17950                        if (dumpState.onTitlePrinted())
17951                            pw.println();
17952                        pw.println("ContentProvider Authorities:");
17953                        printedSomething = true;
17954                    }
17955                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
17956                    pw.print("    "); pw.println(p.toString());
17957                    if (p.info != null && p.info.applicationInfo != null) {
17958                        final String appInfo = p.info.applicationInfo.toString();
17959                        pw.print("      applicationInfo="); pw.println(appInfo);
17960                    }
17961                }
17962            }
17963
17964            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
17965                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
17966            }
17967
17968            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
17969                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
17970            }
17971
17972            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
17973                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
17974            }
17975
17976            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
17977                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
17978            }
17979
17980            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
17981                // XXX should handle packageName != null by dumping only install data that
17982                // the given package is involved with.
17983                if (dumpState.onTitlePrinted()) pw.println();
17984                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
17985            }
17986
17987            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
17988                if (dumpState.onTitlePrinted()) pw.println();
17989                mSettings.dumpReadMessagesLPr(pw, dumpState);
17990
17991                pw.println();
17992                pw.println("Package warning messages:");
17993                BufferedReader in = null;
17994                String line = null;
17995                try {
17996                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17997                    while ((line = in.readLine()) != null) {
17998                        if (line.contains("ignored: updated version")) continue;
17999                        pw.println(line);
18000                    }
18001                } catch (IOException ignored) {
18002                } finally {
18003                    IoUtils.closeQuietly(in);
18004                }
18005            }
18006
18007            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18008                BufferedReader in = null;
18009                String line = null;
18010                try {
18011                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18012                    while ((line = in.readLine()) != null) {
18013                        if (line.contains("ignored: updated version")) continue;
18014                        pw.print("msg,");
18015                        pw.println(line);
18016                    }
18017                } catch (IOException ignored) {
18018                } finally {
18019                    IoUtils.closeQuietly(in);
18020                }
18021            }
18022        }
18023    }
18024
18025    private String dumpDomainString(String packageName) {
18026        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18027                .getList();
18028        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18029
18030        ArraySet<String> result = new ArraySet<>();
18031        if (iviList.size() > 0) {
18032            for (IntentFilterVerificationInfo ivi : iviList) {
18033                for (String host : ivi.getDomains()) {
18034                    result.add(host);
18035                }
18036            }
18037        }
18038        if (filters != null && filters.size() > 0) {
18039            for (IntentFilter filter : filters) {
18040                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18041                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18042                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18043                    result.addAll(filter.getHostsList());
18044                }
18045            }
18046        }
18047
18048        StringBuilder sb = new StringBuilder(result.size() * 16);
18049        for (String domain : result) {
18050            if (sb.length() > 0) sb.append(" ");
18051            sb.append(domain);
18052        }
18053        return sb.toString();
18054    }
18055
18056    // ------- apps on sdcard specific code -------
18057    static final boolean DEBUG_SD_INSTALL = false;
18058
18059    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18060
18061    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18062
18063    private boolean mMediaMounted = false;
18064
18065    static String getEncryptKey() {
18066        try {
18067            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18068                    SD_ENCRYPTION_KEYSTORE_NAME);
18069            if (sdEncKey == null) {
18070                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18071                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18072                if (sdEncKey == null) {
18073                    Slog.e(TAG, "Failed to create encryption keys");
18074                    return null;
18075                }
18076            }
18077            return sdEncKey;
18078        } catch (NoSuchAlgorithmException nsae) {
18079            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18080            return null;
18081        } catch (IOException ioe) {
18082            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18083            return null;
18084        }
18085    }
18086
18087    /*
18088     * Update media status on PackageManager.
18089     */
18090    @Override
18091    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18092        int callingUid = Binder.getCallingUid();
18093        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18094            throw new SecurityException("Media status can only be updated by the system");
18095        }
18096        // reader; this apparently protects mMediaMounted, but should probably
18097        // be a different lock in that case.
18098        synchronized (mPackages) {
18099            Log.i(TAG, "Updating external media status from "
18100                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18101                    + (mediaStatus ? "mounted" : "unmounted"));
18102            if (DEBUG_SD_INSTALL)
18103                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18104                        + ", mMediaMounted=" + mMediaMounted);
18105            if (mediaStatus == mMediaMounted) {
18106                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18107                        : 0, -1);
18108                mHandler.sendMessage(msg);
18109                return;
18110            }
18111            mMediaMounted = mediaStatus;
18112        }
18113        // Queue up an async operation since the package installation may take a
18114        // little while.
18115        mHandler.post(new Runnable() {
18116            public void run() {
18117                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18118            }
18119        });
18120    }
18121
18122    /**
18123     * Called by MountService when the initial ASECs to scan are available.
18124     * Should block until all the ASEC containers are finished being scanned.
18125     */
18126    public void scanAvailableAsecs() {
18127        updateExternalMediaStatusInner(true, false, false);
18128    }
18129
18130    /*
18131     * Collect information of applications on external media, map them against
18132     * existing containers and update information based on current mount status.
18133     * Please note that we always have to report status if reportStatus has been
18134     * set to true especially when unloading packages.
18135     */
18136    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18137            boolean externalStorage) {
18138        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18139        int[] uidArr = EmptyArray.INT;
18140
18141        final String[] list = PackageHelper.getSecureContainerList();
18142        if (ArrayUtils.isEmpty(list)) {
18143            Log.i(TAG, "No secure containers found");
18144        } else {
18145            // Process list of secure containers and categorize them
18146            // as active or stale based on their package internal state.
18147
18148            // reader
18149            synchronized (mPackages) {
18150                for (String cid : list) {
18151                    // Leave stages untouched for now; installer service owns them
18152                    if (PackageInstallerService.isStageName(cid)) continue;
18153
18154                    if (DEBUG_SD_INSTALL)
18155                        Log.i(TAG, "Processing container " + cid);
18156                    String pkgName = getAsecPackageName(cid);
18157                    if (pkgName == null) {
18158                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18159                        continue;
18160                    }
18161                    if (DEBUG_SD_INSTALL)
18162                        Log.i(TAG, "Looking for pkg : " + pkgName);
18163
18164                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18165                    if (ps == null) {
18166                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18167                        continue;
18168                    }
18169
18170                    /*
18171                     * Skip packages that are not external if we're unmounting
18172                     * external storage.
18173                     */
18174                    if (externalStorage && !isMounted && !isExternal(ps)) {
18175                        continue;
18176                    }
18177
18178                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18179                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18180                    // The package status is changed only if the code path
18181                    // matches between settings and the container id.
18182                    if (ps.codePathString != null
18183                            && ps.codePathString.startsWith(args.getCodePath())) {
18184                        if (DEBUG_SD_INSTALL) {
18185                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18186                                    + " at code path: " + ps.codePathString);
18187                        }
18188
18189                        // We do have a valid package installed on sdcard
18190                        processCids.put(args, ps.codePathString);
18191                        final int uid = ps.appId;
18192                        if (uid != -1) {
18193                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18194                        }
18195                    } else {
18196                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18197                                + ps.codePathString);
18198                    }
18199                }
18200            }
18201
18202            Arrays.sort(uidArr);
18203        }
18204
18205        // Process packages with valid entries.
18206        if (isMounted) {
18207            if (DEBUG_SD_INSTALL)
18208                Log.i(TAG, "Loading packages");
18209            loadMediaPackages(processCids, uidArr, externalStorage);
18210            startCleaningPackages();
18211            mInstallerService.onSecureContainersAvailable();
18212        } else {
18213            if (DEBUG_SD_INSTALL)
18214                Log.i(TAG, "Unloading packages");
18215            unloadMediaPackages(processCids, uidArr, reportStatus);
18216        }
18217    }
18218
18219    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18220            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18221        final int size = infos.size();
18222        final String[] packageNames = new String[size];
18223        final int[] packageUids = new int[size];
18224        for (int i = 0; i < size; i++) {
18225            final ApplicationInfo info = infos.get(i);
18226            packageNames[i] = info.packageName;
18227            packageUids[i] = info.uid;
18228        }
18229        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18230                finishedReceiver);
18231    }
18232
18233    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18234            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18235        sendResourcesChangedBroadcast(mediaStatus, replacing,
18236                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18237    }
18238
18239    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18240            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18241        int size = pkgList.length;
18242        if (size > 0) {
18243            // Send broadcasts here
18244            Bundle extras = new Bundle();
18245            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18246            if (uidArr != null) {
18247                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18248            }
18249            if (replacing) {
18250                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18251            }
18252            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18253                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18254            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18255        }
18256    }
18257
18258   /*
18259     * Look at potentially valid container ids from processCids If package
18260     * information doesn't match the one on record or package scanning fails,
18261     * the cid is added to list of removeCids. We currently don't delete stale
18262     * containers.
18263     */
18264    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18265            boolean externalStorage) {
18266        ArrayList<String> pkgList = new ArrayList<String>();
18267        Set<AsecInstallArgs> keys = processCids.keySet();
18268
18269        for (AsecInstallArgs args : keys) {
18270            String codePath = processCids.get(args);
18271            if (DEBUG_SD_INSTALL)
18272                Log.i(TAG, "Loading container : " + args.cid);
18273            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
18274            try {
18275                // Make sure there are no container errors first.
18276                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
18277                    Slog.e(TAG, "Failed to mount cid : " + args.cid
18278                            + " when installing from sdcard");
18279                    continue;
18280                }
18281                // Check code path here.
18282                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
18283                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
18284                            + " does not match one in settings " + codePath);
18285                    continue;
18286                }
18287                // Parse package
18288                int parseFlags = mDefParseFlags;
18289                if (args.isExternalAsec()) {
18290                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
18291                }
18292                if (args.isFwdLocked()) {
18293                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
18294                }
18295
18296                synchronized (mInstallLock) {
18297                    PackageParser.Package pkg = null;
18298                    try {
18299                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
18300                    } catch (PackageManagerException e) {
18301                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
18302                    }
18303                    // Scan the package
18304                    if (pkg != null) {
18305                        /*
18306                         * TODO why is the lock being held? doPostInstall is
18307                         * called in other places without the lock. This needs
18308                         * to be straightened out.
18309                         */
18310                        // writer
18311                        synchronized (mPackages) {
18312                            retCode = PackageManager.INSTALL_SUCCEEDED;
18313                            pkgList.add(pkg.packageName);
18314                            // Post process args
18315                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
18316                                    pkg.applicationInfo.uid);
18317                        }
18318                    } else {
18319                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
18320                    }
18321                }
18322
18323            } finally {
18324                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
18325                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
18326                }
18327            }
18328        }
18329        // writer
18330        synchronized (mPackages) {
18331            // If the platform SDK has changed since the last time we booted,
18332            // we need to re-grant app permission to catch any new ones that
18333            // appear. This is really a hack, and means that apps can in some
18334            // cases get permissions that the user didn't initially explicitly
18335            // allow... it would be nice to have some better way to handle
18336            // this situation.
18337            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
18338                    : mSettings.getInternalVersion();
18339            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
18340                    : StorageManager.UUID_PRIVATE_INTERNAL;
18341
18342            int updateFlags = UPDATE_PERMISSIONS_ALL;
18343            if (ver.sdkVersion != mSdkVersion) {
18344                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18345                        + mSdkVersion + "; regranting permissions for external");
18346                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18347            }
18348            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18349
18350            // Yay, everything is now upgraded
18351            ver.forceCurrent();
18352
18353            // can downgrade to reader
18354            // Persist settings
18355            mSettings.writeLPr();
18356        }
18357        // Send a broadcast to let everyone know we are done processing
18358        if (pkgList.size() > 0) {
18359            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
18360        }
18361    }
18362
18363   /*
18364     * Utility method to unload a list of specified containers
18365     */
18366    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
18367        // Just unmount all valid containers.
18368        for (AsecInstallArgs arg : cidArgs) {
18369            synchronized (mInstallLock) {
18370                arg.doPostDeleteLI(false);
18371           }
18372       }
18373   }
18374
18375    /*
18376     * Unload packages mounted on external media. This involves deleting package
18377     * data from internal structures, sending broadcasts about disabled packages,
18378     * gc'ing to free up references, unmounting all secure containers
18379     * corresponding to packages on external media, and posting a
18380     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
18381     * that we always have to post this message if status has been requested no
18382     * matter what.
18383     */
18384    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
18385            final boolean reportStatus) {
18386        if (DEBUG_SD_INSTALL)
18387            Log.i(TAG, "unloading media packages");
18388        ArrayList<String> pkgList = new ArrayList<String>();
18389        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
18390        final Set<AsecInstallArgs> keys = processCids.keySet();
18391        for (AsecInstallArgs args : keys) {
18392            String pkgName = args.getPackageName();
18393            if (DEBUG_SD_INSTALL)
18394                Log.i(TAG, "Trying to unload pkg : " + pkgName);
18395            // Delete package internally
18396            PackageRemovedInfo outInfo = new PackageRemovedInfo();
18397            synchronized (mInstallLock) {
18398                boolean res = deletePackageLI(pkgName, null, false, null,
18399                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null);
18400                if (res) {
18401                    pkgList.add(pkgName);
18402                } else {
18403                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
18404                    failedList.add(args);
18405                }
18406            }
18407        }
18408
18409        // reader
18410        synchronized (mPackages) {
18411            // We didn't update the settings after removing each package;
18412            // write them now for all packages.
18413            mSettings.writeLPr();
18414        }
18415
18416        // We have to absolutely send UPDATED_MEDIA_STATUS only
18417        // after confirming that all the receivers processed the ordered
18418        // broadcast when packages get disabled, force a gc to clean things up.
18419        // and unload all the containers.
18420        if (pkgList.size() > 0) {
18421            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
18422                    new IIntentReceiver.Stub() {
18423                public void performReceive(Intent intent, int resultCode, String data,
18424                        Bundle extras, boolean ordered, boolean sticky,
18425                        int sendingUser) throws RemoteException {
18426                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
18427                            reportStatus ? 1 : 0, 1, keys);
18428                    mHandler.sendMessage(msg);
18429                }
18430            });
18431        } else {
18432            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
18433                    keys);
18434            mHandler.sendMessage(msg);
18435        }
18436    }
18437
18438    private void loadPrivatePackages(final VolumeInfo vol) {
18439        mHandler.post(new Runnable() {
18440            @Override
18441            public void run() {
18442                loadPrivatePackagesInner(vol);
18443            }
18444        });
18445    }
18446
18447    private void loadPrivatePackagesInner(VolumeInfo vol) {
18448        final String volumeUuid = vol.fsUuid;
18449        if (TextUtils.isEmpty(volumeUuid)) {
18450            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
18451            return;
18452        }
18453
18454        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
18455        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
18456
18457        final VersionInfo ver;
18458        final List<PackageSetting> packages;
18459        synchronized (mPackages) {
18460            ver = mSettings.findOrCreateVersion(volumeUuid);
18461            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18462        }
18463
18464        // TODO: introduce a new concept similar to "frozen" to prevent these
18465        // apps from being launched until after data has been fully reconciled
18466        for (PackageSetting ps : packages) {
18467            synchronized (mInstallLock) {
18468                final PackageParser.Package pkg;
18469                try {
18470                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
18471                    loaded.add(pkg.applicationInfo);
18472
18473                } catch (PackageManagerException e) {
18474                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
18475                }
18476
18477                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
18478                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
18479                }
18480            }
18481        }
18482
18483        // Reconcile app data for all started/unlocked users
18484        final StorageManager sm = mContext.getSystemService(StorageManager.class);
18485        final UserManager um = mContext.getSystemService(UserManager.class);
18486        for (UserInfo user : um.getUsers()) {
18487            final int flags;
18488            if (um.isUserUnlocked(user.id)) {
18489                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18490            } else if (um.isUserRunning(user.id)) {
18491                flags = StorageManager.FLAG_STORAGE_DE;
18492            } else {
18493                continue;
18494            }
18495
18496            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
18497            reconcileAppsData(volumeUuid, user.id, flags);
18498        }
18499
18500        synchronized (mPackages) {
18501            int updateFlags = UPDATE_PERMISSIONS_ALL;
18502            if (ver.sdkVersion != mSdkVersion) {
18503                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18504                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
18505                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18506            }
18507            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18508
18509            // Yay, everything is now upgraded
18510            ver.forceCurrent();
18511
18512            mSettings.writeLPr();
18513        }
18514
18515        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
18516        sendResourcesChangedBroadcast(true, false, loaded, null);
18517    }
18518
18519    private void unloadPrivatePackages(final VolumeInfo vol) {
18520        mHandler.post(new Runnable() {
18521            @Override
18522            public void run() {
18523                unloadPrivatePackagesInner(vol);
18524            }
18525        });
18526    }
18527
18528    private void unloadPrivatePackagesInner(VolumeInfo vol) {
18529        final String volumeUuid = vol.fsUuid;
18530        if (TextUtils.isEmpty(volumeUuid)) {
18531            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
18532            return;
18533        }
18534
18535        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
18536        synchronized (mInstallLock) {
18537        synchronized (mPackages) {
18538            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
18539            for (PackageSetting ps : packages) {
18540                if (ps.pkg == null) continue;
18541
18542                final ApplicationInfo info = ps.pkg.applicationInfo;
18543                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
18544                if (deletePackageLI(ps.name, null, false, null,
18545                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) {
18546                    unloaded.add(info);
18547                } else {
18548                    Slog.w(TAG, "Failed to unload " + ps.codePath);
18549                }
18550            }
18551
18552            mSettings.writeLPr();
18553        }
18554        }
18555
18556        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
18557        sendResourcesChangedBroadcast(false, false, unloaded, null);
18558    }
18559
18560    /**
18561     * Examine all users present on given mounted volume, and destroy data
18562     * belonging to users that are no longer valid, or whose user ID has been
18563     * recycled.
18564     */
18565    private void reconcileUsers(String volumeUuid) {
18566        // TODO: also reconcile DE directories
18567        final File[] files = FileUtils
18568                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid));
18569        for (File file : files) {
18570            if (!file.isDirectory()) continue;
18571
18572            final int userId;
18573            final UserInfo info;
18574            try {
18575                userId = Integer.parseInt(file.getName());
18576                info = sUserManager.getUserInfo(userId);
18577            } catch (NumberFormatException e) {
18578                Slog.w(TAG, "Invalid user directory " + file);
18579                continue;
18580            }
18581
18582            boolean destroyUser = false;
18583            if (info == null) {
18584                logCriticalInfo(Log.WARN, "Destroying user directory " + file
18585                        + " because no matching user was found");
18586                destroyUser = true;
18587            } else {
18588                try {
18589                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
18590                } catch (IOException e) {
18591                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
18592                            + " because we failed to enforce serial number: " + e);
18593                    destroyUser = true;
18594                }
18595            }
18596
18597            if (destroyUser) {
18598                synchronized (mInstallLock) {
18599                    try {
18600                        mInstaller.removeUserDataDirs(volumeUuid, userId);
18601                    } catch (InstallerException e) {
18602                        Slog.w(TAG, "Failed to clean up user dirs", e);
18603                    }
18604                }
18605            }
18606        }
18607    }
18608
18609    private void assertPackageKnown(String volumeUuid, String packageName)
18610            throws PackageManagerException {
18611        synchronized (mPackages) {
18612            final PackageSetting ps = mSettings.mPackages.get(packageName);
18613            if (ps == null) {
18614                throw new PackageManagerException("Package " + packageName + " is unknown");
18615            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18616                throw new PackageManagerException(
18617                        "Package " + packageName + " found on unknown volume " + volumeUuid
18618                                + "; expected volume " + ps.volumeUuid);
18619            }
18620        }
18621    }
18622
18623    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
18624            throws PackageManagerException {
18625        synchronized (mPackages) {
18626            final PackageSetting ps = mSettings.mPackages.get(packageName);
18627            if (ps == null) {
18628                throw new PackageManagerException("Package " + packageName + " is unknown");
18629            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18630                throw new PackageManagerException(
18631                        "Package " + packageName + " found on unknown volume " + volumeUuid
18632                                + "; expected volume " + ps.volumeUuid);
18633            } else if (!ps.getInstalled(userId)) {
18634                throw new PackageManagerException(
18635                        "Package " + packageName + " not installed for user " + userId);
18636            }
18637        }
18638    }
18639
18640    /**
18641     * Examine all apps present on given mounted volume, and destroy apps that
18642     * aren't expected, either due to uninstallation or reinstallation on
18643     * another volume.
18644     */
18645    private void reconcileApps(String volumeUuid) {
18646        final File[] files = FileUtils
18647                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
18648        for (File file : files) {
18649            final boolean isPackage = (isApkFile(file) || file.isDirectory())
18650                    && !PackageInstallerService.isStageName(file.getName());
18651            if (!isPackage) {
18652                // Ignore entries which are not packages
18653                continue;
18654            }
18655
18656            try {
18657                final PackageLite pkg = PackageParser.parsePackageLite(file,
18658                        PackageParser.PARSE_MUST_BE_APK);
18659                assertPackageKnown(volumeUuid, pkg.packageName);
18660
18661            } catch (PackageParserException | PackageManagerException e) {
18662                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18663                synchronized (mInstallLock) {
18664                    removeCodePathLI(file);
18665                }
18666            }
18667        }
18668    }
18669
18670    /**
18671     * Reconcile all app data for the given user.
18672     * <p>
18673     * Verifies that directories exist and that ownership and labeling is
18674     * correct for all installed apps on all mounted volumes.
18675     */
18676    void reconcileAppsData(int userId, int flags) {
18677        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18678        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18679            final String volumeUuid = vol.getFsUuid();
18680            reconcileAppsData(volumeUuid, userId, flags);
18681        }
18682    }
18683
18684    /**
18685     * Reconcile all app data on given mounted volume.
18686     * <p>
18687     * Destroys app data that isn't expected, either due to uninstallation or
18688     * reinstallation on another volume.
18689     * <p>
18690     * Verifies that directories exist and that ownership and labeling is
18691     * correct for all installed apps.
18692     */
18693    private void reconcileAppsData(String volumeUuid, int userId, int flags) {
18694        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
18695                + Integer.toHexString(flags));
18696
18697        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
18698        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
18699
18700        boolean restoreconNeeded = false;
18701
18702        // First look for stale data that doesn't belong, and check if things
18703        // have changed since we did our last restorecon
18704        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18705            if (!isUserKeyUnlocked(userId)) {
18706                throw new RuntimeException(
18707                        "Yikes, someone asked us to reconcile CE storage while " + userId
18708                                + " was still locked; this would have caused massive data loss!");
18709            }
18710
18711            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
18712
18713            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
18714            for (File file : files) {
18715                final String packageName = file.getName();
18716                try {
18717                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18718                } catch (PackageManagerException e) {
18719                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18720                    synchronized (mInstallLock) {
18721                        destroyAppDataLI(volumeUuid, packageName, userId,
18722                                StorageManager.FLAG_STORAGE_CE);
18723                    }
18724                }
18725            }
18726        }
18727        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18728            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
18729
18730            final File[] files = FileUtils.listFilesOrEmpty(deDir);
18731            for (File file : files) {
18732                final String packageName = file.getName();
18733                try {
18734                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18735                } catch (PackageManagerException e) {
18736                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18737                    synchronized (mInstallLock) {
18738                        destroyAppDataLI(volumeUuid, packageName, userId,
18739                                StorageManager.FLAG_STORAGE_DE);
18740                    }
18741                }
18742            }
18743        }
18744
18745        // Ensure that data directories are ready to roll for all packages
18746        // installed for this volume and user
18747        final List<PackageSetting> packages;
18748        synchronized (mPackages) {
18749            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18750        }
18751        int preparedCount = 0;
18752        for (PackageSetting ps : packages) {
18753            final String packageName = ps.name;
18754            if (ps.pkg == null) {
18755                Slog.w(TAG, "Odd, missing scanned package " + packageName);
18756                // TODO: might be due to legacy ASEC apps; we should circle back
18757                // and reconcile again once they're scanned
18758                continue;
18759            }
18760
18761            if (ps.getInstalled(userId)) {
18762                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
18763
18764                if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) {
18765                    // We may have just shuffled around app data directories, so
18766                    // prepare them one more time
18767                    prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
18768                }
18769
18770                preparedCount++;
18771            }
18772        }
18773
18774        if (restoreconNeeded) {
18775            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18776                SELinuxMMAC.setRestoreconDone(ceDir);
18777            }
18778            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18779                SELinuxMMAC.setRestoreconDone(deDir);
18780            }
18781        }
18782
18783        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
18784                + " packages; restoreconNeeded was " + restoreconNeeded);
18785    }
18786
18787    /**
18788     * Prepare app data for the given app just after it was installed or
18789     * upgraded. This method carefully only touches users that it's installed
18790     * for, and it forces a restorecon to handle any seinfo changes.
18791     * <p>
18792     * Verifies that directories exist and that ownership and labeling is
18793     * correct for all installed apps. If there is an ownership mismatch, it
18794     * will try recovering system apps by wiping data; third-party app data is
18795     * left intact.
18796     * <p>
18797     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
18798     */
18799    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
18800        prepareAppDataAfterInstallInternal(pkg);
18801        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18802        for (int i = 0; i < childCount; i++) {
18803            PackageParser.Package childPackage = pkg.childPackages.get(i);
18804            prepareAppDataAfterInstallInternal(childPackage);
18805        }
18806    }
18807
18808    private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) {
18809        final PackageSetting ps;
18810        synchronized (mPackages) {
18811            ps = mSettings.mPackages.get(pkg.packageName);
18812            mSettings.writeKernelMappingLPr(ps);
18813        }
18814
18815        final UserManager um = mContext.getSystemService(UserManager.class);
18816        for (UserInfo user : um.getUsers()) {
18817            final int flags;
18818            if (um.isUserUnlocked(user.id)) {
18819                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18820            } else if (um.isUserRunning(user.id)) {
18821                flags = StorageManager.FLAG_STORAGE_DE;
18822            } else {
18823                continue;
18824            }
18825
18826            if (ps.getInstalled(user.id)) {
18827                // Whenever an app changes, force a restorecon of its data
18828                // TODO: when user data is locked, mark that we're still dirty
18829                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
18830            }
18831        }
18832    }
18833
18834    /**
18835     * Prepare app data for the given app.
18836     * <p>
18837     * Verifies that directories exist and that ownership and labeling is
18838     * correct for all installed apps. If there is an ownership mismatch, this
18839     * will try recovering system apps by wiping data; third-party app data is
18840     * left intact.
18841     */
18842    private void prepareAppData(String volumeUuid, int userId, int flags,
18843            PackageParser.Package pkg, boolean restoreconNeeded) {
18844        if (DEBUG_APP_DATA) {
18845            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
18846                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
18847        }
18848
18849        final String packageName = pkg.packageName;
18850        final ApplicationInfo app = pkg.applicationInfo;
18851        final int appId = UserHandle.getAppId(app.uid);
18852
18853        Preconditions.checkNotNull(app.seinfo);
18854
18855        synchronized (mInstallLock) {
18856            try {
18857                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18858                        appId, app.seinfo, app.targetSdkVersion);
18859            } catch (InstallerException e) {
18860                if (app.isSystemApp()) {
18861                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
18862                            + ", but trying to recover: " + e);
18863                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
18864                    try {
18865                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18866                                appId, app.seinfo, app.targetSdkVersion);
18867                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
18868                    } catch (InstallerException e2) {
18869                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
18870                    }
18871                } else {
18872                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
18873                }
18874            }
18875
18876            if (restoreconNeeded) {
18877                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
18878            }
18879
18880            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18881                // Create a native library symlink only if we have native libraries
18882                // and if the native libraries are 32 bit libraries. We do not provide
18883                // this symlink for 64 bit libraries.
18884                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
18885                    final String nativeLibPath = app.nativeLibraryDir;
18886                    try {
18887                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
18888                                nativeLibPath, userId);
18889                    } catch (InstallerException e) {
18890                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
18891                    }
18892                }
18893            }
18894        }
18895    }
18896
18897    /**
18898     * For system apps on non-FBE devices, this method migrates any existing
18899     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
18900     * requested by the app.
18901     */
18902    private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) {
18903        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
18904                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
18905            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
18906                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
18907            synchronized (mInstallLock) {
18908                try {
18909                    mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget);
18910                } catch (InstallerException e) {
18911                    logCriticalInfo(Log.WARN,
18912                            "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
18913                }
18914            }
18915            return true;
18916        } else {
18917            return false;
18918        }
18919    }
18920
18921    private void unfreezePackage(String packageName) {
18922        synchronized (mPackages) {
18923            final PackageSetting ps = mSettings.mPackages.get(packageName);
18924            if (ps != null) {
18925                ps.frozen = false;
18926            }
18927        }
18928    }
18929
18930    @Override
18931    public int movePackage(final String packageName, final String volumeUuid) {
18932        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18933
18934        final int moveId = mNextMoveId.getAndIncrement();
18935        mHandler.post(new Runnable() {
18936            @Override
18937            public void run() {
18938                try {
18939                    movePackageInternal(packageName, volumeUuid, moveId);
18940                } catch (PackageManagerException e) {
18941                    Slog.w(TAG, "Failed to move " + packageName, e);
18942                    mMoveCallbacks.notifyStatusChanged(moveId,
18943                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18944                }
18945            }
18946        });
18947        return moveId;
18948    }
18949
18950    private void movePackageInternal(final String packageName, final String volumeUuid,
18951            final int moveId) throws PackageManagerException {
18952        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
18953        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18954        final PackageManager pm = mContext.getPackageManager();
18955
18956        final boolean currentAsec;
18957        final String currentVolumeUuid;
18958        final File codeFile;
18959        final String installerPackageName;
18960        final String packageAbiOverride;
18961        final int appId;
18962        final String seinfo;
18963        final String label;
18964        final int targetSdkVersion;
18965
18966        // reader
18967        synchronized (mPackages) {
18968            final PackageParser.Package pkg = mPackages.get(packageName);
18969            final PackageSetting ps = mSettings.mPackages.get(packageName);
18970            if (pkg == null || ps == null) {
18971                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
18972            }
18973
18974            if (pkg.applicationInfo.isSystemApp()) {
18975                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
18976                        "Cannot move system application");
18977            }
18978
18979            if (pkg.applicationInfo.isExternalAsec()) {
18980                currentAsec = true;
18981                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
18982            } else if (pkg.applicationInfo.isForwardLocked()) {
18983                currentAsec = true;
18984                currentVolumeUuid = "forward_locked";
18985            } else {
18986                currentAsec = false;
18987                currentVolumeUuid = ps.volumeUuid;
18988
18989                final File probe = new File(pkg.codePath);
18990                final File probeOat = new File(probe, "oat");
18991                if (!probe.isDirectory() || !probeOat.isDirectory()) {
18992                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18993                            "Move only supported for modern cluster style installs");
18994                }
18995            }
18996
18997            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
18998                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18999                        "Package already moved to " + volumeUuid);
19000            }
19001            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
19002                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
19003                        "Device admin cannot be moved");
19004            }
19005
19006            if (ps.frozen) {
19007                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
19008                        "Failed to move already frozen package");
19009            }
19010            ps.frozen = true;
19011
19012            codeFile = new File(pkg.codePath);
19013            installerPackageName = ps.installerPackageName;
19014            packageAbiOverride = ps.cpuAbiOverrideString;
19015            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19016            seinfo = pkg.applicationInfo.seinfo;
19017            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
19018            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
19019        }
19020
19021        // Now that we're guarded by frozen state, kill app during move
19022        final long token = Binder.clearCallingIdentity();
19023        try {
19024            killApplication(packageName, appId, "move pkg");
19025        } finally {
19026            Binder.restoreCallingIdentity(token);
19027        }
19028
19029        final Bundle extras = new Bundle();
19030        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
19031        extras.putString(Intent.EXTRA_TITLE, label);
19032        mMoveCallbacks.notifyCreated(moveId, extras);
19033
19034        int installFlags;
19035        final boolean moveCompleteApp;
19036        final File measurePath;
19037
19038        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
19039            installFlags = INSTALL_INTERNAL;
19040            moveCompleteApp = !currentAsec;
19041            measurePath = Environment.getDataAppDirectory(volumeUuid);
19042        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
19043            installFlags = INSTALL_EXTERNAL;
19044            moveCompleteApp = false;
19045            measurePath = storage.getPrimaryPhysicalVolume().getPath();
19046        } else {
19047            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
19048            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
19049                    || !volume.isMountedWritable()) {
19050                unfreezePackage(packageName);
19051                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19052                        "Move location not mounted private volume");
19053            }
19054
19055            Preconditions.checkState(!currentAsec);
19056
19057            installFlags = INSTALL_INTERNAL;
19058            moveCompleteApp = true;
19059            measurePath = Environment.getDataAppDirectory(volumeUuid);
19060        }
19061
19062        final PackageStats stats = new PackageStats(null, -1);
19063        synchronized (mInstaller) {
19064            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
19065                unfreezePackage(packageName);
19066                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19067                        "Failed to measure package size");
19068            }
19069        }
19070
19071        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
19072                + stats.dataSize);
19073
19074        final long startFreeBytes = measurePath.getFreeSpace();
19075        final long sizeBytes;
19076        if (moveCompleteApp) {
19077            sizeBytes = stats.codeSize + stats.dataSize;
19078        } else {
19079            sizeBytes = stats.codeSize;
19080        }
19081
19082        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
19083            unfreezePackage(packageName);
19084            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19085                    "Not enough free space to move");
19086        }
19087
19088        mMoveCallbacks.notifyStatusChanged(moveId, 10);
19089
19090        final CountDownLatch installedLatch = new CountDownLatch(1);
19091        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
19092            @Override
19093            public void onUserActionRequired(Intent intent) throws RemoteException {
19094                throw new IllegalStateException();
19095            }
19096
19097            @Override
19098            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
19099                    Bundle extras) throws RemoteException {
19100                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
19101                        + PackageManager.installStatusToString(returnCode, msg));
19102
19103                installedLatch.countDown();
19104
19105                // Regardless of success or failure of the move operation,
19106                // always unfreeze the package
19107                unfreezePackage(packageName);
19108
19109                final int status = PackageManager.installStatusToPublicStatus(returnCode);
19110                switch (status) {
19111                    case PackageInstaller.STATUS_SUCCESS:
19112                        mMoveCallbacks.notifyStatusChanged(moveId,
19113                                PackageManager.MOVE_SUCCEEDED);
19114                        break;
19115                    case PackageInstaller.STATUS_FAILURE_STORAGE:
19116                        mMoveCallbacks.notifyStatusChanged(moveId,
19117                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
19118                        break;
19119                    default:
19120                        mMoveCallbacks.notifyStatusChanged(moveId,
19121                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19122                        break;
19123                }
19124            }
19125        };
19126
19127        final MoveInfo move;
19128        if (moveCompleteApp) {
19129            // Kick off a thread to report progress estimates
19130            new Thread() {
19131                @Override
19132                public void run() {
19133                    while (true) {
19134                        try {
19135                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
19136                                break;
19137                            }
19138                        } catch (InterruptedException ignored) {
19139                        }
19140
19141                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
19142                        final int progress = 10 + (int) MathUtils.constrain(
19143                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
19144                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
19145                    }
19146                }
19147            }.start();
19148
19149            final String dataAppName = codeFile.getName();
19150            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
19151                    dataAppName, appId, seinfo, targetSdkVersion);
19152        } else {
19153            move = null;
19154        }
19155
19156        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
19157
19158        final Message msg = mHandler.obtainMessage(INIT_COPY);
19159        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
19160        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
19161                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
19162                packageAbiOverride, null);
19163        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
19164        msg.obj = params;
19165
19166        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
19167                System.identityHashCode(msg.obj));
19168        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
19169                System.identityHashCode(msg.obj));
19170
19171        mHandler.sendMessage(msg);
19172    }
19173
19174    @Override
19175    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
19176        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19177
19178        final int realMoveId = mNextMoveId.getAndIncrement();
19179        final Bundle extras = new Bundle();
19180        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
19181        mMoveCallbacks.notifyCreated(realMoveId, extras);
19182
19183        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
19184            @Override
19185            public void onCreated(int moveId, Bundle extras) {
19186                // Ignored
19187            }
19188
19189            @Override
19190            public void onStatusChanged(int moveId, int status, long estMillis) {
19191                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
19192            }
19193        };
19194
19195        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19196        storage.setPrimaryStorageUuid(volumeUuid, callback);
19197        return realMoveId;
19198    }
19199
19200    @Override
19201    public int getMoveStatus(int moveId) {
19202        mContext.enforceCallingOrSelfPermission(
19203                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19204        return mMoveCallbacks.mLastStatus.get(moveId);
19205    }
19206
19207    @Override
19208    public void registerMoveCallback(IPackageMoveObserver callback) {
19209        mContext.enforceCallingOrSelfPermission(
19210                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19211        mMoveCallbacks.register(callback);
19212    }
19213
19214    @Override
19215    public void unregisterMoveCallback(IPackageMoveObserver callback) {
19216        mContext.enforceCallingOrSelfPermission(
19217                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19218        mMoveCallbacks.unregister(callback);
19219    }
19220
19221    @Override
19222    public boolean setInstallLocation(int loc) {
19223        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
19224                null);
19225        if (getInstallLocation() == loc) {
19226            return true;
19227        }
19228        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
19229                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
19230            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
19231                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
19232            return true;
19233        }
19234        return false;
19235   }
19236
19237    @Override
19238    public int getInstallLocation() {
19239        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
19240                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
19241                PackageHelper.APP_INSTALL_AUTO);
19242    }
19243
19244    /** Called by UserManagerService */
19245    void cleanUpUser(UserManagerService userManager, int userHandle) {
19246        synchronized (mPackages) {
19247            mDirtyUsers.remove(userHandle);
19248            mUserNeedsBadging.delete(userHandle);
19249            mSettings.removeUserLPw(userHandle);
19250            mPendingBroadcasts.remove(userHandle);
19251            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
19252        }
19253        synchronized (mInstallLock) {
19254            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19255            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19256                final String volumeUuid = vol.getFsUuid();
19257                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
19258                try {
19259                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
19260                } catch (InstallerException e) {
19261                    Slog.w(TAG, "Failed to remove user data", e);
19262                }
19263            }
19264            synchronized (mPackages) {
19265                removeUnusedPackagesLILPw(userManager, userHandle);
19266            }
19267        }
19268    }
19269
19270    /**
19271     * We're removing userHandle and would like to remove any downloaded packages
19272     * that are no longer in use by any other user.
19273     * @param userHandle the user being removed
19274     */
19275    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
19276        final boolean DEBUG_CLEAN_APKS = false;
19277        int [] users = userManager.getUserIds();
19278        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
19279        while (psit.hasNext()) {
19280            PackageSetting ps = psit.next();
19281            if (ps.pkg == null) {
19282                continue;
19283            }
19284            final String packageName = ps.pkg.packageName;
19285            // Skip over if system app
19286            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
19287                continue;
19288            }
19289            if (DEBUG_CLEAN_APKS) {
19290                Slog.i(TAG, "Checking package " + packageName);
19291            }
19292            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
19293            if (keep) {
19294                if (DEBUG_CLEAN_APKS) {
19295                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
19296                }
19297            } else {
19298                for (int i = 0; i < users.length; i++) {
19299                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
19300                        keep = true;
19301                        if (DEBUG_CLEAN_APKS) {
19302                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
19303                                    + users[i]);
19304                        }
19305                        break;
19306                    }
19307                }
19308            }
19309            if (!keep) {
19310                if (DEBUG_CLEAN_APKS) {
19311                    Slog.i(TAG, "  Removing package " + packageName);
19312                }
19313                mHandler.post(new Runnable() {
19314                    public void run() {
19315                        deletePackageX(packageName, userHandle, 0);
19316                    } //end run
19317                });
19318            }
19319        }
19320    }
19321
19322    /** Called by UserManagerService */
19323    void createNewUser(int userHandle) {
19324        synchronized (mInstallLock) {
19325            try {
19326                mInstaller.createUserConfig(userHandle);
19327            } catch (InstallerException e) {
19328                Slog.w(TAG, "Failed to create user config", e);
19329            }
19330            mSettings.createNewUserLI(this, mInstaller, userHandle);
19331        }
19332        synchronized (mPackages) {
19333            applyFactoryDefaultBrowserLPw(userHandle);
19334            primeDomainVerificationsLPw(userHandle);
19335        }
19336    }
19337
19338    void newUserCreated(final int userHandle) {
19339        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
19340        // If permission review for legacy apps is required, we represent
19341        // dagerous permissions for such apps as always granted runtime
19342        // permissions to keep per user flag state whether review is needed.
19343        // Hence, if a new user is added we have to propagate dangerous
19344        // permission grants for these legacy apps.
19345        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
19346            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
19347                    | UPDATE_PERMISSIONS_REPLACE_ALL);
19348        }
19349    }
19350
19351    @Override
19352    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
19353        mContext.enforceCallingOrSelfPermission(
19354                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
19355                "Only package verification agents can read the verifier device identity");
19356
19357        synchronized (mPackages) {
19358            return mSettings.getVerifierDeviceIdentityLPw();
19359        }
19360    }
19361
19362    @Override
19363    public void setPermissionEnforced(String permission, boolean enforced) {
19364        // TODO: Now that we no longer change GID for storage, this should to away.
19365        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
19366                "setPermissionEnforced");
19367        if (READ_EXTERNAL_STORAGE.equals(permission)) {
19368            synchronized (mPackages) {
19369                if (mSettings.mReadExternalStorageEnforced == null
19370                        || mSettings.mReadExternalStorageEnforced != enforced) {
19371                    mSettings.mReadExternalStorageEnforced = enforced;
19372                    mSettings.writeLPr();
19373                }
19374            }
19375            // kill any non-foreground processes so we restart them and
19376            // grant/revoke the GID.
19377            final IActivityManager am = ActivityManagerNative.getDefault();
19378            if (am != null) {
19379                final long token = Binder.clearCallingIdentity();
19380                try {
19381                    am.killProcessesBelowForeground("setPermissionEnforcement");
19382                } catch (RemoteException e) {
19383                } finally {
19384                    Binder.restoreCallingIdentity(token);
19385                }
19386            }
19387        } else {
19388            throw new IllegalArgumentException("No selective enforcement for " + permission);
19389        }
19390    }
19391
19392    @Override
19393    @Deprecated
19394    public boolean isPermissionEnforced(String permission) {
19395        return true;
19396    }
19397
19398    @Override
19399    public boolean isStorageLow() {
19400        final long token = Binder.clearCallingIdentity();
19401        try {
19402            final DeviceStorageMonitorInternal
19403                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
19404            if (dsm != null) {
19405                return dsm.isMemoryLow();
19406            } else {
19407                return false;
19408            }
19409        } finally {
19410            Binder.restoreCallingIdentity(token);
19411        }
19412    }
19413
19414    @Override
19415    public IPackageInstaller getPackageInstaller() {
19416        return mInstallerService;
19417    }
19418
19419    private boolean userNeedsBadging(int userId) {
19420        int index = mUserNeedsBadging.indexOfKey(userId);
19421        if (index < 0) {
19422            final UserInfo userInfo;
19423            final long token = Binder.clearCallingIdentity();
19424            try {
19425                userInfo = sUserManager.getUserInfo(userId);
19426            } finally {
19427                Binder.restoreCallingIdentity(token);
19428            }
19429            final boolean b;
19430            if (userInfo != null && userInfo.isManagedProfile()) {
19431                b = true;
19432            } else {
19433                b = false;
19434            }
19435            mUserNeedsBadging.put(userId, b);
19436            return b;
19437        }
19438        return mUserNeedsBadging.valueAt(index);
19439    }
19440
19441    @Override
19442    public KeySet getKeySetByAlias(String packageName, String alias) {
19443        if (packageName == null || alias == null) {
19444            return null;
19445        }
19446        synchronized(mPackages) {
19447            final PackageParser.Package pkg = mPackages.get(packageName);
19448            if (pkg == null) {
19449                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19450                throw new IllegalArgumentException("Unknown package: " + packageName);
19451            }
19452            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19453            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
19454        }
19455    }
19456
19457    @Override
19458    public KeySet getSigningKeySet(String packageName) {
19459        if (packageName == null) {
19460            return null;
19461        }
19462        synchronized(mPackages) {
19463            final PackageParser.Package pkg = mPackages.get(packageName);
19464            if (pkg == null) {
19465                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19466                throw new IllegalArgumentException("Unknown package: " + packageName);
19467            }
19468            if (pkg.applicationInfo.uid != Binder.getCallingUid()
19469                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
19470                throw new SecurityException("May not access signing KeySet of other apps.");
19471            }
19472            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19473            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
19474        }
19475    }
19476
19477    @Override
19478    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
19479        if (packageName == null || ks == null) {
19480            return false;
19481        }
19482        synchronized(mPackages) {
19483            final PackageParser.Package pkg = mPackages.get(packageName);
19484            if (pkg == null) {
19485                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19486                throw new IllegalArgumentException("Unknown package: " + packageName);
19487            }
19488            IBinder ksh = ks.getToken();
19489            if (ksh instanceof KeySetHandle) {
19490                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19491                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
19492            }
19493            return false;
19494        }
19495    }
19496
19497    @Override
19498    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
19499        if (packageName == null || ks == null) {
19500            return false;
19501        }
19502        synchronized(mPackages) {
19503            final PackageParser.Package pkg = mPackages.get(packageName);
19504            if (pkg == null) {
19505                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19506                throw new IllegalArgumentException("Unknown package: " + packageName);
19507            }
19508            IBinder ksh = ks.getToken();
19509            if (ksh instanceof KeySetHandle) {
19510                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19511                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
19512            }
19513            return false;
19514        }
19515    }
19516
19517    private void deletePackageIfUnusedLPr(final String packageName) {
19518        PackageSetting ps = mSettings.mPackages.get(packageName);
19519        if (ps == null) {
19520            return;
19521        }
19522        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
19523            // TODO Implement atomic delete if package is unused
19524            // It is currently possible that the package will be deleted even if it is installed
19525            // after this method returns.
19526            mHandler.post(new Runnable() {
19527                public void run() {
19528                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
19529                }
19530            });
19531        }
19532    }
19533
19534    /**
19535     * Check and throw if the given before/after packages would be considered a
19536     * downgrade.
19537     */
19538    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
19539            throws PackageManagerException {
19540        if (after.versionCode < before.mVersionCode) {
19541            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19542                    "Update version code " + after.versionCode + " is older than current "
19543                    + before.mVersionCode);
19544        } else if (after.versionCode == before.mVersionCode) {
19545            if (after.baseRevisionCode < before.baseRevisionCode) {
19546                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19547                        "Update base revision code " + after.baseRevisionCode
19548                        + " is older than current " + before.baseRevisionCode);
19549            }
19550
19551            if (!ArrayUtils.isEmpty(after.splitNames)) {
19552                for (int i = 0; i < after.splitNames.length; i++) {
19553                    final String splitName = after.splitNames[i];
19554                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
19555                    if (j != -1) {
19556                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
19557                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19558                                    "Update split " + splitName + " revision code "
19559                                    + after.splitRevisionCodes[i] + " is older than current "
19560                                    + before.splitRevisionCodes[j]);
19561                        }
19562                    }
19563                }
19564            }
19565        }
19566    }
19567
19568    private static class MoveCallbacks extends Handler {
19569        private static final int MSG_CREATED = 1;
19570        private static final int MSG_STATUS_CHANGED = 2;
19571
19572        private final RemoteCallbackList<IPackageMoveObserver>
19573                mCallbacks = new RemoteCallbackList<>();
19574
19575        private final SparseIntArray mLastStatus = new SparseIntArray();
19576
19577        public MoveCallbacks(Looper looper) {
19578            super(looper);
19579        }
19580
19581        public void register(IPackageMoveObserver callback) {
19582            mCallbacks.register(callback);
19583        }
19584
19585        public void unregister(IPackageMoveObserver callback) {
19586            mCallbacks.unregister(callback);
19587        }
19588
19589        @Override
19590        public void handleMessage(Message msg) {
19591            final SomeArgs args = (SomeArgs) msg.obj;
19592            final int n = mCallbacks.beginBroadcast();
19593            for (int i = 0; i < n; i++) {
19594                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
19595                try {
19596                    invokeCallback(callback, msg.what, args);
19597                } catch (RemoteException ignored) {
19598                }
19599            }
19600            mCallbacks.finishBroadcast();
19601            args.recycle();
19602        }
19603
19604        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
19605                throws RemoteException {
19606            switch (what) {
19607                case MSG_CREATED: {
19608                    callback.onCreated(args.argi1, (Bundle) args.arg2);
19609                    break;
19610                }
19611                case MSG_STATUS_CHANGED: {
19612                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
19613                    break;
19614                }
19615            }
19616        }
19617
19618        private void notifyCreated(int moveId, Bundle extras) {
19619            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
19620
19621            final SomeArgs args = SomeArgs.obtain();
19622            args.argi1 = moveId;
19623            args.arg2 = extras;
19624            obtainMessage(MSG_CREATED, args).sendToTarget();
19625        }
19626
19627        private void notifyStatusChanged(int moveId, int status) {
19628            notifyStatusChanged(moveId, status, -1);
19629        }
19630
19631        private void notifyStatusChanged(int moveId, int status, long estMillis) {
19632            Slog.v(TAG, "Move " + moveId + " status " + status);
19633
19634            final SomeArgs args = SomeArgs.obtain();
19635            args.argi1 = moveId;
19636            args.argi2 = status;
19637            args.arg3 = estMillis;
19638            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
19639
19640            synchronized (mLastStatus) {
19641                mLastStatus.put(moveId, status);
19642            }
19643        }
19644    }
19645
19646    private final static class OnPermissionChangeListeners extends Handler {
19647        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
19648
19649        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
19650                new RemoteCallbackList<>();
19651
19652        public OnPermissionChangeListeners(Looper looper) {
19653            super(looper);
19654        }
19655
19656        @Override
19657        public void handleMessage(Message msg) {
19658            switch (msg.what) {
19659                case MSG_ON_PERMISSIONS_CHANGED: {
19660                    final int uid = msg.arg1;
19661                    handleOnPermissionsChanged(uid);
19662                } break;
19663            }
19664        }
19665
19666        public void addListenerLocked(IOnPermissionsChangeListener listener) {
19667            mPermissionListeners.register(listener);
19668
19669        }
19670
19671        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
19672            mPermissionListeners.unregister(listener);
19673        }
19674
19675        public void onPermissionsChanged(int uid) {
19676            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
19677                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
19678            }
19679        }
19680
19681        private void handleOnPermissionsChanged(int uid) {
19682            final int count = mPermissionListeners.beginBroadcast();
19683            try {
19684                for (int i = 0; i < count; i++) {
19685                    IOnPermissionsChangeListener callback = mPermissionListeners
19686                            .getBroadcastItem(i);
19687                    try {
19688                        callback.onPermissionsChanged(uid);
19689                    } catch (RemoteException e) {
19690                        Log.e(TAG, "Permission listener is dead", e);
19691                    }
19692                }
19693            } finally {
19694                mPermissionListeners.finishBroadcast();
19695            }
19696        }
19697    }
19698
19699    private class PackageManagerInternalImpl extends PackageManagerInternal {
19700        @Override
19701        public void setLocationPackagesProvider(PackagesProvider provider) {
19702            synchronized (mPackages) {
19703                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
19704            }
19705        }
19706
19707        @Override
19708        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
19709            synchronized (mPackages) {
19710                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
19711            }
19712        }
19713
19714        @Override
19715        public void setSmsAppPackagesProvider(PackagesProvider provider) {
19716            synchronized (mPackages) {
19717                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
19718            }
19719        }
19720
19721        @Override
19722        public void setDialerAppPackagesProvider(PackagesProvider provider) {
19723            synchronized (mPackages) {
19724                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
19725            }
19726        }
19727
19728        @Override
19729        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
19730            synchronized (mPackages) {
19731                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
19732            }
19733        }
19734
19735        @Override
19736        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
19737            synchronized (mPackages) {
19738                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
19739            }
19740        }
19741
19742        @Override
19743        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
19744            synchronized (mPackages) {
19745                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
19746                        packageName, userId);
19747            }
19748        }
19749
19750        @Override
19751        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
19752            synchronized (mPackages) {
19753                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
19754                        packageName, userId);
19755            }
19756        }
19757
19758        @Override
19759        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
19760            synchronized (mPackages) {
19761                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
19762                        packageName, userId);
19763            }
19764        }
19765
19766        @Override
19767        public void setKeepUninstalledPackages(final List<String> packageList) {
19768            Preconditions.checkNotNull(packageList);
19769            List<String> removedFromList = null;
19770            synchronized (mPackages) {
19771                if (mKeepUninstalledPackages != null) {
19772                    final int packagesCount = mKeepUninstalledPackages.size();
19773                    for (int i = 0; i < packagesCount; i++) {
19774                        String oldPackage = mKeepUninstalledPackages.get(i);
19775                        if (packageList != null && packageList.contains(oldPackage)) {
19776                            continue;
19777                        }
19778                        if (removedFromList == null) {
19779                            removedFromList = new ArrayList<>();
19780                        }
19781                        removedFromList.add(oldPackage);
19782                    }
19783                }
19784                mKeepUninstalledPackages = new ArrayList<>(packageList);
19785                if (removedFromList != null) {
19786                    final int removedCount = removedFromList.size();
19787                    for (int i = 0; i < removedCount; i++) {
19788                        deletePackageIfUnusedLPr(removedFromList.get(i));
19789                    }
19790                }
19791            }
19792        }
19793
19794        @Override
19795        public boolean isPermissionsReviewRequired(String packageName, int userId) {
19796            synchronized (mPackages) {
19797                // If we do not support permission review, done.
19798                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
19799                    return false;
19800                }
19801
19802                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
19803                if (packageSetting == null) {
19804                    return false;
19805                }
19806
19807                // Permission review applies only to apps not supporting the new permission model.
19808                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
19809                    return false;
19810                }
19811
19812                // Legacy apps have the permission and get user consent on launch.
19813                PermissionsState permissionsState = packageSetting.getPermissionsState();
19814                return permissionsState.isPermissionReviewRequired(userId);
19815            }
19816        }
19817
19818        @Override
19819        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
19820            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
19821        }
19822
19823        @Override
19824        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19825                int userId) {
19826            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
19827        }
19828    }
19829
19830    @Override
19831    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
19832        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
19833        synchronized (mPackages) {
19834            final long identity = Binder.clearCallingIdentity();
19835            try {
19836                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
19837                        packageNames, userId);
19838            } finally {
19839                Binder.restoreCallingIdentity(identity);
19840            }
19841        }
19842    }
19843
19844    private static void enforceSystemOrPhoneCaller(String tag) {
19845        int callingUid = Binder.getCallingUid();
19846        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
19847            throw new SecurityException(
19848                    "Cannot call " + tag + " from UID " + callingUid);
19849        }
19850    }
19851
19852    boolean isHistoricalPackageUsageAvailable() {
19853        return mPackageUsage.isHistoricalPackageUsageAvailable();
19854    }
19855
19856    /**
19857     * Return a <b>copy</b> of the collection of packages known to the package manager.
19858     * @return A copy of the values of mPackages.
19859     */
19860    Collection<PackageParser.Package> getPackages() {
19861        synchronized (mPackages) {
19862            return new ArrayList<>(mPackages.values());
19863        }
19864    }
19865
19866    /**
19867     * Logs process start information (including base APK hash) to the security log.
19868     * @hide
19869     */
19870    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
19871            String apkFile, int pid) {
19872        if (!SecurityLog.isLoggingEnabled()) {
19873            return;
19874        }
19875        Bundle data = new Bundle();
19876        data.putLong("startTimestamp", System.currentTimeMillis());
19877        data.putString("processName", processName);
19878        data.putInt("uid", uid);
19879        data.putString("seinfo", seinfo);
19880        data.putString("apkFile", apkFile);
19881        data.putInt("pid", pid);
19882        Message msg = mProcessLoggingHandler.obtainMessage(
19883                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
19884        msg.setData(data);
19885        mProcessLoggingHandler.sendMessage(msg);
19886    }
19887}
19888