PackageManagerService.java revision 3cd658e1a598e59738bc129c35eecf4cd0f20680
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_DUPLICATE_PACKAGE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
61import static android.content.pm.PackageManager.MATCH_ALL;
62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
63import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
65import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
66import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
67import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
68import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
69import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
70import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
71import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
72import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
73import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
74import static android.content.pm.PackageManager.PERMISSION_DENIED;
75import static android.content.pm.PackageManager.PERMISSION_GRANTED;
76import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
77import static android.content.pm.PackageParser.isApkFile;
78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
79import static android.system.OsConstants.O_CREAT;
80import static android.system.OsConstants.O_RDWR;
81
82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
86import static com.android.internal.util.ArrayUtils.appendInt;
87import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
93import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
99
100import android.Manifest;
101import android.annotation.NonNull;
102import android.annotation.Nullable;
103import android.app.ActivityManager;
104import android.app.ActivityManagerNative;
105import android.app.IActivityManager;
106import android.app.ResourcesManager;
107import android.app.admin.IDevicePolicyManager;
108import android.app.admin.SecurityLog;
109import android.app.backup.IBackupManager;
110import android.content.BroadcastReceiver;
111import android.content.ComponentName;
112import android.content.Context;
113import android.content.IIntentReceiver;
114import android.content.Intent;
115import android.content.IntentFilter;
116import android.content.IntentSender;
117import android.content.IntentSender.SendIntentException;
118import android.content.ServiceConnection;
119import android.content.pm.ActivityInfo;
120import android.content.pm.ApplicationInfo;
121import android.content.pm.AppsQueryHelper;
122import android.content.pm.ComponentInfo;
123import android.content.pm.EphemeralApplicationInfo;
124import android.content.pm.EphemeralResolveInfo;
125import android.content.pm.EphemeralResolveInfo.EphemeralDigest;
126import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
127import android.content.pm.FeatureInfo;
128import android.content.pm.IOnPermissionsChangeListener;
129import android.content.pm.IPackageDataObserver;
130import android.content.pm.IPackageDeleteObserver;
131import android.content.pm.IPackageDeleteObserver2;
132import android.content.pm.IPackageInstallObserver2;
133import android.content.pm.IPackageInstaller;
134import android.content.pm.IPackageManager;
135import android.content.pm.IPackageMoveObserver;
136import android.content.pm.IPackageStatsObserver;
137import android.content.pm.InstrumentationInfo;
138import android.content.pm.IntentFilterVerificationInfo;
139import android.content.pm.KeySet;
140import android.content.pm.PackageCleanItem;
141import android.content.pm.PackageInfo;
142import android.content.pm.PackageInfoLite;
143import android.content.pm.PackageInstaller;
144import android.content.pm.PackageManager;
145import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
146import android.content.pm.PackageManagerInternal;
147import android.content.pm.PackageParser;
148import android.content.pm.PackageParser.ActivityIntentInfo;
149import android.content.pm.PackageParser.PackageLite;
150import android.content.pm.PackageParser.PackageParserException;
151import android.content.pm.PackageStats;
152import android.content.pm.PackageUserState;
153import android.content.pm.ParceledListSlice;
154import android.content.pm.PermissionGroupInfo;
155import android.content.pm.PermissionInfo;
156import android.content.pm.ProviderInfo;
157import android.content.pm.ResolveInfo;
158import android.content.pm.ServiceInfo;
159import android.content.pm.Signature;
160import android.content.pm.UserInfo;
161import android.content.pm.VerifierDeviceIdentity;
162import android.content.pm.VerifierInfo;
163import android.content.res.Resources;
164import android.graphics.Bitmap;
165import android.hardware.display.DisplayManager;
166import android.net.Uri;
167import android.os.Binder;
168import android.os.Build;
169import android.os.Bundle;
170import android.os.Debug;
171import android.os.Environment;
172import android.os.Environment.UserEnvironment;
173import android.os.FileUtils;
174import android.os.Handler;
175import android.os.IBinder;
176import android.os.Looper;
177import android.os.Message;
178import android.os.Parcel;
179import android.os.ParcelFileDescriptor;
180import android.os.PatternMatcher;
181import android.os.Process;
182import android.os.RemoteCallbackList;
183import android.os.RemoteException;
184import android.os.ResultReceiver;
185import android.os.SELinux;
186import android.os.ServiceManager;
187import android.os.SystemClock;
188import android.os.SystemProperties;
189import android.os.Trace;
190import android.os.UserHandle;
191import android.os.UserManager;
192import android.os.UserManagerInternal;
193import android.os.storage.IMountService;
194import android.os.storage.MountServiceInternal;
195import android.os.storage.StorageEventListener;
196import android.os.storage.StorageManager;
197import android.os.storage.VolumeInfo;
198import android.os.storage.VolumeRecord;
199import android.provider.Settings.Global;
200import android.provider.Settings.Secure;
201import android.security.KeyStore;
202import android.security.SystemKeyStore;
203import android.system.ErrnoException;
204import android.system.Os;
205import android.text.TextUtils;
206import android.text.format.DateUtils;
207import android.util.ArrayMap;
208import android.util.ArraySet;
209import android.util.DisplayMetrics;
210import android.util.EventLog;
211import android.util.ExceptionUtils;
212import android.util.Log;
213import android.util.LogPrinter;
214import android.util.MathUtils;
215import android.util.PrintStreamPrinter;
216import android.util.Slog;
217import android.util.SparseArray;
218import android.util.SparseBooleanArray;
219import android.util.SparseIntArray;
220import android.util.Xml;
221import android.util.jar.StrictJarFile;
222import android.view.Display;
223
224import com.android.internal.R;
225import com.android.internal.annotations.GuardedBy;
226import com.android.internal.app.IMediaContainerService;
227import com.android.internal.app.ResolverActivity;
228import com.android.internal.content.NativeLibraryHelper;
229import com.android.internal.content.PackageHelper;
230import com.android.internal.logging.MetricsLogger;
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.telephony.CarrierAppUtils;
236import com.android.internal.util.ArrayUtils;
237import com.android.internal.util.FastPrintWriter;
238import com.android.internal.util.FastXmlSerializer;
239import com.android.internal.util.IndentingPrintWriter;
240import com.android.internal.util.Preconditions;
241import com.android.internal.util.XmlUtils;
242import com.android.server.AttributeCache;
243import com.android.server.EventLogTags;
244import com.android.server.FgThread;
245import com.android.server.IntentResolver;
246import com.android.server.LocalServices;
247import com.android.server.ServiceThread;
248import com.android.server.SystemConfig;
249import com.android.server.Watchdog;
250import com.android.server.net.NetworkPolicyManagerInternal;
251import com.android.server.pm.PermissionsState.PermissionState;
252import com.android.server.pm.Settings.DatabaseVersion;
253import com.android.server.pm.Settings.VersionInfo;
254import com.android.server.storage.DeviceStorageMonitorInternal;
255
256import dalvik.system.CloseGuard;
257import dalvik.system.DexFile;
258import dalvik.system.VMRuntime;
259
260import libcore.io.IoUtils;
261import libcore.util.EmptyArray;
262
263import org.xmlpull.v1.XmlPullParser;
264import org.xmlpull.v1.XmlPullParserException;
265import org.xmlpull.v1.XmlSerializer;
266
267import java.io.BufferedOutputStream;
268import java.io.BufferedReader;
269import java.io.ByteArrayInputStream;
270import java.io.ByteArrayOutputStream;
271import java.io.File;
272import java.io.FileDescriptor;
273import java.io.FileInputStream;
274import java.io.FileNotFoundException;
275import java.io.FileOutputStream;
276import java.io.FileReader;
277import java.io.FilenameFilter;
278import java.io.IOException;
279import java.io.PrintWriter;
280import java.nio.charset.StandardCharsets;
281import java.security.DigestInputStream;
282import java.security.MessageDigest;
283import java.security.NoSuchAlgorithmException;
284import java.security.PublicKey;
285import java.security.cert.Certificate;
286import java.security.cert.CertificateEncodingException;
287import java.security.cert.CertificateException;
288import java.text.SimpleDateFormat;
289import java.util.ArrayList;
290import java.util.Arrays;
291import java.util.Collection;
292import java.util.Collections;
293import java.util.Comparator;
294import java.util.Date;
295import java.util.HashSet;
296import java.util.Iterator;
297import java.util.List;
298import java.util.Map;
299import java.util.Objects;
300import java.util.Set;
301import java.util.concurrent.CountDownLatch;
302import java.util.concurrent.TimeUnit;
303import java.util.concurrent.atomic.AtomicBoolean;
304import java.util.concurrent.atomic.AtomicInteger;
305
306/**
307 * Keep track of all those APKs everywhere.
308 * <p>
309 * Internally there are two important locks:
310 * <ul>
311 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
312 * and other related state. It is a fine-grained lock that should only be held
313 * momentarily, as it's one of the most contended locks in the system.
314 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
315 * operations typically involve heavy lifting of application data on disk. Since
316 * {@code installd} is single-threaded, and it's operations can often be slow,
317 * this lock should never be acquired while already holding {@link #mPackages}.
318 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
319 * holding {@link #mInstallLock}.
320 * </ul>
321 * Many internal methods rely on the caller to hold the appropriate locks, and
322 * this contract is expressed through method name suffixes:
323 * <ul>
324 * <li>fooLI(): the caller must hold {@link #mInstallLock}
325 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
326 * being modified must be frozen
327 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
328 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
329 * </ul>
330 * <p>
331 * Because this class is very central to the platform's security; please run all
332 * CTS and unit tests whenever making modifications:
333 *
334 * <pre>
335 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
336 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
337 * </pre>
338 */
339public class PackageManagerService extends IPackageManager.Stub {
340    static final String TAG = "PackageManager";
341    static final boolean DEBUG_SETTINGS = false;
342    static final boolean DEBUG_PREFERRED = false;
343    static final boolean DEBUG_UPGRADE = false;
344    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
345    private static final boolean DEBUG_BACKUP = false;
346    private static final boolean DEBUG_INSTALL = false;
347    private static final boolean DEBUG_REMOVE = false;
348    private static final boolean DEBUG_BROADCASTS = false;
349    private static final boolean DEBUG_SHOW_INFO = false;
350    private static final boolean DEBUG_PACKAGE_INFO = false;
351    private static final boolean DEBUG_INTENT_MATCHING = false;
352    private static final boolean DEBUG_PACKAGE_SCANNING = false;
353    private static final boolean DEBUG_VERIFY = false;
354    private static final boolean DEBUG_FILTERS = false;
355
356    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
357    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
358    // user, but by default initialize to this.
359    static final boolean DEBUG_DEXOPT = false;
360
361    private static final boolean DEBUG_ABI_SELECTION = false;
362    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
363    private static final boolean DEBUG_TRIAGED_MISSING = false;
364    private static final boolean DEBUG_APP_DATA = false;
365
366    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
367    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
368
369    // STOPSHIP; b/30256615
370    private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE;
371
372    private static final int RADIO_UID = Process.PHONE_UID;
373    private static final int LOG_UID = Process.LOG_UID;
374    private static final int NFC_UID = Process.NFC_UID;
375    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
376    private static final int SHELL_UID = Process.SHELL_UID;
377
378    // Cap the size of permission trees that 3rd party apps can define
379    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
380
381    // Suffix used during package installation when copying/moving
382    // package apks to install directory.
383    private static final String INSTALL_PACKAGE_SUFFIX = "-";
384
385    static final int SCAN_NO_DEX = 1<<1;
386    static final int SCAN_FORCE_DEX = 1<<2;
387    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
388    static final int SCAN_NEW_INSTALL = 1<<4;
389    static final int SCAN_NO_PATHS = 1<<5;
390    static final int SCAN_UPDATE_TIME = 1<<6;
391    static final int SCAN_DEFER_DEX = 1<<7;
392    static final int SCAN_BOOTING = 1<<8;
393    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
394    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
395    static final int SCAN_REPLACING = 1<<11;
396    static final int SCAN_REQUIRE_KNOWN = 1<<12;
397    static final int SCAN_MOVE = 1<<13;
398    static final int SCAN_INITIAL = 1<<14;
399    static final int SCAN_CHECK_ONLY = 1<<15;
400    static final int SCAN_DONT_KILL_APP = 1<<17;
401    static final int SCAN_IGNORE_FROZEN = 1<<18;
402
403    static final int REMOVE_CHATTY = 1<<16;
404
405    private static final int[] EMPTY_INT_ARRAY = new int[0];
406
407    /**
408     * Timeout (in milliseconds) after which the watchdog should declare that
409     * our handler thread is wedged.  The usual default for such things is one
410     * minute but we sometimes do very lengthy I/O operations on this thread,
411     * such as installing multi-gigabyte applications, so ours needs to be longer.
412     */
413    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
414
415    /**
416     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
417     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
418     * settings entry if available, otherwise we use the hardcoded default.  If it's been
419     * more than this long since the last fstrim, we force one during the boot sequence.
420     *
421     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
422     * one gets run at the next available charging+idle time.  This final mandatory
423     * no-fstrim check kicks in only of the other scheduling criteria is never met.
424     */
425    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
426
427    /**
428     * Whether verification is enabled by default.
429     */
430    private static final boolean DEFAULT_VERIFY_ENABLE = true;
431
432    /**
433     * The default maximum time to wait for the verification agent to return in
434     * milliseconds.
435     */
436    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
437
438    /**
439     * The default response for package verification timeout.
440     *
441     * This can be either PackageManager.VERIFICATION_ALLOW or
442     * PackageManager.VERIFICATION_REJECT.
443     */
444    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
445
446    static final String PLATFORM_PACKAGE_NAME = "android";
447
448    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
449
450    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
451            DEFAULT_CONTAINER_PACKAGE,
452            "com.android.defcontainer.DefaultContainerService");
453
454    private static final String KILL_APP_REASON_GIDS_CHANGED =
455            "permission grant or revoke changed gids";
456
457    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
458            "permissions revoked";
459
460    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
461
462    private static final String PACKAGE_SCHEME = "package";
463
464    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
465
466    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
467    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
468
469    /** Permission grant: not grant the permission. */
470    private static final int GRANT_DENIED = 1;
471
472    /** Permission grant: grant the permission as an install permission. */
473    private static final int GRANT_INSTALL = 2;
474
475    /** Permission grant: grant the permission as a runtime one. */
476    private static final int GRANT_RUNTIME = 3;
477
478    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
479    private static final int GRANT_UPGRADE = 4;
480
481    /** Canonical intent used to identify what counts as a "web browser" app */
482    private static final Intent sBrowserIntent;
483    static {
484        sBrowserIntent = new Intent();
485        sBrowserIntent.setAction(Intent.ACTION_VIEW);
486        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
487        sBrowserIntent.setData(Uri.parse("http:"));
488    }
489
490    /**
491     * The set of all protected actions [i.e. those actions for which a high priority
492     * intent filter is disallowed].
493     */
494    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
495    static {
496        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
497        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
498        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
499        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
500    }
501
502    // Compilation reasons.
503    public static final int REASON_FIRST_BOOT = 0;
504    public static final int REASON_BOOT = 1;
505    public static final int REASON_INSTALL = 2;
506    public static final int REASON_BACKGROUND_DEXOPT = 3;
507    public static final int REASON_AB_OTA = 4;
508    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
509    public static final int REASON_SHARED_APK = 6;
510    public static final int REASON_FORCED_DEXOPT = 7;
511    public static final int REASON_CORE_APP = 8;
512
513    public static final int REASON_LAST = REASON_CORE_APP;
514
515    /** Special library name that skips shared libraries check during compilation. */
516    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
517
518    final ServiceThread mHandlerThread;
519
520    final PackageHandler mHandler;
521
522    private final ProcessLoggingHandler mProcessLoggingHandler;
523
524    /**
525     * Messages for {@link #mHandler} that need to wait for system ready before
526     * being dispatched.
527     */
528    private ArrayList<Message> mPostSystemReadyMessages;
529
530    final int mSdkVersion = Build.VERSION.SDK_INT;
531
532    final Context mContext;
533    final boolean mFactoryTest;
534    final boolean mOnlyCore;
535    final DisplayMetrics mMetrics;
536    final int mDefParseFlags;
537    final String[] mSeparateProcesses;
538    final boolean mIsUpgrade;
539    final boolean mIsPreNUpgrade;
540    final boolean mIsPreNMR1Upgrade;
541
542    @GuardedBy("mPackages")
543    private boolean mDexOptDialogShown;
544
545    /** The location for ASEC container files on internal storage. */
546    final String mAsecInternalPath;
547
548    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
549    // LOCK HELD.  Can be called with mInstallLock held.
550    @GuardedBy("mInstallLock")
551    final Installer mInstaller;
552
553    /** Directory where installed third-party apps stored */
554    final File mAppInstallDir;
555    final File mEphemeralInstallDir;
556
557    /**
558     * Directory to which applications installed internally have their
559     * 32 bit native libraries copied.
560     */
561    private File mAppLib32InstallDir;
562
563    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
564    // apps.
565    final File mDrmAppPrivateInstallDir;
566
567    // ----------------------------------------------------------------
568
569    // Lock for state used when installing and doing other long running
570    // operations.  Methods that must be called with this lock held have
571    // the suffix "LI".
572    final Object mInstallLock = new Object();
573
574    // ----------------------------------------------------------------
575
576    // Keys are String (package name), values are Package.  This also serves
577    // as the lock for the global state.  Methods that must be called with
578    // this lock held have the prefix "LP".
579    @GuardedBy("mPackages")
580    final ArrayMap<String, PackageParser.Package> mPackages =
581            new ArrayMap<String, PackageParser.Package>();
582
583    final ArrayMap<String, Set<String>> mKnownCodebase =
584            new ArrayMap<String, Set<String>>();
585
586    // Tracks available target package names -> overlay package paths.
587    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
588        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
589
590    /**
591     * Tracks new system packages [received in an OTA] that we expect to
592     * find updated user-installed versions. Keys are package name, values
593     * are package location.
594     */
595    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
596    /**
597     * Tracks high priority intent filters for protected actions. During boot, certain
598     * filter actions are protected and should never be allowed to have a high priority
599     * intent filter for them. However, there is one, and only one exception -- the
600     * setup wizard. It must be able to define a high priority intent filter for these
601     * actions to ensure there are no escapes from the wizard. We need to delay processing
602     * of these during boot as we need to look at all of the system packages in order
603     * to know which component is the setup wizard.
604     */
605    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
606    /**
607     * Whether or not processing protected filters should be deferred.
608     */
609    private boolean mDeferProtectedFilters = true;
610
611    /**
612     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
613     */
614    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
615    /**
616     * Whether or not system app permissions should be promoted from install to runtime.
617     */
618    boolean mPromoteSystemApps;
619
620    @GuardedBy("mPackages")
621    final Settings mSettings;
622
623    /**
624     * Set of package names that are currently "frozen", which means active
625     * surgery is being done on the code/data for that package. The platform
626     * will refuse to launch frozen packages to avoid race conditions.
627     *
628     * @see PackageFreezer
629     */
630    @GuardedBy("mPackages")
631    final ArraySet<String> mFrozenPackages = new ArraySet<>();
632
633    final ProtectedPackages mProtectedPackages;
634
635    boolean mFirstBoot;
636
637    // System configuration read by SystemConfig.
638    final int[] mGlobalGids;
639    final SparseArray<ArraySet<String>> mSystemPermissions;
640    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
641
642    // If mac_permissions.xml was found for seinfo labeling.
643    boolean mFoundPolicyFile;
644
645    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
646
647    public static final class SharedLibraryEntry {
648        public final String path;
649        public final String apk;
650
651        SharedLibraryEntry(String _path, String _apk) {
652            path = _path;
653            apk = _apk;
654        }
655    }
656
657    // Currently known shared libraries.
658    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
659            new ArrayMap<String, SharedLibraryEntry>();
660
661    // All available activities, for your resolving pleasure.
662    final ActivityIntentResolver mActivities =
663            new ActivityIntentResolver();
664
665    // All available receivers, for your resolving pleasure.
666    final ActivityIntentResolver mReceivers =
667            new ActivityIntentResolver();
668
669    // All available services, for your resolving pleasure.
670    final ServiceIntentResolver mServices = new ServiceIntentResolver();
671
672    // All available providers, for your resolving pleasure.
673    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
674
675    // Mapping from provider base names (first directory in content URI codePath)
676    // to the provider information.
677    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
678            new ArrayMap<String, PackageParser.Provider>();
679
680    // Mapping from instrumentation class names to info about them.
681    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
682            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
683
684    // Mapping from permission names to info about them.
685    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
686            new ArrayMap<String, PackageParser.PermissionGroup>();
687
688    // Packages whose data we have transfered into another package, thus
689    // should no longer exist.
690    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
691
692    // Broadcast actions that are only available to the system.
693    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
694
695    /** List of packages waiting for verification. */
696    final SparseArray<PackageVerificationState> mPendingVerification
697            = new SparseArray<PackageVerificationState>();
698
699    /** Set of packages associated with each app op permission. */
700    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
701
702    final PackageInstallerService mInstallerService;
703
704    private final PackageDexOptimizer mPackageDexOptimizer;
705
706    private AtomicInteger mNextMoveId = new AtomicInteger();
707    private final MoveCallbacks mMoveCallbacks;
708
709    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
710
711    // Cache of users who need badging.
712    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
713
714    /** Token for keys in mPendingVerification. */
715    private int mPendingVerificationToken = 0;
716
717    volatile boolean mSystemReady;
718    volatile boolean mSafeMode;
719    volatile boolean mHasSystemUidErrors;
720
721    ApplicationInfo mAndroidApplication;
722    final ActivityInfo mResolveActivity = new ActivityInfo();
723    final ResolveInfo mResolveInfo = new ResolveInfo();
724    ComponentName mResolveComponentName;
725    PackageParser.Package mPlatformPackage;
726    ComponentName mCustomResolverComponentName;
727
728    boolean mResolverReplaced = false;
729
730    private final @Nullable ComponentName mIntentFilterVerifierComponent;
731    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
732
733    private int mIntentFilterVerificationToken = 0;
734
735    /** Component that knows whether or not an ephemeral application exists */
736    final ComponentName mEphemeralResolverComponent;
737    /** The service connection to the ephemeral resolver */
738    final EphemeralResolverConnection mEphemeralResolverConnection;
739
740    /** Component used to install ephemeral applications */
741    final ComponentName mEphemeralInstallerComponent;
742    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
743    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
744
745    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
746            = new SparseArray<IntentFilterVerificationState>();
747
748    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
749
750    // List of packages names to keep cached, even if they are uninstalled for all users
751    private List<String> mKeepUninstalledPackages;
752
753    private UserManagerInternal mUserManagerInternal;
754
755    private static class IFVerificationParams {
756        PackageParser.Package pkg;
757        boolean replacing;
758        int userId;
759        int verifierUid;
760
761        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
762                int _userId, int _verifierUid) {
763            pkg = _pkg;
764            replacing = _replacing;
765            userId = _userId;
766            replacing = _replacing;
767            verifierUid = _verifierUid;
768        }
769    }
770
771    private interface IntentFilterVerifier<T extends IntentFilter> {
772        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
773                                               T filter, String packageName);
774        void startVerifications(int userId);
775        void receiveVerificationResponse(int verificationId);
776    }
777
778    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
779        private Context mContext;
780        private ComponentName mIntentFilterVerifierComponent;
781        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
782
783        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
784            mContext = context;
785            mIntentFilterVerifierComponent = verifierComponent;
786        }
787
788        private String getDefaultScheme() {
789            return IntentFilter.SCHEME_HTTPS;
790        }
791
792        @Override
793        public void startVerifications(int userId) {
794            // Launch verifications requests
795            int count = mCurrentIntentFilterVerifications.size();
796            for (int n=0; n<count; n++) {
797                int verificationId = mCurrentIntentFilterVerifications.get(n);
798                final IntentFilterVerificationState ivs =
799                        mIntentFilterVerificationStates.get(verificationId);
800
801                String packageName = ivs.getPackageName();
802
803                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
804                final int filterCount = filters.size();
805                ArraySet<String> domainsSet = new ArraySet<>();
806                for (int m=0; m<filterCount; m++) {
807                    PackageParser.ActivityIntentInfo filter = filters.get(m);
808                    domainsSet.addAll(filter.getHostsList());
809                }
810                synchronized (mPackages) {
811                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
812                            packageName, domainsSet) != null) {
813                        scheduleWriteSettingsLocked();
814                    }
815                }
816                sendVerificationRequest(userId, verificationId, ivs);
817            }
818            mCurrentIntentFilterVerifications.clear();
819        }
820
821        private void sendVerificationRequest(int userId, int verificationId,
822                IntentFilterVerificationState ivs) {
823
824            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
825            verificationIntent.putExtra(
826                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
827                    verificationId);
828            verificationIntent.putExtra(
829                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
830                    getDefaultScheme());
831            verificationIntent.putExtra(
832                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
833                    ivs.getHostsString());
834            verificationIntent.putExtra(
835                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
836                    ivs.getPackageName());
837            verificationIntent.setComponent(mIntentFilterVerifierComponent);
838            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
839
840            UserHandle user = new UserHandle(userId);
841            mContext.sendBroadcastAsUser(verificationIntent, user);
842            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
843                    "Sending IntentFilter verification broadcast");
844        }
845
846        public void receiveVerificationResponse(int verificationId) {
847            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
848
849            final boolean verified = ivs.isVerified();
850
851            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
852            final int count = filters.size();
853            if (DEBUG_DOMAIN_VERIFICATION) {
854                Slog.i(TAG, "Received verification response " + verificationId
855                        + " for " + count + " filters, verified=" + verified);
856            }
857            for (int n=0; n<count; n++) {
858                PackageParser.ActivityIntentInfo filter = filters.get(n);
859                filter.setVerified(verified);
860
861                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
862                        + " verified with result:" + verified + " and hosts:"
863                        + ivs.getHostsString());
864            }
865
866            mIntentFilterVerificationStates.remove(verificationId);
867
868            final String packageName = ivs.getPackageName();
869            IntentFilterVerificationInfo ivi = null;
870
871            synchronized (mPackages) {
872                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
873            }
874            if (ivi == null) {
875                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
876                        + verificationId + " packageName:" + packageName);
877                return;
878            }
879            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
880                    "Updating IntentFilterVerificationInfo for package " + packageName
881                            +" verificationId:" + verificationId);
882
883            synchronized (mPackages) {
884                if (verified) {
885                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
886                } else {
887                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
888                }
889                scheduleWriteSettingsLocked();
890
891                final int userId = ivs.getUserId();
892                if (userId != UserHandle.USER_ALL) {
893                    final int userStatus =
894                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
895
896                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
897                    boolean needUpdate = false;
898
899                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
900                    // already been set by the User thru the Disambiguation dialog
901                    switch (userStatus) {
902                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
903                            if (verified) {
904                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
905                            } else {
906                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
907                            }
908                            needUpdate = true;
909                            break;
910
911                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
912                            if (verified) {
913                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
914                                needUpdate = true;
915                            }
916                            break;
917
918                        default:
919                            // Nothing to do
920                    }
921
922                    if (needUpdate) {
923                        mSettings.updateIntentFilterVerificationStatusLPw(
924                                packageName, updatedStatus, userId);
925                        scheduleWritePackageRestrictionsLocked(userId);
926                    }
927                }
928            }
929        }
930
931        @Override
932        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
933                    ActivityIntentInfo filter, String packageName) {
934            if (!hasValidDomains(filter)) {
935                return false;
936            }
937            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
938            if (ivs == null) {
939                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
940                        packageName);
941            }
942            if (DEBUG_DOMAIN_VERIFICATION) {
943                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
944            }
945            ivs.addFilter(filter);
946            return true;
947        }
948
949        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
950                int userId, int verificationId, String packageName) {
951            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
952                    verifierUid, userId, packageName);
953            ivs.setPendingState();
954            synchronized (mPackages) {
955                mIntentFilterVerificationStates.append(verificationId, ivs);
956                mCurrentIntentFilterVerifications.add(verificationId);
957            }
958            return ivs;
959        }
960    }
961
962    private static boolean hasValidDomains(ActivityIntentInfo filter) {
963        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
964                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
965                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
966    }
967
968    // Set of pending broadcasts for aggregating enable/disable of components.
969    static class PendingPackageBroadcasts {
970        // for each user id, a map of <package name -> components within that package>
971        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
972
973        public PendingPackageBroadcasts() {
974            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
975        }
976
977        public ArrayList<String> get(int userId, String packageName) {
978            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
979            return packages.get(packageName);
980        }
981
982        public void put(int userId, String packageName, ArrayList<String> components) {
983            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
984            packages.put(packageName, components);
985        }
986
987        public void remove(int userId, String packageName) {
988            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
989            if (packages != null) {
990                packages.remove(packageName);
991            }
992        }
993
994        public void remove(int userId) {
995            mUidMap.remove(userId);
996        }
997
998        public int userIdCount() {
999            return mUidMap.size();
1000        }
1001
1002        public int userIdAt(int n) {
1003            return mUidMap.keyAt(n);
1004        }
1005
1006        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1007            return mUidMap.get(userId);
1008        }
1009
1010        public int size() {
1011            // total number of pending broadcast entries across all userIds
1012            int num = 0;
1013            for (int i = 0; i< mUidMap.size(); i++) {
1014                num += mUidMap.valueAt(i).size();
1015            }
1016            return num;
1017        }
1018
1019        public void clear() {
1020            mUidMap.clear();
1021        }
1022
1023        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1024            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1025            if (map == null) {
1026                map = new ArrayMap<String, ArrayList<String>>();
1027                mUidMap.put(userId, map);
1028            }
1029            return map;
1030        }
1031    }
1032    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1033
1034    // Service Connection to remote media container service to copy
1035    // package uri's from external media onto secure containers
1036    // or internal storage.
1037    private IMediaContainerService mContainerService = null;
1038
1039    static final int SEND_PENDING_BROADCAST = 1;
1040    static final int MCS_BOUND = 3;
1041    static final int END_COPY = 4;
1042    static final int INIT_COPY = 5;
1043    static final int MCS_UNBIND = 6;
1044    static final int START_CLEANING_PACKAGE = 7;
1045    static final int FIND_INSTALL_LOC = 8;
1046    static final int POST_INSTALL = 9;
1047    static final int MCS_RECONNECT = 10;
1048    static final int MCS_GIVE_UP = 11;
1049    static final int UPDATED_MEDIA_STATUS = 12;
1050    static final int WRITE_SETTINGS = 13;
1051    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1052    static final int PACKAGE_VERIFIED = 15;
1053    static final int CHECK_PENDING_VERIFICATION = 16;
1054    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1055    static final int INTENT_FILTER_VERIFIED = 18;
1056    static final int WRITE_PACKAGE_LIST = 19;
1057
1058    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1059
1060    // Delay time in millisecs
1061    static final int BROADCAST_DELAY = 10 * 1000;
1062
1063    static UserManagerService sUserManager;
1064
1065    // Stores a list of users whose package restrictions file needs to be updated
1066    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1067
1068    final private DefaultContainerConnection mDefContainerConn =
1069            new DefaultContainerConnection();
1070    class DefaultContainerConnection implements ServiceConnection {
1071        public void onServiceConnected(ComponentName name, IBinder service) {
1072            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1073            IMediaContainerService imcs =
1074                IMediaContainerService.Stub.asInterface(service);
1075            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1076        }
1077
1078        public void onServiceDisconnected(ComponentName name) {
1079            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1080        }
1081    }
1082
1083    // Recordkeeping of restore-after-install operations that are currently in flight
1084    // between the Package Manager and the Backup Manager
1085    static class PostInstallData {
1086        public InstallArgs args;
1087        public PackageInstalledInfo res;
1088
1089        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1090            args = _a;
1091            res = _r;
1092        }
1093    }
1094
1095    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1096    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1097
1098    // XML tags for backup/restore of various bits of state
1099    private static final String TAG_PREFERRED_BACKUP = "pa";
1100    private static final String TAG_DEFAULT_APPS = "da";
1101    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1102
1103    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1104    private static final String TAG_ALL_GRANTS = "rt-grants";
1105    private static final String TAG_GRANT = "grant";
1106    private static final String ATTR_PACKAGE_NAME = "pkg";
1107
1108    private static final String TAG_PERMISSION = "perm";
1109    private static final String ATTR_PERMISSION_NAME = "name";
1110    private static final String ATTR_IS_GRANTED = "g";
1111    private static final String ATTR_USER_SET = "set";
1112    private static final String ATTR_USER_FIXED = "fixed";
1113    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1114
1115    // System/policy permission grants are not backed up
1116    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1117            FLAG_PERMISSION_POLICY_FIXED
1118            | FLAG_PERMISSION_SYSTEM_FIXED
1119            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1120
1121    // And we back up these user-adjusted states
1122    private static final int USER_RUNTIME_GRANT_MASK =
1123            FLAG_PERMISSION_USER_SET
1124            | FLAG_PERMISSION_USER_FIXED
1125            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1126
1127    final @Nullable String mRequiredVerifierPackage;
1128    final @NonNull String mRequiredInstallerPackage;
1129    final @NonNull String mRequiredUninstallerPackage;
1130    final @Nullable String mSetupWizardPackage;
1131    final @Nullable String mStorageManagerPackage;
1132    final @NonNull String mServicesSystemSharedLibraryPackageName;
1133    final @NonNull String mSharedSystemSharedLibraryPackageName;
1134
1135    final boolean mPermissionReviewRequired;
1136
1137    private final PackageUsage mPackageUsage = new PackageUsage();
1138    private final CompilerStats mCompilerStats = new CompilerStats();
1139
1140    class PackageHandler extends Handler {
1141        private boolean mBound = false;
1142        final ArrayList<HandlerParams> mPendingInstalls =
1143            new ArrayList<HandlerParams>();
1144
1145        private boolean connectToService() {
1146            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1147                    " DefaultContainerService");
1148            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1149            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1150            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1151                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1152                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1153                mBound = true;
1154                return true;
1155            }
1156            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1157            return false;
1158        }
1159
1160        private void disconnectService() {
1161            mContainerService = null;
1162            mBound = false;
1163            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1164            mContext.unbindService(mDefContainerConn);
1165            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1166        }
1167
1168        PackageHandler(Looper looper) {
1169            super(looper);
1170        }
1171
1172        public void handleMessage(Message msg) {
1173            try {
1174                doHandleMessage(msg);
1175            } finally {
1176                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1177            }
1178        }
1179
1180        void doHandleMessage(Message msg) {
1181            switch (msg.what) {
1182                case INIT_COPY: {
1183                    HandlerParams params = (HandlerParams) msg.obj;
1184                    int idx = mPendingInstalls.size();
1185                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1186                    // If a bind was already initiated we dont really
1187                    // need to do anything. The pending install
1188                    // will be processed later on.
1189                    if (!mBound) {
1190                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1191                                System.identityHashCode(mHandler));
1192                        // If this is the only one pending we might
1193                        // have to bind to the service again.
1194                        if (!connectToService()) {
1195                            Slog.e(TAG, "Failed to bind to media container service");
1196                            params.serviceError();
1197                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1198                                    System.identityHashCode(mHandler));
1199                            if (params.traceMethod != null) {
1200                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1201                                        params.traceCookie);
1202                            }
1203                            return;
1204                        } else {
1205                            // Once we bind to the service, the first
1206                            // pending request will be processed.
1207                            mPendingInstalls.add(idx, params);
1208                        }
1209                    } else {
1210                        mPendingInstalls.add(idx, params);
1211                        // Already bound to the service. Just make
1212                        // sure we trigger off processing the first request.
1213                        if (idx == 0) {
1214                            mHandler.sendEmptyMessage(MCS_BOUND);
1215                        }
1216                    }
1217                    break;
1218                }
1219                case MCS_BOUND: {
1220                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1221                    if (msg.obj != null) {
1222                        mContainerService = (IMediaContainerService) msg.obj;
1223                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1224                                System.identityHashCode(mHandler));
1225                    }
1226                    if (mContainerService == null) {
1227                        if (!mBound) {
1228                            // Something seriously wrong since we are not bound and we are not
1229                            // waiting for connection. Bail out.
1230                            Slog.e(TAG, "Cannot bind to media container service");
1231                            for (HandlerParams params : mPendingInstalls) {
1232                                // Indicate service bind error
1233                                params.serviceError();
1234                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1235                                        System.identityHashCode(params));
1236                                if (params.traceMethod != null) {
1237                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1238                                            params.traceMethod, params.traceCookie);
1239                                }
1240                                return;
1241                            }
1242                            mPendingInstalls.clear();
1243                        } else {
1244                            Slog.w(TAG, "Waiting to connect to media container service");
1245                        }
1246                    } else if (mPendingInstalls.size() > 0) {
1247                        HandlerParams params = mPendingInstalls.get(0);
1248                        if (params != null) {
1249                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1250                                    System.identityHashCode(params));
1251                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1252                            if (params.startCopy()) {
1253                                // We are done...  look for more work or to
1254                                // go idle.
1255                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1256                                        "Checking for more work or unbind...");
1257                                // Delete pending install
1258                                if (mPendingInstalls.size() > 0) {
1259                                    mPendingInstalls.remove(0);
1260                                }
1261                                if (mPendingInstalls.size() == 0) {
1262                                    if (mBound) {
1263                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1264                                                "Posting delayed MCS_UNBIND");
1265                                        removeMessages(MCS_UNBIND);
1266                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1267                                        // Unbind after a little delay, to avoid
1268                                        // continual thrashing.
1269                                        sendMessageDelayed(ubmsg, 10000);
1270                                    }
1271                                } else {
1272                                    // There are more pending requests in queue.
1273                                    // Just post MCS_BOUND message to trigger processing
1274                                    // of next pending install.
1275                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1276                                            "Posting MCS_BOUND for next work");
1277                                    mHandler.sendEmptyMessage(MCS_BOUND);
1278                                }
1279                            }
1280                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1281                        }
1282                    } else {
1283                        // Should never happen ideally.
1284                        Slog.w(TAG, "Empty queue");
1285                    }
1286                    break;
1287                }
1288                case MCS_RECONNECT: {
1289                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1290                    if (mPendingInstalls.size() > 0) {
1291                        if (mBound) {
1292                            disconnectService();
1293                        }
1294                        if (!connectToService()) {
1295                            Slog.e(TAG, "Failed to bind to media container service");
1296                            for (HandlerParams params : mPendingInstalls) {
1297                                // Indicate service bind error
1298                                params.serviceError();
1299                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1300                                        System.identityHashCode(params));
1301                            }
1302                            mPendingInstalls.clear();
1303                        }
1304                    }
1305                    break;
1306                }
1307                case MCS_UNBIND: {
1308                    // If there is no actual work left, then time to unbind.
1309                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1310
1311                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1312                        if (mBound) {
1313                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1314
1315                            disconnectService();
1316                        }
1317                    } else if (mPendingInstalls.size() > 0) {
1318                        // There are more pending requests in queue.
1319                        // Just post MCS_BOUND message to trigger processing
1320                        // of next pending install.
1321                        mHandler.sendEmptyMessage(MCS_BOUND);
1322                    }
1323
1324                    break;
1325                }
1326                case MCS_GIVE_UP: {
1327                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1328                    HandlerParams params = mPendingInstalls.remove(0);
1329                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1330                            System.identityHashCode(params));
1331                    break;
1332                }
1333                case SEND_PENDING_BROADCAST: {
1334                    String packages[];
1335                    ArrayList<String> components[];
1336                    int size = 0;
1337                    int uids[];
1338                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1339                    synchronized (mPackages) {
1340                        if (mPendingBroadcasts == null) {
1341                            return;
1342                        }
1343                        size = mPendingBroadcasts.size();
1344                        if (size <= 0) {
1345                            // Nothing to be done. Just return
1346                            return;
1347                        }
1348                        packages = new String[size];
1349                        components = new ArrayList[size];
1350                        uids = new int[size];
1351                        int i = 0;  // filling out the above arrays
1352
1353                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1354                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1355                            Iterator<Map.Entry<String, ArrayList<String>>> it
1356                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1357                                            .entrySet().iterator();
1358                            while (it.hasNext() && i < size) {
1359                                Map.Entry<String, ArrayList<String>> ent = it.next();
1360                                packages[i] = ent.getKey();
1361                                components[i] = ent.getValue();
1362                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1363                                uids[i] = (ps != null)
1364                                        ? UserHandle.getUid(packageUserId, ps.appId)
1365                                        : -1;
1366                                i++;
1367                            }
1368                        }
1369                        size = i;
1370                        mPendingBroadcasts.clear();
1371                    }
1372                    // Send broadcasts
1373                    for (int i = 0; i < size; i++) {
1374                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1375                    }
1376                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1377                    break;
1378                }
1379                case START_CLEANING_PACKAGE: {
1380                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1381                    final String packageName = (String)msg.obj;
1382                    final int userId = msg.arg1;
1383                    final boolean andCode = msg.arg2 != 0;
1384                    synchronized (mPackages) {
1385                        if (userId == UserHandle.USER_ALL) {
1386                            int[] users = sUserManager.getUserIds();
1387                            for (int user : users) {
1388                                mSettings.addPackageToCleanLPw(
1389                                        new PackageCleanItem(user, packageName, andCode));
1390                            }
1391                        } else {
1392                            mSettings.addPackageToCleanLPw(
1393                                    new PackageCleanItem(userId, packageName, andCode));
1394                        }
1395                    }
1396                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1397                    startCleaningPackages();
1398                } break;
1399                case POST_INSTALL: {
1400                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1401
1402                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1403                    final boolean didRestore = (msg.arg2 != 0);
1404                    mRunningInstalls.delete(msg.arg1);
1405
1406                    if (data != null) {
1407                        InstallArgs args = data.args;
1408                        PackageInstalledInfo parentRes = data.res;
1409
1410                        final boolean grantPermissions = (args.installFlags
1411                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1412                        final boolean killApp = (args.installFlags
1413                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1414                        final String[] grantedPermissions = args.installGrantPermissions;
1415
1416                        // Handle the parent package
1417                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1418                                grantedPermissions, didRestore, args.installerPackageName,
1419                                args.observer);
1420
1421                        // Handle the child packages
1422                        final int childCount = (parentRes.addedChildPackages != null)
1423                                ? parentRes.addedChildPackages.size() : 0;
1424                        for (int i = 0; i < childCount; i++) {
1425                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1426                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1427                                    grantedPermissions, false, args.installerPackageName,
1428                                    args.observer);
1429                        }
1430
1431                        // Log tracing if needed
1432                        if (args.traceMethod != null) {
1433                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1434                                    args.traceCookie);
1435                        }
1436                    } else {
1437                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1438                    }
1439
1440                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1441                } break;
1442                case UPDATED_MEDIA_STATUS: {
1443                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1444                    boolean reportStatus = msg.arg1 == 1;
1445                    boolean doGc = msg.arg2 == 1;
1446                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1447                    if (doGc) {
1448                        // Force a gc to clear up stale containers.
1449                        Runtime.getRuntime().gc();
1450                    }
1451                    if (msg.obj != null) {
1452                        @SuppressWarnings("unchecked")
1453                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1454                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1455                        // Unload containers
1456                        unloadAllContainers(args);
1457                    }
1458                    if (reportStatus) {
1459                        try {
1460                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1461                            PackageHelper.getMountService().finishMediaUpdate();
1462                        } catch (RemoteException e) {
1463                            Log.e(TAG, "MountService not running?");
1464                        }
1465                    }
1466                } break;
1467                case WRITE_SETTINGS: {
1468                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1469                    synchronized (mPackages) {
1470                        removeMessages(WRITE_SETTINGS);
1471                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1472                        mSettings.writeLPr();
1473                        mDirtyUsers.clear();
1474                    }
1475                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1476                } break;
1477                case WRITE_PACKAGE_RESTRICTIONS: {
1478                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1479                    synchronized (mPackages) {
1480                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1481                        for (int userId : mDirtyUsers) {
1482                            mSettings.writePackageRestrictionsLPr(userId);
1483                        }
1484                        mDirtyUsers.clear();
1485                    }
1486                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1487                } break;
1488                case WRITE_PACKAGE_LIST: {
1489                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1490                    synchronized (mPackages) {
1491                        removeMessages(WRITE_PACKAGE_LIST);
1492                        mSettings.writePackageListLPr(msg.arg1);
1493                    }
1494                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1495                } break;
1496                case CHECK_PENDING_VERIFICATION: {
1497                    final int verificationId = msg.arg1;
1498                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1499
1500                    if ((state != null) && !state.timeoutExtended()) {
1501                        final InstallArgs args = state.getInstallArgs();
1502                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1503
1504                        Slog.i(TAG, "Verification timed out for " + originUri);
1505                        mPendingVerification.remove(verificationId);
1506
1507                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1508
1509                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1510                            Slog.i(TAG, "Continuing with installation of " + originUri);
1511                            state.setVerifierResponse(Binder.getCallingUid(),
1512                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1513                            broadcastPackageVerified(verificationId, originUri,
1514                                    PackageManager.VERIFICATION_ALLOW,
1515                                    state.getInstallArgs().getUser());
1516                            try {
1517                                ret = args.copyApk(mContainerService, true);
1518                            } catch (RemoteException e) {
1519                                Slog.e(TAG, "Could not contact the ContainerService");
1520                            }
1521                        } else {
1522                            broadcastPackageVerified(verificationId, originUri,
1523                                    PackageManager.VERIFICATION_REJECT,
1524                                    state.getInstallArgs().getUser());
1525                        }
1526
1527                        Trace.asyncTraceEnd(
1528                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1529
1530                        processPendingInstall(args, ret);
1531                        mHandler.sendEmptyMessage(MCS_UNBIND);
1532                    }
1533                    break;
1534                }
1535                case PACKAGE_VERIFIED: {
1536                    final int verificationId = msg.arg1;
1537
1538                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1539                    if (state == null) {
1540                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1541                        break;
1542                    }
1543
1544                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1545
1546                    state.setVerifierResponse(response.callerUid, response.code);
1547
1548                    if (state.isVerificationComplete()) {
1549                        mPendingVerification.remove(verificationId);
1550
1551                        final InstallArgs args = state.getInstallArgs();
1552                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1553
1554                        int ret;
1555                        if (state.isInstallAllowed()) {
1556                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1557                            broadcastPackageVerified(verificationId, originUri,
1558                                    response.code, state.getInstallArgs().getUser());
1559                            try {
1560                                ret = args.copyApk(mContainerService, true);
1561                            } catch (RemoteException e) {
1562                                Slog.e(TAG, "Could not contact the ContainerService");
1563                            }
1564                        } else {
1565                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1566                        }
1567
1568                        Trace.asyncTraceEnd(
1569                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1570
1571                        processPendingInstall(args, ret);
1572                        mHandler.sendEmptyMessage(MCS_UNBIND);
1573                    }
1574
1575                    break;
1576                }
1577                case START_INTENT_FILTER_VERIFICATIONS: {
1578                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1579                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1580                            params.replacing, params.pkg);
1581                    break;
1582                }
1583                case INTENT_FILTER_VERIFIED: {
1584                    final int verificationId = msg.arg1;
1585
1586                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1587                            verificationId);
1588                    if (state == null) {
1589                        Slog.w(TAG, "Invalid IntentFilter verification token "
1590                                + verificationId + " received");
1591                        break;
1592                    }
1593
1594                    final int userId = state.getUserId();
1595
1596                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1597                            "Processing IntentFilter verification with token:"
1598                            + verificationId + " and userId:" + userId);
1599
1600                    final IntentFilterVerificationResponse response =
1601                            (IntentFilterVerificationResponse) msg.obj;
1602
1603                    state.setVerifierResponse(response.callerUid, response.code);
1604
1605                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1606                            "IntentFilter verification with token:" + verificationId
1607                            + " and userId:" + userId
1608                            + " is settings verifier response with response code:"
1609                            + response.code);
1610
1611                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1612                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1613                                + response.getFailedDomainsString());
1614                    }
1615
1616                    if (state.isVerificationComplete()) {
1617                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1618                    } else {
1619                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1620                                "IntentFilter verification with token:" + verificationId
1621                                + " was not said to be complete");
1622                    }
1623
1624                    break;
1625                }
1626            }
1627        }
1628    }
1629
1630    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1631            boolean killApp, String[] grantedPermissions,
1632            boolean launchedForRestore, String installerPackage,
1633            IPackageInstallObserver2 installObserver) {
1634        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1635            // Send the removed broadcasts
1636            if (res.removedInfo != null) {
1637                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1638            }
1639
1640            // Now that we successfully installed the package, grant runtime
1641            // permissions if requested before broadcasting the install.
1642            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1643                    >= Build.VERSION_CODES.M) {
1644                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1645            }
1646
1647            final boolean update = res.removedInfo != null
1648                    && res.removedInfo.removedPackage != null;
1649
1650            // If this is the first time we have child packages for a disabled privileged
1651            // app that had no children, we grant requested runtime permissions to the new
1652            // children if the parent on the system image had them already granted.
1653            if (res.pkg.parentPackage != null) {
1654                synchronized (mPackages) {
1655                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1656                }
1657            }
1658
1659            synchronized (mPackages) {
1660                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1661            }
1662
1663            final String packageName = res.pkg.applicationInfo.packageName;
1664            Bundle extras = new Bundle(1);
1665            extras.putInt(Intent.EXTRA_UID, res.uid);
1666
1667            // Determine the set of users who are adding this package for
1668            // the first time vs. those who are seeing an update.
1669            int[] firstUsers = EMPTY_INT_ARRAY;
1670            int[] updateUsers = EMPTY_INT_ARRAY;
1671            if (res.origUsers == null || res.origUsers.length == 0) {
1672                firstUsers = res.newUsers;
1673            } else {
1674                for (int newUser : res.newUsers) {
1675                    boolean isNew = true;
1676                    for (int origUser : res.origUsers) {
1677                        if (origUser == newUser) {
1678                            isNew = false;
1679                            break;
1680                        }
1681                    }
1682                    if (isNew) {
1683                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1684                    } else {
1685                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1686                    }
1687                }
1688            }
1689
1690            // Send installed broadcasts if the install/update is not ephemeral
1691            if (!isEphemeral(res.pkg)) {
1692                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1693
1694                // Send added for users that see the package for the first time
1695                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1696                        extras, 0 /*flags*/, null /*targetPackage*/,
1697                        null /*finishedReceiver*/, firstUsers);
1698
1699                // Send added for users that don't see the package for the first time
1700                if (update) {
1701                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1702                }
1703                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1704                        extras, 0 /*flags*/, null /*targetPackage*/,
1705                        null /*finishedReceiver*/, updateUsers);
1706
1707                // Send replaced for users that don't see the package for the first time
1708                if (update) {
1709                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1710                            packageName, extras, 0 /*flags*/,
1711                            null /*targetPackage*/, null /*finishedReceiver*/,
1712                            updateUsers);
1713                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1714                            null /*package*/, null /*extras*/, 0 /*flags*/,
1715                            packageName /*targetPackage*/,
1716                            null /*finishedReceiver*/, updateUsers);
1717                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1718                    // First-install and we did a restore, so we're responsible for the
1719                    // first-launch broadcast.
1720                    if (DEBUG_BACKUP) {
1721                        Slog.i(TAG, "Post-restore of " + packageName
1722                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1723                    }
1724                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1725                }
1726
1727                // Send broadcast package appeared if forward locked/external for all users
1728                // treat asec-hosted packages like removable media on upgrade
1729                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1730                    if (DEBUG_INSTALL) {
1731                        Slog.i(TAG, "upgrading pkg " + res.pkg
1732                                + " is ASEC-hosted -> AVAILABLE");
1733                    }
1734                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1735                    ArrayList<String> pkgList = new ArrayList<>(1);
1736                    pkgList.add(packageName);
1737                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1738                }
1739            }
1740
1741            // Work that needs to happen on first install within each user
1742            if (firstUsers != null && firstUsers.length > 0) {
1743                synchronized (mPackages) {
1744                    for (int userId : firstUsers) {
1745                        // If this app is a browser and it's newly-installed for some
1746                        // users, clear any default-browser state in those users. The
1747                        // app's nature doesn't depend on the user, so we can just check
1748                        // its browser nature in any user and generalize.
1749                        if (packageIsBrowser(packageName, userId)) {
1750                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1751                        }
1752
1753                        // We may also need to apply pending (restored) runtime
1754                        // permission grants within these users.
1755                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1756                    }
1757                }
1758            }
1759
1760            // Log current value of "unknown sources" setting
1761            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1762                    getUnknownSourcesSettings());
1763
1764            // Force a gc to clear up things
1765            Runtime.getRuntime().gc();
1766
1767            // Remove the replaced package's older resources safely now
1768            // We delete after a gc for applications  on sdcard.
1769            if (res.removedInfo != null && res.removedInfo.args != null) {
1770                synchronized (mInstallLock) {
1771                    res.removedInfo.args.doPostDeleteLI(true);
1772                }
1773            }
1774        }
1775
1776        // If someone is watching installs - notify them
1777        if (installObserver != null) {
1778            try {
1779                Bundle extras = extrasForInstallResult(res);
1780                installObserver.onPackageInstalled(res.name, res.returnCode,
1781                        res.returnMsg, extras);
1782            } catch (RemoteException e) {
1783                Slog.i(TAG, "Observer no longer exists.");
1784            }
1785        }
1786    }
1787
1788    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1789            PackageParser.Package pkg) {
1790        if (pkg.parentPackage == null) {
1791            return;
1792        }
1793        if (pkg.requestedPermissions == null) {
1794            return;
1795        }
1796        final PackageSetting disabledSysParentPs = mSettings
1797                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1798        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1799                || !disabledSysParentPs.isPrivileged()
1800                || (disabledSysParentPs.childPackageNames != null
1801                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1802            return;
1803        }
1804        final int[] allUserIds = sUserManager.getUserIds();
1805        final int permCount = pkg.requestedPermissions.size();
1806        for (int i = 0; i < permCount; i++) {
1807            String permission = pkg.requestedPermissions.get(i);
1808            BasePermission bp = mSettings.mPermissions.get(permission);
1809            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1810                continue;
1811            }
1812            for (int userId : allUserIds) {
1813                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1814                        permission, userId)) {
1815                    grantRuntimePermission(pkg.packageName, permission, userId);
1816                }
1817            }
1818        }
1819    }
1820
1821    private StorageEventListener mStorageListener = new StorageEventListener() {
1822        @Override
1823        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1824            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1825                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1826                    final String volumeUuid = vol.getFsUuid();
1827
1828                    // Clean up any users or apps that were removed or recreated
1829                    // while this volume was missing
1830                    reconcileUsers(volumeUuid);
1831                    reconcileApps(volumeUuid);
1832
1833                    // Clean up any install sessions that expired or were
1834                    // cancelled while this volume was missing
1835                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1836
1837                    loadPrivatePackages(vol);
1838
1839                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1840                    unloadPrivatePackages(vol);
1841                }
1842            }
1843
1844            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1845                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1846                    updateExternalMediaStatus(true, false);
1847                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1848                    updateExternalMediaStatus(false, false);
1849                }
1850            }
1851        }
1852
1853        @Override
1854        public void onVolumeForgotten(String fsUuid) {
1855            if (TextUtils.isEmpty(fsUuid)) {
1856                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1857                return;
1858            }
1859
1860            // Remove any apps installed on the forgotten volume
1861            synchronized (mPackages) {
1862                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1863                for (PackageSetting ps : packages) {
1864                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1865                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1866                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1867                }
1868
1869                mSettings.onVolumeForgotten(fsUuid);
1870                mSettings.writeLPr();
1871            }
1872        }
1873    };
1874
1875    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1876            String[] grantedPermissions) {
1877        for (int userId : userIds) {
1878            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1879        }
1880
1881        // We could have touched GID membership, so flush out packages.list
1882        synchronized (mPackages) {
1883            mSettings.writePackageListLPr();
1884        }
1885    }
1886
1887    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1888            String[] grantedPermissions) {
1889        SettingBase sb = (SettingBase) pkg.mExtras;
1890        if (sb == null) {
1891            return;
1892        }
1893
1894        PermissionsState permissionsState = sb.getPermissionsState();
1895
1896        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1897                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1898
1899        for (String permission : pkg.requestedPermissions) {
1900            final BasePermission bp;
1901            synchronized (mPackages) {
1902                bp = mSettings.mPermissions.get(permission);
1903            }
1904            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1905                    && (grantedPermissions == null
1906                           || ArrayUtils.contains(grantedPermissions, permission))) {
1907                final int flags = permissionsState.getPermissionFlags(permission, userId);
1908                // Installer cannot change immutable permissions.
1909                if ((flags & immutableFlags) == 0) {
1910                    grantRuntimePermission(pkg.packageName, permission, userId);
1911                }
1912            }
1913        }
1914    }
1915
1916    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1917        Bundle extras = null;
1918        switch (res.returnCode) {
1919            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1920                extras = new Bundle();
1921                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1922                        res.origPermission);
1923                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1924                        res.origPackage);
1925                break;
1926            }
1927            case PackageManager.INSTALL_SUCCEEDED: {
1928                extras = new Bundle();
1929                extras.putBoolean(Intent.EXTRA_REPLACING,
1930                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1931                break;
1932            }
1933        }
1934        return extras;
1935    }
1936
1937    void scheduleWriteSettingsLocked() {
1938        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1939            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1940        }
1941    }
1942
1943    void scheduleWritePackageListLocked(int userId) {
1944        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1945            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1946            msg.arg1 = userId;
1947            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1948        }
1949    }
1950
1951    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1952        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1953        scheduleWritePackageRestrictionsLocked(userId);
1954    }
1955
1956    void scheduleWritePackageRestrictionsLocked(int userId) {
1957        final int[] userIds = (userId == UserHandle.USER_ALL)
1958                ? sUserManager.getUserIds() : new int[]{userId};
1959        for (int nextUserId : userIds) {
1960            if (!sUserManager.exists(nextUserId)) return;
1961            mDirtyUsers.add(nextUserId);
1962            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1963                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1964            }
1965        }
1966    }
1967
1968    public static PackageManagerService main(Context context, Installer installer,
1969            boolean factoryTest, boolean onlyCore) {
1970        // Self-check for initial settings.
1971        PackageManagerServiceCompilerMapping.checkProperties();
1972
1973        PackageManagerService m = new PackageManagerService(context, installer,
1974                factoryTest, onlyCore);
1975        m.enableSystemUserPackages();
1976        ServiceManager.addService("package", m);
1977        return m;
1978    }
1979
1980    private void enableSystemUserPackages() {
1981        if (!UserManager.isSplitSystemUser()) {
1982            return;
1983        }
1984        // For system user, enable apps based on the following conditions:
1985        // - app is whitelisted or belong to one of these groups:
1986        //   -- system app which has no launcher icons
1987        //   -- system app which has INTERACT_ACROSS_USERS permission
1988        //   -- system IME app
1989        // - app is not in the blacklist
1990        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1991        Set<String> enableApps = new ArraySet<>();
1992        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1993                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1994                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1995        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1996        enableApps.addAll(wlApps);
1997        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1998                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1999        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2000        enableApps.removeAll(blApps);
2001        Log.i(TAG, "Applications installed for system user: " + enableApps);
2002        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2003                UserHandle.SYSTEM);
2004        final int allAppsSize = allAps.size();
2005        synchronized (mPackages) {
2006            for (int i = 0; i < allAppsSize; i++) {
2007                String pName = allAps.get(i);
2008                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2009                // Should not happen, but we shouldn't be failing if it does
2010                if (pkgSetting == null) {
2011                    continue;
2012                }
2013                boolean install = enableApps.contains(pName);
2014                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2015                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2016                            + " for system user");
2017                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2018                }
2019            }
2020        }
2021    }
2022
2023    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2024        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2025                Context.DISPLAY_SERVICE);
2026        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2027    }
2028
2029    /**
2030     * Requests that files preopted on a secondary system partition be copied to the data partition
2031     * if possible.  Note that the actual copying of the files is accomplished by init for security
2032     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2033     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2034     */
2035    private static void requestCopyPreoptedFiles() {
2036        final int WAIT_TIME_MS = 100;
2037        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2038        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2039            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2040            // We will wait for up to 100 seconds.
2041            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2042            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2043                try {
2044                    Thread.sleep(WAIT_TIME_MS);
2045                } catch (InterruptedException e) {
2046                    // Do nothing
2047                }
2048                if (SystemClock.uptimeMillis() > timeEnd) {
2049                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2050                    Slog.wtf(TAG, "cppreopt did not finish!");
2051                    break;
2052                }
2053            }
2054        }
2055    }
2056
2057    public PackageManagerService(Context context, Installer installer,
2058            boolean factoryTest, boolean onlyCore) {
2059        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2060        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2061                SystemClock.uptimeMillis());
2062
2063        if (mSdkVersion <= 0) {
2064            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2065        }
2066
2067        mContext = context;
2068
2069        mPermissionReviewRequired = context.getResources().getBoolean(
2070                R.bool.config_permissionReviewRequired);
2071
2072        mFactoryTest = factoryTest;
2073        mOnlyCore = onlyCore;
2074        mMetrics = new DisplayMetrics();
2075        mSettings = new Settings(mPackages);
2076        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2077                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2078        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2079                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2080        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2081                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2082        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2083                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2084        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2085                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2086        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2087                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2088
2089        String separateProcesses = SystemProperties.get("debug.separate_processes");
2090        if (separateProcesses != null && separateProcesses.length() > 0) {
2091            if ("*".equals(separateProcesses)) {
2092                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2093                mSeparateProcesses = null;
2094                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2095            } else {
2096                mDefParseFlags = 0;
2097                mSeparateProcesses = separateProcesses.split(",");
2098                Slog.w(TAG, "Running with debug.separate_processes: "
2099                        + separateProcesses);
2100            }
2101        } else {
2102            mDefParseFlags = 0;
2103            mSeparateProcesses = null;
2104        }
2105
2106        mInstaller = installer;
2107        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2108                "*dexopt*");
2109        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2110
2111        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2112                FgThread.get().getLooper());
2113
2114        getDefaultDisplayMetrics(context, mMetrics);
2115
2116        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2117        SystemConfig systemConfig = SystemConfig.getInstance();
2118        mGlobalGids = systemConfig.getGlobalGids();
2119        mSystemPermissions = systemConfig.getSystemPermissions();
2120        mAvailableFeatures = systemConfig.getAvailableFeatures();
2121        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2122
2123        mProtectedPackages = new ProtectedPackages(mContext);
2124
2125        synchronized (mInstallLock) {
2126        // writer
2127        synchronized (mPackages) {
2128            mHandlerThread = new ServiceThread(TAG,
2129                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2130            mHandlerThread.start();
2131            mHandler = new PackageHandler(mHandlerThread.getLooper());
2132            mProcessLoggingHandler = new ProcessLoggingHandler();
2133            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2134
2135            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2136
2137            File dataDir = Environment.getDataDirectory();
2138            mAppInstallDir = new File(dataDir, "app");
2139            mAppLib32InstallDir = new File(dataDir, "app-lib");
2140            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2141            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2142            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2143
2144            sUserManager = new UserManagerService(context, this, mPackages);
2145
2146            // Propagate permission configuration in to package manager.
2147            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2148                    = systemConfig.getPermissions();
2149            for (int i=0; i<permConfig.size(); i++) {
2150                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2151                BasePermission bp = mSettings.mPermissions.get(perm.name);
2152                if (bp == null) {
2153                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2154                    mSettings.mPermissions.put(perm.name, bp);
2155                }
2156                if (perm.gids != null) {
2157                    bp.setGids(perm.gids, perm.perUser);
2158                }
2159            }
2160
2161            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2162            for (int i=0; i<libConfig.size(); i++) {
2163                mSharedLibraries.put(libConfig.keyAt(i),
2164                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2165            }
2166
2167            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2168
2169            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2170            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2171            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2172
2173            if (mFirstBoot) {
2174                requestCopyPreoptedFiles();
2175            }
2176
2177            String customResolverActivity = Resources.getSystem().getString(
2178                    R.string.config_customResolverActivity);
2179            if (TextUtils.isEmpty(customResolverActivity)) {
2180                customResolverActivity = null;
2181            } else {
2182                mCustomResolverComponentName = ComponentName.unflattenFromString(
2183                        customResolverActivity);
2184            }
2185
2186            long startTime = SystemClock.uptimeMillis();
2187
2188            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2189                    startTime);
2190
2191            // Set flag to monitor and not change apk file paths when
2192            // scanning install directories.
2193            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2194
2195            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2196            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2197
2198            if (bootClassPath == null) {
2199                Slog.w(TAG, "No BOOTCLASSPATH found!");
2200            }
2201
2202            if (systemServerClassPath == null) {
2203                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2204            }
2205
2206            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2207            final String[] dexCodeInstructionSets =
2208                    getDexCodeInstructionSets(
2209                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2210
2211            /**
2212             * Ensure all external libraries have had dexopt run on them.
2213             */
2214            if (mSharedLibraries.size() > 0) {
2215                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2216                // NOTE: For now, we're compiling these system "shared libraries"
2217                // (and framework jars) into all available architectures. It's possible
2218                // to compile them only when we come across an app that uses them (there's
2219                // already logic for that in scanPackageLI) but that adds some complexity.
2220                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2221                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2222                        final String lib = libEntry.path;
2223                        if (lib == null) {
2224                            continue;
2225                        }
2226
2227                        try {
2228                            // Shared libraries do not have profiles so we perform a full
2229                            // AOT compilation (if needed).
2230                            int dexoptNeeded = DexFile.getDexOptNeeded(
2231                                    lib, dexCodeInstructionSet,
2232                                    getCompilerFilterForReason(REASON_SHARED_APK),
2233                                    false /* newProfile */);
2234                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2235                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2236                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2237                                        getCompilerFilterForReason(REASON_SHARED_APK),
2238                                        StorageManager.UUID_PRIVATE_INTERNAL,
2239                                        SKIP_SHARED_LIBRARY_CHECK);
2240                            }
2241                        } catch (FileNotFoundException e) {
2242                            Slog.w(TAG, "Library not found: " + lib);
2243                        } catch (IOException | InstallerException e) {
2244                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2245                                    + e.getMessage());
2246                        }
2247                    }
2248                }
2249                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2250            }
2251
2252            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2253
2254            final VersionInfo ver = mSettings.getInternalVersion();
2255            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2256
2257            // when upgrading from pre-M, promote system app permissions from install to runtime
2258            mPromoteSystemApps =
2259                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2260
2261            // When upgrading from pre-N, we need to handle package extraction like first boot,
2262            // as there is no profiling data available.
2263            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2264
2265            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2266
2267            // save off the names of pre-existing system packages prior to scanning; we don't
2268            // want to automatically grant runtime permissions for new system apps
2269            if (mPromoteSystemApps) {
2270                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2271                while (pkgSettingIter.hasNext()) {
2272                    PackageSetting ps = pkgSettingIter.next();
2273                    if (isSystemApp(ps)) {
2274                        mExistingSystemPackages.add(ps.name);
2275                    }
2276                }
2277            }
2278
2279            // Collect vendor overlay packages.
2280            // (Do this before scanning any apps.)
2281            // For security and version matching reason, only consider
2282            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2283            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2284            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2285                    | PackageParser.PARSE_IS_SYSTEM
2286                    | PackageParser.PARSE_IS_SYSTEM_DIR
2287                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2288
2289            // Find base frameworks (resource packages without code).
2290            scanDirTracedLI(frameworkDir, mDefParseFlags
2291                    | PackageParser.PARSE_IS_SYSTEM
2292                    | PackageParser.PARSE_IS_SYSTEM_DIR
2293                    | PackageParser.PARSE_IS_PRIVILEGED,
2294                    scanFlags | SCAN_NO_DEX, 0);
2295
2296            // Collected privileged system packages.
2297            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2298            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2299                    | PackageParser.PARSE_IS_SYSTEM
2300                    | PackageParser.PARSE_IS_SYSTEM_DIR
2301                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2302
2303            // Collect ordinary system packages.
2304            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2305            scanDirTracedLI(systemAppDir, mDefParseFlags
2306                    | PackageParser.PARSE_IS_SYSTEM
2307                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2308
2309            // Collect all vendor packages.
2310            File vendorAppDir = new File("/vendor/app");
2311            try {
2312                vendorAppDir = vendorAppDir.getCanonicalFile();
2313            } catch (IOException e) {
2314                // failed to look up canonical path, continue with original one
2315            }
2316            scanDirTracedLI(vendorAppDir, mDefParseFlags
2317                    | PackageParser.PARSE_IS_SYSTEM
2318                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2319
2320            // Collect all OEM packages.
2321            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2322            scanDirTracedLI(oemAppDir, mDefParseFlags
2323                    | PackageParser.PARSE_IS_SYSTEM
2324                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2325
2326            // Prune any system packages that no longer exist.
2327            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2328            if (!mOnlyCore) {
2329                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2330                while (psit.hasNext()) {
2331                    PackageSetting ps = psit.next();
2332
2333                    /*
2334                     * If this is not a system app, it can't be a
2335                     * disable system app.
2336                     */
2337                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2338                        continue;
2339                    }
2340
2341                    /*
2342                     * If the package is scanned, it's not erased.
2343                     */
2344                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2345                    if (scannedPkg != null) {
2346                        /*
2347                         * If the system app is both scanned and in the
2348                         * disabled packages list, then it must have been
2349                         * added via OTA. Remove it from the currently
2350                         * scanned package so the previously user-installed
2351                         * application can be scanned.
2352                         */
2353                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2354                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2355                                    + ps.name + "; removing system app.  Last known codePath="
2356                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2357                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2358                                    + scannedPkg.mVersionCode);
2359                            removePackageLI(scannedPkg, true);
2360                            mExpectingBetter.put(ps.name, ps.codePath);
2361                        }
2362
2363                        continue;
2364                    }
2365
2366                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2367                        psit.remove();
2368                        logCriticalInfo(Log.WARN, "System package " + ps.name
2369                                + " no longer exists; it's data will be wiped");
2370                        // Actual deletion of code and data will be handled by later
2371                        // reconciliation step
2372                    } else {
2373                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2374                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2375                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2376                        }
2377                    }
2378                }
2379            }
2380
2381            //look for any incomplete package installations
2382            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2383            for (int i = 0; i < deletePkgsList.size(); i++) {
2384                // Actual deletion of code and data will be handled by later
2385                // reconciliation step
2386                final String packageName = deletePkgsList.get(i).name;
2387                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2388                synchronized (mPackages) {
2389                    mSettings.removePackageLPw(packageName);
2390                }
2391            }
2392
2393            //delete tmp files
2394            deleteTempPackageFiles();
2395
2396            // Remove any shared userIDs that have no associated packages
2397            mSettings.pruneSharedUsersLPw();
2398
2399            if (!mOnlyCore) {
2400                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2401                        SystemClock.uptimeMillis());
2402                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2403
2404                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2405                        | PackageParser.PARSE_FORWARD_LOCK,
2406                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2407
2408                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2409                        | PackageParser.PARSE_IS_EPHEMERAL,
2410                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2411
2412                /**
2413                 * Remove disable package settings for any updated system
2414                 * apps that were removed via an OTA. If they're not a
2415                 * previously-updated app, remove them completely.
2416                 * Otherwise, just revoke their system-level permissions.
2417                 */
2418                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2419                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2420                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2421
2422                    String msg;
2423                    if (deletedPkg == null) {
2424                        msg = "Updated system package " + deletedAppName
2425                                + " no longer exists; it's data will be wiped";
2426                        // Actual deletion of code and data will be handled by later
2427                        // reconciliation step
2428                    } else {
2429                        msg = "Updated system app + " + deletedAppName
2430                                + " no longer present; removing system privileges for "
2431                                + deletedAppName;
2432
2433                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2434
2435                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2436                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2437                    }
2438                    logCriticalInfo(Log.WARN, msg);
2439                }
2440
2441                /**
2442                 * Make sure all system apps that we expected to appear on
2443                 * the userdata partition actually showed up. If they never
2444                 * appeared, crawl back and revive the system version.
2445                 */
2446                for (int i = 0; i < mExpectingBetter.size(); i++) {
2447                    final String packageName = mExpectingBetter.keyAt(i);
2448                    if (!mPackages.containsKey(packageName)) {
2449                        final File scanFile = mExpectingBetter.valueAt(i);
2450
2451                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2452                                + " but never showed up; reverting to system");
2453
2454                        int reparseFlags = mDefParseFlags;
2455                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2456                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2457                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2458                                    | PackageParser.PARSE_IS_PRIVILEGED;
2459                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2460                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2461                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2462                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2463                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2464                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2465                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2466                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2467                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2468                        } else {
2469                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2470                            continue;
2471                        }
2472
2473                        mSettings.enableSystemPackageLPw(packageName);
2474
2475                        try {
2476                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2477                        } catch (PackageManagerException e) {
2478                            Slog.e(TAG, "Failed to parse original system package: "
2479                                    + e.getMessage());
2480                        }
2481                    }
2482                }
2483            }
2484            mExpectingBetter.clear();
2485
2486            // Resolve the storage manager.
2487            mStorageManagerPackage = getStorageManagerPackageName();
2488
2489            // Resolve protected action filters. Only the setup wizard is allowed to
2490            // have a high priority filter for these actions.
2491            mSetupWizardPackage = getSetupWizardPackageName();
2492            if (mProtectedFilters.size() > 0) {
2493                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2494                    Slog.i(TAG, "No setup wizard;"
2495                        + " All protected intents capped to priority 0");
2496                }
2497                for (ActivityIntentInfo filter : mProtectedFilters) {
2498                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2499                        if (DEBUG_FILTERS) {
2500                            Slog.i(TAG, "Found setup wizard;"
2501                                + " allow priority " + filter.getPriority() + ";"
2502                                + " package: " + filter.activity.info.packageName
2503                                + " activity: " + filter.activity.className
2504                                + " priority: " + filter.getPriority());
2505                        }
2506                        // skip setup wizard; allow it to keep the high priority filter
2507                        continue;
2508                    }
2509                    Slog.w(TAG, "Protected action; cap priority to 0;"
2510                            + " package: " + filter.activity.info.packageName
2511                            + " activity: " + filter.activity.className
2512                            + " origPrio: " + filter.getPriority());
2513                    filter.setPriority(0);
2514                }
2515            }
2516            mDeferProtectedFilters = false;
2517            mProtectedFilters.clear();
2518
2519            // Now that we know all of the shared libraries, update all clients to have
2520            // the correct library paths.
2521            updateAllSharedLibrariesLPw();
2522
2523            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2524                // NOTE: We ignore potential failures here during a system scan (like
2525                // the rest of the commands above) because there's precious little we
2526                // can do about it. A settings error is reported, though.
2527                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2528                        false /* boot complete */);
2529            }
2530
2531            // Now that we know all the packages we are keeping,
2532            // read and update their last usage times.
2533            mPackageUsage.read(mPackages);
2534            mCompilerStats.read();
2535
2536            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2537                    SystemClock.uptimeMillis());
2538            Slog.i(TAG, "Time to scan packages: "
2539                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2540                    + " seconds");
2541
2542            // If the platform SDK has changed since the last time we booted,
2543            // we need to re-grant app permission to catch any new ones that
2544            // appear.  This is really a hack, and means that apps can in some
2545            // cases get permissions that the user didn't initially explicitly
2546            // allow...  it would be nice to have some better way to handle
2547            // this situation.
2548            int updateFlags = UPDATE_PERMISSIONS_ALL;
2549            if (ver.sdkVersion != mSdkVersion) {
2550                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2551                        + mSdkVersion + "; regranting permissions for internal storage");
2552                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2553            }
2554            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2555            ver.sdkVersion = mSdkVersion;
2556
2557            // If this is the first boot or an update from pre-M, and it is a normal
2558            // boot, then we need to initialize the default preferred apps across
2559            // all defined users.
2560            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2561                for (UserInfo user : sUserManager.getUsers(true)) {
2562                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2563                    applyFactoryDefaultBrowserLPw(user.id);
2564                    primeDomainVerificationsLPw(user.id);
2565                }
2566            }
2567
2568            // Prepare storage for system user really early during boot,
2569            // since core system apps like SettingsProvider and SystemUI
2570            // can't wait for user to start
2571            final int storageFlags;
2572            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2573                storageFlags = StorageManager.FLAG_STORAGE_DE;
2574            } else {
2575                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2576            }
2577            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2578                    storageFlags, true /* migrateAppData */);
2579
2580            // If this is first boot after an OTA, and a normal boot, then
2581            // we need to clear code cache directories.
2582            // Note that we do *not* clear the application profiles. These remain valid
2583            // across OTAs and are used to drive profile verification (post OTA) and
2584            // profile compilation (without waiting to collect a fresh set of profiles).
2585            if (mIsUpgrade && !onlyCore) {
2586                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2587                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2588                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2589                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2590                        // No apps are running this early, so no need to freeze
2591                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2592                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2593                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2594                    }
2595                }
2596                ver.fingerprint = Build.FINGERPRINT;
2597            }
2598
2599            checkDefaultBrowser();
2600
2601            // clear only after permissions and other defaults have been updated
2602            mExistingSystemPackages.clear();
2603            mPromoteSystemApps = false;
2604
2605            // All the changes are done during package scanning.
2606            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2607
2608            // can downgrade to reader
2609            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2610            mSettings.writeLPr();
2611            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2612
2613            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2614            // early on (before the package manager declares itself as early) because other
2615            // components in the system server might ask for package contexts for these apps.
2616            //
2617            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2618            // (i.e, that the data partition is unavailable).
2619            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2620                long start = System.nanoTime();
2621                List<PackageParser.Package> coreApps = new ArrayList<>();
2622                for (PackageParser.Package pkg : mPackages.values()) {
2623                    if (pkg.coreApp) {
2624                        coreApps.add(pkg);
2625                    }
2626                }
2627
2628                int[] stats = performDexOptUpgrade(coreApps, false,
2629                        getCompilerFilterForReason(REASON_CORE_APP));
2630
2631                final int elapsedTimeSeconds =
2632                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2633                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2634
2635                if (DEBUG_DEXOPT) {
2636                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2637                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2638                }
2639
2640
2641                // TODO: Should we log these stats to tron too ?
2642                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2643                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2644                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2645                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2646            }
2647
2648            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2649                    SystemClock.uptimeMillis());
2650
2651            if (!mOnlyCore) {
2652                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2653                mRequiredInstallerPackage = getRequiredInstallerLPr();
2654                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2655                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2656                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2657                        mIntentFilterVerifierComponent);
2658                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2659                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2660                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2661                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2662            } else {
2663                mRequiredVerifierPackage = null;
2664                mRequiredInstallerPackage = null;
2665                mRequiredUninstallerPackage = null;
2666                mIntentFilterVerifierComponent = null;
2667                mIntentFilterVerifier = null;
2668                mServicesSystemSharedLibraryPackageName = null;
2669                mSharedSystemSharedLibraryPackageName = null;
2670            }
2671
2672            mInstallerService = new PackageInstallerService(context, this);
2673
2674            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2675            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2676            // both the installer and resolver must be present to enable ephemeral
2677            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2678                if (DEBUG_EPHEMERAL) {
2679                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2680                            + " installer:" + ephemeralInstallerComponent);
2681                }
2682                mEphemeralResolverComponent = ephemeralResolverComponent;
2683                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2684                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2685                mEphemeralResolverConnection =
2686                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2687            } else {
2688                if (DEBUG_EPHEMERAL) {
2689                    final String missingComponent =
2690                            (ephemeralResolverComponent == null)
2691                            ? (ephemeralInstallerComponent == null)
2692                                    ? "resolver and installer"
2693                                    : "resolver"
2694                            : "installer";
2695                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2696                }
2697                mEphemeralResolverComponent = null;
2698                mEphemeralInstallerComponent = null;
2699                mEphemeralResolverConnection = null;
2700            }
2701
2702            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2703        } // synchronized (mPackages)
2704        } // synchronized (mInstallLock)
2705
2706        // Now after opening every single application zip, make sure they
2707        // are all flushed.  Not really needed, but keeps things nice and
2708        // tidy.
2709        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2710        Runtime.getRuntime().gc();
2711        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2712
2713        // The initial scanning above does many calls into installd while
2714        // holding the mPackages lock, but we're mostly interested in yelling
2715        // once we have a booted system.
2716        mInstaller.setWarnIfHeld(mPackages);
2717
2718        // Expose private service for system components to use.
2719        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2720        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2721    }
2722
2723    @Override
2724    public boolean isFirstBoot() {
2725        return mFirstBoot;
2726    }
2727
2728    @Override
2729    public boolean isOnlyCoreApps() {
2730        return mOnlyCore;
2731    }
2732
2733    @Override
2734    public boolean isUpgrade() {
2735        return mIsUpgrade;
2736    }
2737
2738    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2739        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2740
2741        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2742                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2743                UserHandle.USER_SYSTEM);
2744        if (matches.size() == 1) {
2745            return matches.get(0).getComponentInfo().packageName;
2746        } else if (matches.size() == 0) {
2747            Log.e(TAG, "There should probably be a verifier, but, none were found");
2748            return null;
2749        }
2750        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2751    }
2752
2753    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2754        synchronized (mPackages) {
2755            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2756            if (libraryEntry == null) {
2757                throw new IllegalStateException("Missing required shared library:" + libraryName);
2758            }
2759            return libraryEntry.apk;
2760        }
2761    }
2762
2763    private @NonNull String getRequiredInstallerLPr() {
2764        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2765        intent.addCategory(Intent.CATEGORY_DEFAULT);
2766        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2767
2768        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2769                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2770                UserHandle.USER_SYSTEM);
2771        if (matches.size() == 1) {
2772            ResolveInfo resolveInfo = matches.get(0);
2773            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2774                throw new RuntimeException("The installer must be a privileged app");
2775            }
2776            return matches.get(0).getComponentInfo().packageName;
2777        } else {
2778            throw new RuntimeException("There must be exactly one installer; found " + matches);
2779        }
2780    }
2781
2782    private @NonNull String getRequiredUninstallerLPr() {
2783        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2784        intent.addCategory(Intent.CATEGORY_DEFAULT);
2785        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2786
2787        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2788                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2789                UserHandle.USER_SYSTEM);
2790        if (resolveInfo == null ||
2791                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2792            throw new RuntimeException("There must be exactly one uninstaller; found "
2793                    + resolveInfo);
2794        }
2795        return resolveInfo.getComponentInfo().packageName;
2796    }
2797
2798    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2799        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2800
2801        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2802                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2803                UserHandle.USER_SYSTEM);
2804        ResolveInfo best = null;
2805        final int N = matches.size();
2806        for (int i = 0; i < N; i++) {
2807            final ResolveInfo cur = matches.get(i);
2808            final String packageName = cur.getComponentInfo().packageName;
2809            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2810                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2811                continue;
2812            }
2813
2814            if (best == null || cur.priority > best.priority) {
2815                best = cur;
2816            }
2817        }
2818
2819        if (best != null) {
2820            return best.getComponentInfo().getComponentName();
2821        } else {
2822            throw new RuntimeException("There must be at least one intent filter verifier");
2823        }
2824    }
2825
2826    private @Nullable ComponentName getEphemeralResolverLPr() {
2827        final String[] packageArray =
2828                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2829        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2830            if (DEBUG_EPHEMERAL) {
2831                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2832            }
2833            return null;
2834        }
2835
2836        final int resolveFlags =
2837                MATCH_DIRECT_BOOT_AWARE
2838                | MATCH_DIRECT_BOOT_UNAWARE
2839                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2840        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2841        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2842                resolveFlags, UserHandle.USER_SYSTEM);
2843
2844        final int N = resolvers.size();
2845        if (N == 0) {
2846            if (DEBUG_EPHEMERAL) {
2847                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2848            }
2849            return null;
2850        }
2851
2852        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2853        for (int i = 0; i < N; i++) {
2854            final ResolveInfo info = resolvers.get(i);
2855
2856            if (info.serviceInfo == null) {
2857                continue;
2858            }
2859
2860            final String packageName = info.serviceInfo.packageName;
2861            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2862                if (DEBUG_EPHEMERAL) {
2863                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2864                            + " pkg: " + packageName + ", info:" + info);
2865                }
2866                continue;
2867            }
2868
2869            if (DEBUG_EPHEMERAL) {
2870                Slog.v(TAG, "Ephemeral resolver found;"
2871                        + " pkg: " + packageName + ", info:" + info);
2872            }
2873            return new ComponentName(packageName, info.serviceInfo.name);
2874        }
2875        if (DEBUG_EPHEMERAL) {
2876            Slog.v(TAG, "Ephemeral resolver NOT found");
2877        }
2878        return null;
2879    }
2880
2881    private @Nullable ComponentName getEphemeralInstallerLPr() {
2882        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2883        intent.addCategory(Intent.CATEGORY_DEFAULT);
2884        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2885
2886        final int resolveFlags =
2887                MATCH_DIRECT_BOOT_AWARE
2888                | MATCH_DIRECT_BOOT_UNAWARE
2889                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2890        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2891                resolveFlags, UserHandle.USER_SYSTEM);
2892        if (matches.size() == 0) {
2893            return null;
2894        } else if (matches.size() == 1) {
2895            return matches.get(0).getComponentInfo().getComponentName();
2896        } else {
2897            throw new RuntimeException(
2898                    "There must be at most one ephemeral installer; found " + matches);
2899        }
2900    }
2901
2902    private void primeDomainVerificationsLPw(int userId) {
2903        if (DEBUG_DOMAIN_VERIFICATION) {
2904            Slog.d(TAG, "Priming domain verifications in user " + userId);
2905        }
2906
2907        SystemConfig systemConfig = SystemConfig.getInstance();
2908        ArraySet<String> packages = systemConfig.getLinkedApps();
2909
2910        for (String packageName : packages) {
2911            PackageParser.Package pkg = mPackages.get(packageName);
2912            if (pkg != null) {
2913                if (!pkg.isSystemApp()) {
2914                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2915                    continue;
2916                }
2917
2918                ArraySet<String> domains = null;
2919                for (PackageParser.Activity a : pkg.activities) {
2920                    for (ActivityIntentInfo filter : a.intents) {
2921                        if (hasValidDomains(filter)) {
2922                            if (domains == null) {
2923                                domains = new ArraySet<String>();
2924                            }
2925                            domains.addAll(filter.getHostsList());
2926                        }
2927                    }
2928                }
2929
2930                if (domains != null && domains.size() > 0) {
2931                    if (DEBUG_DOMAIN_VERIFICATION) {
2932                        Slog.v(TAG, "      + " + packageName);
2933                    }
2934                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2935                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2936                    // and then 'always' in the per-user state actually used for intent resolution.
2937                    final IntentFilterVerificationInfo ivi;
2938                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
2939                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2940                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2941                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2942                } else {
2943                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2944                            + "' does not handle web links");
2945                }
2946            } else {
2947                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2948            }
2949        }
2950
2951        scheduleWritePackageRestrictionsLocked(userId);
2952        scheduleWriteSettingsLocked();
2953    }
2954
2955    private void applyFactoryDefaultBrowserLPw(int userId) {
2956        // The default browser app's package name is stored in a string resource,
2957        // with a product-specific overlay used for vendor customization.
2958        String browserPkg = mContext.getResources().getString(
2959                com.android.internal.R.string.default_browser);
2960        if (!TextUtils.isEmpty(browserPkg)) {
2961            // non-empty string => required to be a known package
2962            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2963            if (ps == null) {
2964                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2965                browserPkg = null;
2966            } else {
2967                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2968            }
2969        }
2970
2971        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2972        // default.  If there's more than one, just leave everything alone.
2973        if (browserPkg == null) {
2974            calculateDefaultBrowserLPw(userId);
2975        }
2976    }
2977
2978    private void calculateDefaultBrowserLPw(int userId) {
2979        List<String> allBrowsers = resolveAllBrowserApps(userId);
2980        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2981        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2982    }
2983
2984    private List<String> resolveAllBrowserApps(int userId) {
2985        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2986        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2987                PackageManager.MATCH_ALL, userId);
2988
2989        final int count = list.size();
2990        List<String> result = new ArrayList<String>(count);
2991        for (int i=0; i<count; i++) {
2992            ResolveInfo info = list.get(i);
2993            if (info.activityInfo == null
2994                    || !info.handleAllWebDataURI
2995                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2996                    || result.contains(info.activityInfo.packageName)) {
2997                continue;
2998            }
2999            result.add(info.activityInfo.packageName);
3000        }
3001
3002        return result;
3003    }
3004
3005    private boolean packageIsBrowser(String packageName, int userId) {
3006        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3007                PackageManager.MATCH_ALL, userId);
3008        final int N = list.size();
3009        for (int i = 0; i < N; i++) {
3010            ResolveInfo info = list.get(i);
3011            if (packageName.equals(info.activityInfo.packageName)) {
3012                return true;
3013            }
3014        }
3015        return false;
3016    }
3017
3018    private void checkDefaultBrowser() {
3019        final int myUserId = UserHandle.myUserId();
3020        final String packageName = getDefaultBrowserPackageName(myUserId);
3021        if (packageName != null) {
3022            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3023            if (info == null) {
3024                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3025                synchronized (mPackages) {
3026                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3027                }
3028            }
3029        }
3030    }
3031
3032    @Override
3033    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3034            throws RemoteException {
3035        try {
3036            return super.onTransact(code, data, reply, flags);
3037        } catch (RuntimeException e) {
3038            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3039                Slog.wtf(TAG, "Package Manager Crash", e);
3040            }
3041            throw e;
3042        }
3043    }
3044
3045    static int[] appendInts(int[] cur, int[] add) {
3046        if (add == null) return cur;
3047        if (cur == null) return add;
3048        final int N = add.length;
3049        for (int i=0; i<N; i++) {
3050            cur = appendInt(cur, add[i]);
3051        }
3052        return cur;
3053    }
3054
3055    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3056        if (!sUserManager.exists(userId)) return null;
3057        if (ps == null) {
3058            return null;
3059        }
3060        final PackageParser.Package p = ps.pkg;
3061        if (p == null) {
3062            return null;
3063        }
3064
3065        final PermissionsState permissionsState = ps.getPermissionsState();
3066
3067        // Compute GIDs only if requested
3068        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3069                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3070        // Compute granted permissions only if package has requested permissions
3071        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3072                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3073        final PackageUserState state = ps.readUserState(userId);
3074
3075        return PackageParser.generatePackageInfo(p, gids, flags,
3076                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3077    }
3078
3079    @Override
3080    public void checkPackageStartable(String packageName, int userId) {
3081        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3082
3083        synchronized (mPackages) {
3084            final PackageSetting ps = mSettings.mPackages.get(packageName);
3085            if (ps == null) {
3086                throw new SecurityException("Package " + packageName + " was not found!");
3087            }
3088
3089            if (!ps.getInstalled(userId)) {
3090                throw new SecurityException(
3091                        "Package " + packageName + " was not installed for user " + userId + "!");
3092            }
3093
3094            if (mSafeMode && !ps.isSystem()) {
3095                throw new SecurityException("Package " + packageName + " not a system app!");
3096            }
3097
3098            if (mFrozenPackages.contains(packageName)) {
3099                throw new SecurityException("Package " + packageName + " is currently frozen!");
3100            }
3101
3102            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3103                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3104                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3105            }
3106        }
3107    }
3108
3109    @Override
3110    public boolean isPackageAvailable(String packageName, int userId) {
3111        if (!sUserManager.exists(userId)) return false;
3112        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3113                false /* requireFullPermission */, false /* checkShell */, "is package available");
3114        synchronized (mPackages) {
3115            PackageParser.Package p = mPackages.get(packageName);
3116            if (p != null) {
3117                final PackageSetting ps = (PackageSetting) p.mExtras;
3118                if (ps != null) {
3119                    final PackageUserState state = ps.readUserState(userId);
3120                    if (state != null) {
3121                        return PackageParser.isAvailable(state);
3122                    }
3123                }
3124            }
3125        }
3126        return false;
3127    }
3128
3129    @Override
3130    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3131        if (!sUserManager.exists(userId)) return null;
3132        flags = updateFlagsForPackage(flags, userId, packageName);
3133        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3134                false /* requireFullPermission */, false /* checkShell */, "get package info");
3135        // reader
3136        synchronized (mPackages) {
3137            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3138            PackageParser.Package p = null;
3139            if (matchFactoryOnly) {
3140                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3141                if (ps != null) {
3142                    return generatePackageInfo(ps, flags, userId);
3143                }
3144            }
3145            if (p == null) {
3146                p = mPackages.get(packageName);
3147                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3148                    return null;
3149                }
3150            }
3151            if (DEBUG_PACKAGE_INFO)
3152                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3153            if (p != null) {
3154                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3155            }
3156            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3157                final PackageSetting ps = mSettings.mPackages.get(packageName);
3158                return generatePackageInfo(ps, flags, userId);
3159            }
3160        }
3161        return null;
3162    }
3163
3164    @Override
3165    public String[] currentToCanonicalPackageNames(String[] names) {
3166        String[] out = new String[names.length];
3167        // reader
3168        synchronized (mPackages) {
3169            for (int i=names.length-1; i>=0; i--) {
3170                PackageSetting ps = mSettings.mPackages.get(names[i]);
3171                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3172            }
3173        }
3174        return out;
3175    }
3176
3177    @Override
3178    public String[] canonicalToCurrentPackageNames(String[] names) {
3179        String[] out = new String[names.length];
3180        // reader
3181        synchronized (mPackages) {
3182            for (int i=names.length-1; i>=0; i--) {
3183                String cur = mSettings.getRenamedPackageLPr(names[i]);
3184                out[i] = cur != null ? cur : names[i];
3185            }
3186        }
3187        return out;
3188    }
3189
3190    @Override
3191    public int getPackageUid(String packageName, int flags, int userId) {
3192        if (!sUserManager.exists(userId)) return -1;
3193        flags = updateFlagsForPackage(flags, userId, packageName);
3194        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3195                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3196
3197        // reader
3198        synchronized (mPackages) {
3199            final PackageParser.Package p = mPackages.get(packageName);
3200            if (p != null && p.isMatch(flags)) {
3201                return UserHandle.getUid(userId, p.applicationInfo.uid);
3202            }
3203            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3204                final PackageSetting ps = mSettings.mPackages.get(packageName);
3205                if (ps != null && ps.isMatch(flags)) {
3206                    return UserHandle.getUid(userId, ps.appId);
3207                }
3208            }
3209        }
3210
3211        return -1;
3212    }
3213
3214    @Override
3215    public int[] getPackageGids(String packageName, int flags, int userId) {
3216        if (!sUserManager.exists(userId)) return null;
3217        flags = updateFlagsForPackage(flags, userId, packageName);
3218        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3219                false /* requireFullPermission */, false /* checkShell */,
3220                "getPackageGids");
3221
3222        // reader
3223        synchronized (mPackages) {
3224            final PackageParser.Package p = mPackages.get(packageName);
3225            if (p != null && p.isMatch(flags)) {
3226                PackageSetting ps = (PackageSetting) p.mExtras;
3227                return ps.getPermissionsState().computeGids(userId);
3228            }
3229            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3230                final PackageSetting ps = mSettings.mPackages.get(packageName);
3231                if (ps != null && ps.isMatch(flags)) {
3232                    return ps.getPermissionsState().computeGids(userId);
3233                }
3234            }
3235        }
3236
3237        return null;
3238    }
3239
3240    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3241        if (bp.perm != null) {
3242            return PackageParser.generatePermissionInfo(bp.perm, flags);
3243        }
3244        PermissionInfo pi = new PermissionInfo();
3245        pi.name = bp.name;
3246        pi.packageName = bp.sourcePackage;
3247        pi.nonLocalizedLabel = bp.name;
3248        pi.protectionLevel = bp.protectionLevel;
3249        return pi;
3250    }
3251
3252    @Override
3253    public PermissionInfo getPermissionInfo(String name, int flags) {
3254        // reader
3255        synchronized (mPackages) {
3256            final BasePermission p = mSettings.mPermissions.get(name);
3257            if (p != null) {
3258                return generatePermissionInfo(p, flags);
3259            }
3260            return null;
3261        }
3262    }
3263
3264    @Override
3265    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3266            int flags) {
3267        // reader
3268        synchronized (mPackages) {
3269            if (group != null && !mPermissionGroups.containsKey(group)) {
3270                // This is thrown as NameNotFoundException
3271                return null;
3272            }
3273
3274            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3275            for (BasePermission p : mSettings.mPermissions.values()) {
3276                if (group == null) {
3277                    if (p.perm == null || p.perm.info.group == null) {
3278                        out.add(generatePermissionInfo(p, flags));
3279                    }
3280                } else {
3281                    if (p.perm != null && group.equals(p.perm.info.group)) {
3282                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3283                    }
3284                }
3285            }
3286            return new ParceledListSlice<>(out);
3287        }
3288    }
3289
3290    @Override
3291    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3292        // reader
3293        synchronized (mPackages) {
3294            return PackageParser.generatePermissionGroupInfo(
3295                    mPermissionGroups.get(name), flags);
3296        }
3297    }
3298
3299    @Override
3300    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3301        // reader
3302        synchronized (mPackages) {
3303            final int N = mPermissionGroups.size();
3304            ArrayList<PermissionGroupInfo> out
3305                    = new ArrayList<PermissionGroupInfo>(N);
3306            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3307                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3308            }
3309            return new ParceledListSlice<>(out);
3310        }
3311    }
3312
3313    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3314            int userId) {
3315        if (!sUserManager.exists(userId)) return null;
3316        PackageSetting ps = mSettings.mPackages.get(packageName);
3317        if (ps != null) {
3318            if (ps.pkg == null) {
3319                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3320                if (pInfo != null) {
3321                    return pInfo.applicationInfo;
3322                }
3323                return null;
3324            }
3325            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3326                    ps.readUserState(userId), userId);
3327        }
3328        return null;
3329    }
3330
3331    @Override
3332    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3333        if (!sUserManager.exists(userId)) return null;
3334        flags = updateFlagsForApplication(flags, userId, packageName);
3335        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3336                false /* requireFullPermission */, false /* checkShell */, "get application info");
3337        // writer
3338        synchronized (mPackages) {
3339            PackageParser.Package p = mPackages.get(packageName);
3340            if (DEBUG_PACKAGE_INFO) Log.v(
3341                    TAG, "getApplicationInfo " + packageName
3342                    + ": " + p);
3343            if (p != null) {
3344                PackageSetting ps = mSettings.mPackages.get(packageName);
3345                if (ps == null) return null;
3346                // Note: isEnabledLP() does not apply here - always return info
3347                return PackageParser.generateApplicationInfo(
3348                        p, flags, ps.readUserState(userId), userId);
3349            }
3350            if ("android".equals(packageName)||"system".equals(packageName)) {
3351                return mAndroidApplication;
3352            }
3353            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3354                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3355            }
3356        }
3357        return null;
3358    }
3359
3360    @Override
3361    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3362            final IPackageDataObserver observer) {
3363        mContext.enforceCallingOrSelfPermission(
3364                android.Manifest.permission.CLEAR_APP_CACHE, null);
3365        // Queue up an async operation since clearing cache may take a little while.
3366        mHandler.post(new Runnable() {
3367            public void run() {
3368                mHandler.removeCallbacks(this);
3369                boolean success = true;
3370                synchronized (mInstallLock) {
3371                    try {
3372                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3373                    } catch (InstallerException e) {
3374                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3375                        success = false;
3376                    }
3377                }
3378                if (observer != null) {
3379                    try {
3380                        observer.onRemoveCompleted(null, success);
3381                    } catch (RemoteException e) {
3382                        Slog.w(TAG, "RemoveException when invoking call back");
3383                    }
3384                }
3385            }
3386        });
3387    }
3388
3389    @Override
3390    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3391            final IntentSender pi) {
3392        mContext.enforceCallingOrSelfPermission(
3393                android.Manifest.permission.CLEAR_APP_CACHE, null);
3394        // Queue up an async operation since clearing cache may take a little while.
3395        mHandler.post(new Runnable() {
3396            public void run() {
3397                mHandler.removeCallbacks(this);
3398                boolean success = true;
3399                synchronized (mInstallLock) {
3400                    try {
3401                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3402                    } catch (InstallerException e) {
3403                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3404                        success = false;
3405                    }
3406                }
3407                if(pi != null) {
3408                    try {
3409                        // Callback via pending intent
3410                        int code = success ? 1 : 0;
3411                        pi.sendIntent(null, code, null,
3412                                null, null);
3413                    } catch (SendIntentException e1) {
3414                        Slog.i(TAG, "Failed to send pending intent");
3415                    }
3416                }
3417            }
3418        });
3419    }
3420
3421    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3422        synchronized (mInstallLock) {
3423            try {
3424                mInstaller.freeCache(volumeUuid, freeStorageSize);
3425            } catch (InstallerException e) {
3426                throw new IOException("Failed to free enough space", e);
3427            }
3428        }
3429    }
3430
3431    /**
3432     * Update given flags based on encryption status of current user.
3433     */
3434    private int updateFlags(int flags, int userId) {
3435        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3436                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3437            // Caller expressed an explicit opinion about what encryption
3438            // aware/unaware components they want to see, so fall through and
3439            // give them what they want
3440        } else {
3441            // Caller expressed no opinion, so match based on user state
3442            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3443                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3444            } else {
3445                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3446            }
3447        }
3448        return flags;
3449    }
3450
3451    private UserManagerInternal getUserManagerInternal() {
3452        if (mUserManagerInternal == null) {
3453            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3454        }
3455        return mUserManagerInternal;
3456    }
3457
3458    /**
3459     * Update given flags when being used to request {@link PackageInfo}.
3460     */
3461    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3462        boolean triaged = true;
3463        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3464                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3465            // Caller is asking for component details, so they'd better be
3466            // asking for specific encryption matching behavior, or be triaged
3467            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3468                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3469                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3470                triaged = false;
3471            }
3472        }
3473        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3474                | PackageManager.MATCH_SYSTEM_ONLY
3475                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3476            triaged = false;
3477        }
3478        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3479            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3480                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3481        }
3482        return updateFlags(flags, userId);
3483    }
3484
3485    /**
3486     * Update given flags when being used to request {@link ApplicationInfo}.
3487     */
3488    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3489        return updateFlagsForPackage(flags, userId, cookie);
3490    }
3491
3492    /**
3493     * Update given flags when being used to request {@link ComponentInfo}.
3494     */
3495    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3496        if (cookie instanceof Intent) {
3497            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3498                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3499            }
3500        }
3501
3502        boolean triaged = true;
3503        // Caller is asking for component details, so they'd better be
3504        // asking for specific encryption matching behavior, or be triaged
3505        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3506                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3507                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3508            triaged = false;
3509        }
3510        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3511            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3512                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3513        }
3514
3515        return updateFlags(flags, userId);
3516    }
3517
3518    /**
3519     * Update given flags when being used to request {@link ResolveInfo}.
3520     */
3521    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3522        // Safe mode means we shouldn't match any third-party components
3523        if (mSafeMode) {
3524            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3525        }
3526
3527        return updateFlagsForComponent(flags, userId, cookie);
3528    }
3529
3530    @Override
3531    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3532        if (!sUserManager.exists(userId)) return null;
3533        flags = updateFlagsForComponent(flags, userId, component);
3534        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3535                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3536        synchronized (mPackages) {
3537            PackageParser.Activity a = mActivities.mActivities.get(component);
3538
3539            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3540            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3541                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3542                if (ps == null) return null;
3543                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3544                        userId);
3545            }
3546            if (mResolveComponentName.equals(component)) {
3547                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3548                        new PackageUserState(), userId);
3549            }
3550        }
3551        return null;
3552    }
3553
3554    @Override
3555    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3556            String resolvedType) {
3557        synchronized (mPackages) {
3558            if (component.equals(mResolveComponentName)) {
3559                // The resolver supports EVERYTHING!
3560                return true;
3561            }
3562            PackageParser.Activity a = mActivities.mActivities.get(component);
3563            if (a == null) {
3564                return false;
3565            }
3566            for (int i=0; i<a.intents.size(); i++) {
3567                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3568                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3569                    return true;
3570                }
3571            }
3572            return false;
3573        }
3574    }
3575
3576    @Override
3577    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3578        if (!sUserManager.exists(userId)) return null;
3579        flags = updateFlagsForComponent(flags, userId, component);
3580        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3581                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3582        synchronized (mPackages) {
3583            PackageParser.Activity a = mReceivers.mActivities.get(component);
3584            if (DEBUG_PACKAGE_INFO) Log.v(
3585                TAG, "getReceiverInfo " + component + ": " + a);
3586            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3587                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3588                if (ps == null) return null;
3589                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3590                        userId);
3591            }
3592        }
3593        return null;
3594    }
3595
3596    @Override
3597    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3598        if (!sUserManager.exists(userId)) return null;
3599        flags = updateFlagsForComponent(flags, userId, component);
3600        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3601                false /* requireFullPermission */, false /* checkShell */, "get service info");
3602        synchronized (mPackages) {
3603            PackageParser.Service s = mServices.mServices.get(component);
3604            if (DEBUG_PACKAGE_INFO) Log.v(
3605                TAG, "getServiceInfo " + component + ": " + s);
3606            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3607                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3608                if (ps == null) return null;
3609                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3610                        userId);
3611            }
3612        }
3613        return null;
3614    }
3615
3616    @Override
3617    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3618        if (!sUserManager.exists(userId)) return null;
3619        flags = updateFlagsForComponent(flags, userId, component);
3620        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3621                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3622        synchronized (mPackages) {
3623            PackageParser.Provider p = mProviders.mProviders.get(component);
3624            if (DEBUG_PACKAGE_INFO) Log.v(
3625                TAG, "getProviderInfo " + component + ": " + p);
3626            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3627                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3628                if (ps == null) return null;
3629                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3630                        userId);
3631            }
3632        }
3633        return null;
3634    }
3635
3636    @Override
3637    public String[] getSystemSharedLibraryNames() {
3638        Set<String> libSet;
3639        synchronized (mPackages) {
3640            libSet = mSharedLibraries.keySet();
3641            int size = libSet.size();
3642            if (size > 0) {
3643                String[] libs = new String[size];
3644                libSet.toArray(libs);
3645                return libs;
3646            }
3647        }
3648        return null;
3649    }
3650
3651    @Override
3652    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3653        synchronized (mPackages) {
3654            return mServicesSystemSharedLibraryPackageName;
3655        }
3656    }
3657
3658    @Override
3659    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3660        synchronized (mPackages) {
3661            return mSharedSystemSharedLibraryPackageName;
3662        }
3663    }
3664
3665    @Override
3666    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3667        synchronized (mPackages) {
3668            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3669
3670            final FeatureInfo fi = new FeatureInfo();
3671            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3672                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3673            res.add(fi);
3674
3675            return new ParceledListSlice<>(res);
3676        }
3677    }
3678
3679    @Override
3680    public boolean hasSystemFeature(String name, int version) {
3681        synchronized (mPackages) {
3682            final FeatureInfo feat = mAvailableFeatures.get(name);
3683            if (feat == null) {
3684                return false;
3685            } else {
3686                return feat.version >= version;
3687            }
3688        }
3689    }
3690
3691    @Override
3692    public int checkPermission(String permName, String pkgName, int userId) {
3693        if (!sUserManager.exists(userId)) {
3694            return PackageManager.PERMISSION_DENIED;
3695        }
3696
3697        synchronized (mPackages) {
3698            final PackageParser.Package p = mPackages.get(pkgName);
3699            if (p != null && p.mExtras != null) {
3700                final PackageSetting ps = (PackageSetting) p.mExtras;
3701                final PermissionsState permissionsState = ps.getPermissionsState();
3702                if (permissionsState.hasPermission(permName, userId)) {
3703                    return PackageManager.PERMISSION_GRANTED;
3704                }
3705                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3706                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3707                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3708                    return PackageManager.PERMISSION_GRANTED;
3709                }
3710            }
3711        }
3712
3713        return PackageManager.PERMISSION_DENIED;
3714    }
3715
3716    @Override
3717    public int checkUidPermission(String permName, int uid) {
3718        final int userId = UserHandle.getUserId(uid);
3719
3720        if (!sUserManager.exists(userId)) {
3721            return PackageManager.PERMISSION_DENIED;
3722        }
3723
3724        synchronized (mPackages) {
3725            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3726            if (obj != null) {
3727                final SettingBase ps = (SettingBase) obj;
3728                final PermissionsState permissionsState = ps.getPermissionsState();
3729                if (permissionsState.hasPermission(permName, userId)) {
3730                    return PackageManager.PERMISSION_GRANTED;
3731                }
3732                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3733                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3734                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3735                    return PackageManager.PERMISSION_GRANTED;
3736                }
3737            } else {
3738                ArraySet<String> perms = mSystemPermissions.get(uid);
3739                if (perms != null) {
3740                    if (perms.contains(permName)) {
3741                        return PackageManager.PERMISSION_GRANTED;
3742                    }
3743                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3744                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3745                        return PackageManager.PERMISSION_GRANTED;
3746                    }
3747                }
3748            }
3749        }
3750
3751        return PackageManager.PERMISSION_DENIED;
3752    }
3753
3754    @Override
3755    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3756        if (UserHandle.getCallingUserId() != userId) {
3757            mContext.enforceCallingPermission(
3758                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3759                    "isPermissionRevokedByPolicy for user " + userId);
3760        }
3761
3762        if (checkPermission(permission, packageName, userId)
3763                == PackageManager.PERMISSION_GRANTED) {
3764            return false;
3765        }
3766
3767        final long identity = Binder.clearCallingIdentity();
3768        try {
3769            final int flags = getPermissionFlags(permission, packageName, userId);
3770            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3771        } finally {
3772            Binder.restoreCallingIdentity(identity);
3773        }
3774    }
3775
3776    @Override
3777    public String getPermissionControllerPackageName() {
3778        synchronized (mPackages) {
3779            return mRequiredInstallerPackage;
3780        }
3781    }
3782
3783    /**
3784     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3785     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3786     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3787     * @param message the message to log on security exception
3788     */
3789    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3790            boolean checkShell, String message) {
3791        if (userId < 0) {
3792            throw new IllegalArgumentException("Invalid userId " + userId);
3793        }
3794        if (checkShell) {
3795            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3796        }
3797        if (userId == UserHandle.getUserId(callingUid)) return;
3798        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3799            if (requireFullPermission) {
3800                mContext.enforceCallingOrSelfPermission(
3801                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3802            } else {
3803                try {
3804                    mContext.enforceCallingOrSelfPermission(
3805                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3806                } catch (SecurityException se) {
3807                    mContext.enforceCallingOrSelfPermission(
3808                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3809                }
3810            }
3811        }
3812    }
3813
3814    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3815        if (callingUid == Process.SHELL_UID) {
3816            if (userHandle >= 0
3817                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3818                throw new SecurityException("Shell does not have permission to access user "
3819                        + userHandle);
3820            } else if (userHandle < 0) {
3821                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3822                        + Debug.getCallers(3));
3823            }
3824        }
3825    }
3826
3827    private BasePermission findPermissionTreeLP(String permName) {
3828        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3829            if (permName.startsWith(bp.name) &&
3830                    permName.length() > bp.name.length() &&
3831                    permName.charAt(bp.name.length()) == '.') {
3832                return bp;
3833            }
3834        }
3835        return null;
3836    }
3837
3838    private BasePermission checkPermissionTreeLP(String permName) {
3839        if (permName != null) {
3840            BasePermission bp = findPermissionTreeLP(permName);
3841            if (bp != null) {
3842                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3843                    return bp;
3844                }
3845                throw new SecurityException("Calling uid "
3846                        + Binder.getCallingUid()
3847                        + " is not allowed to add to permission tree "
3848                        + bp.name + " owned by uid " + bp.uid);
3849            }
3850        }
3851        throw new SecurityException("No permission tree found for " + permName);
3852    }
3853
3854    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3855        if (s1 == null) {
3856            return s2 == null;
3857        }
3858        if (s2 == null) {
3859            return false;
3860        }
3861        if (s1.getClass() != s2.getClass()) {
3862            return false;
3863        }
3864        return s1.equals(s2);
3865    }
3866
3867    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3868        if (pi1.icon != pi2.icon) return false;
3869        if (pi1.logo != pi2.logo) return false;
3870        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3871        if (!compareStrings(pi1.name, pi2.name)) return false;
3872        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3873        // We'll take care of setting this one.
3874        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3875        // These are not currently stored in settings.
3876        //if (!compareStrings(pi1.group, pi2.group)) return false;
3877        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3878        //if (pi1.labelRes != pi2.labelRes) return false;
3879        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3880        return true;
3881    }
3882
3883    int permissionInfoFootprint(PermissionInfo info) {
3884        int size = info.name.length();
3885        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3886        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3887        return size;
3888    }
3889
3890    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3891        int size = 0;
3892        for (BasePermission perm : mSettings.mPermissions.values()) {
3893            if (perm.uid == tree.uid) {
3894                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3895            }
3896        }
3897        return size;
3898    }
3899
3900    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3901        // We calculate the max size of permissions defined by this uid and throw
3902        // if that plus the size of 'info' would exceed our stated maximum.
3903        if (tree.uid != Process.SYSTEM_UID) {
3904            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3905            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3906                throw new SecurityException("Permission tree size cap exceeded");
3907            }
3908        }
3909    }
3910
3911    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3912        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3913            throw new SecurityException("Label must be specified in permission");
3914        }
3915        BasePermission tree = checkPermissionTreeLP(info.name);
3916        BasePermission bp = mSettings.mPermissions.get(info.name);
3917        boolean added = bp == null;
3918        boolean changed = true;
3919        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3920        if (added) {
3921            enforcePermissionCapLocked(info, tree);
3922            bp = new BasePermission(info.name, tree.sourcePackage,
3923                    BasePermission.TYPE_DYNAMIC);
3924        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3925            throw new SecurityException(
3926                    "Not allowed to modify non-dynamic permission "
3927                    + info.name);
3928        } else {
3929            if (bp.protectionLevel == fixedLevel
3930                    && bp.perm.owner.equals(tree.perm.owner)
3931                    && bp.uid == tree.uid
3932                    && comparePermissionInfos(bp.perm.info, info)) {
3933                changed = false;
3934            }
3935        }
3936        bp.protectionLevel = fixedLevel;
3937        info = new PermissionInfo(info);
3938        info.protectionLevel = fixedLevel;
3939        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3940        bp.perm.info.packageName = tree.perm.info.packageName;
3941        bp.uid = tree.uid;
3942        if (added) {
3943            mSettings.mPermissions.put(info.name, bp);
3944        }
3945        if (changed) {
3946            if (!async) {
3947                mSettings.writeLPr();
3948            } else {
3949                scheduleWriteSettingsLocked();
3950            }
3951        }
3952        return added;
3953    }
3954
3955    @Override
3956    public boolean addPermission(PermissionInfo info) {
3957        synchronized (mPackages) {
3958            return addPermissionLocked(info, false);
3959        }
3960    }
3961
3962    @Override
3963    public boolean addPermissionAsync(PermissionInfo info) {
3964        synchronized (mPackages) {
3965            return addPermissionLocked(info, true);
3966        }
3967    }
3968
3969    @Override
3970    public void removePermission(String name) {
3971        synchronized (mPackages) {
3972            checkPermissionTreeLP(name);
3973            BasePermission bp = mSettings.mPermissions.get(name);
3974            if (bp != null) {
3975                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3976                    throw new SecurityException(
3977                            "Not allowed to modify non-dynamic permission "
3978                            + name);
3979                }
3980                mSettings.mPermissions.remove(name);
3981                mSettings.writeLPr();
3982            }
3983        }
3984    }
3985
3986    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3987            BasePermission bp) {
3988        int index = pkg.requestedPermissions.indexOf(bp.name);
3989        if (index == -1) {
3990            throw new SecurityException("Package " + pkg.packageName
3991                    + " has not requested permission " + bp.name);
3992        }
3993        if (!bp.isRuntime() && !bp.isDevelopment()) {
3994            throw new SecurityException("Permission " + bp.name
3995                    + " is not a changeable permission type");
3996        }
3997    }
3998
3999    @Override
4000    public void grantRuntimePermission(String packageName, String name, final int userId) {
4001        if (!sUserManager.exists(userId)) {
4002            Log.e(TAG, "No such user:" + userId);
4003            return;
4004        }
4005
4006        mContext.enforceCallingOrSelfPermission(
4007                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4008                "grantRuntimePermission");
4009
4010        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4011                true /* requireFullPermission */, true /* checkShell */,
4012                "grantRuntimePermission");
4013
4014        final int uid;
4015        final SettingBase sb;
4016
4017        synchronized (mPackages) {
4018            final PackageParser.Package pkg = mPackages.get(packageName);
4019            if (pkg == null) {
4020                throw new IllegalArgumentException("Unknown package: " + packageName);
4021            }
4022
4023            final BasePermission bp = mSettings.mPermissions.get(name);
4024            if (bp == null) {
4025                throw new IllegalArgumentException("Unknown permission: " + name);
4026            }
4027
4028            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4029
4030            // If a permission review is required for legacy apps we represent
4031            // their permissions as always granted runtime ones since we need
4032            // to keep the review required permission flag per user while an
4033            // install permission's state is shared across all users.
4034            if (mPermissionReviewRequired
4035                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4036                    && bp.isRuntime()) {
4037                return;
4038            }
4039
4040            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4041            sb = (SettingBase) pkg.mExtras;
4042            if (sb == null) {
4043                throw new IllegalArgumentException("Unknown package: " + packageName);
4044            }
4045
4046            final PermissionsState permissionsState = sb.getPermissionsState();
4047
4048            final int flags = permissionsState.getPermissionFlags(name, userId);
4049            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4050                throw new SecurityException("Cannot grant system fixed permission "
4051                        + name + " for package " + packageName);
4052            }
4053
4054            if (bp.isDevelopment()) {
4055                // Development permissions must be handled specially, since they are not
4056                // normal runtime permissions.  For now they apply to all users.
4057                if (permissionsState.grantInstallPermission(bp) !=
4058                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4059                    scheduleWriteSettingsLocked();
4060                }
4061                return;
4062            }
4063
4064            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4065                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4066                return;
4067            }
4068
4069            final int result = permissionsState.grantRuntimePermission(bp, userId);
4070            switch (result) {
4071                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4072                    return;
4073                }
4074
4075                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4076                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4077                    mHandler.post(new Runnable() {
4078                        @Override
4079                        public void run() {
4080                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4081                        }
4082                    });
4083                }
4084                break;
4085            }
4086
4087            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4088
4089            // Not critical if that is lost - app has to request again.
4090            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4091        }
4092
4093        // Only need to do this if user is initialized. Otherwise it's a new user
4094        // and there are no processes running as the user yet and there's no need
4095        // to make an expensive call to remount processes for the changed permissions.
4096        if (READ_EXTERNAL_STORAGE.equals(name)
4097                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4098            final long token = Binder.clearCallingIdentity();
4099            try {
4100                if (sUserManager.isInitialized(userId)) {
4101                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4102                            MountServiceInternal.class);
4103                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4104                }
4105            } finally {
4106                Binder.restoreCallingIdentity(token);
4107            }
4108        }
4109    }
4110
4111    @Override
4112    public void revokeRuntimePermission(String packageName, String name, int userId) {
4113        if (!sUserManager.exists(userId)) {
4114            Log.e(TAG, "No such user:" + userId);
4115            return;
4116        }
4117
4118        mContext.enforceCallingOrSelfPermission(
4119                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4120                "revokeRuntimePermission");
4121
4122        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4123                true /* requireFullPermission */, true /* checkShell */,
4124                "revokeRuntimePermission");
4125
4126        final int appId;
4127
4128        synchronized (mPackages) {
4129            final PackageParser.Package pkg = mPackages.get(packageName);
4130            if (pkg == null) {
4131                throw new IllegalArgumentException("Unknown package: " + packageName);
4132            }
4133
4134            final BasePermission bp = mSettings.mPermissions.get(name);
4135            if (bp == null) {
4136                throw new IllegalArgumentException("Unknown permission: " + name);
4137            }
4138
4139            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4140
4141            // If a permission review is required for legacy apps we represent
4142            // their permissions as always granted runtime ones since we need
4143            // to keep the review required permission flag per user while an
4144            // install permission's state is shared across all users.
4145            if (mPermissionReviewRequired
4146                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4147                    && bp.isRuntime()) {
4148                return;
4149            }
4150
4151            SettingBase sb = (SettingBase) pkg.mExtras;
4152            if (sb == null) {
4153                throw new IllegalArgumentException("Unknown package: " + packageName);
4154            }
4155
4156            final PermissionsState permissionsState = sb.getPermissionsState();
4157
4158            final int flags = permissionsState.getPermissionFlags(name, userId);
4159            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4160                throw new SecurityException("Cannot revoke system fixed permission "
4161                        + name + " for package " + packageName);
4162            }
4163
4164            if (bp.isDevelopment()) {
4165                // Development permissions must be handled specially, since they are not
4166                // normal runtime permissions.  For now they apply to all users.
4167                if (permissionsState.revokeInstallPermission(bp) !=
4168                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4169                    scheduleWriteSettingsLocked();
4170                }
4171                return;
4172            }
4173
4174            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4175                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4176                return;
4177            }
4178
4179            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4180
4181            // Critical, after this call app should never have the permission.
4182            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4183
4184            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4185        }
4186
4187        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4188    }
4189
4190    @Override
4191    public void resetRuntimePermissions() {
4192        mContext.enforceCallingOrSelfPermission(
4193                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4194                "revokeRuntimePermission");
4195
4196        int callingUid = Binder.getCallingUid();
4197        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4198            mContext.enforceCallingOrSelfPermission(
4199                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4200                    "resetRuntimePermissions");
4201        }
4202
4203        synchronized (mPackages) {
4204            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4205            for (int userId : UserManagerService.getInstance().getUserIds()) {
4206                final int packageCount = mPackages.size();
4207                for (int i = 0; i < packageCount; i++) {
4208                    PackageParser.Package pkg = mPackages.valueAt(i);
4209                    if (!(pkg.mExtras instanceof PackageSetting)) {
4210                        continue;
4211                    }
4212                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4213                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4214                }
4215            }
4216        }
4217    }
4218
4219    @Override
4220    public int getPermissionFlags(String name, String packageName, int userId) {
4221        if (!sUserManager.exists(userId)) {
4222            return 0;
4223        }
4224
4225        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4226
4227        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4228                true /* requireFullPermission */, false /* checkShell */,
4229                "getPermissionFlags");
4230
4231        synchronized (mPackages) {
4232            final PackageParser.Package pkg = mPackages.get(packageName);
4233            if (pkg == null) {
4234                return 0;
4235            }
4236
4237            final BasePermission bp = mSettings.mPermissions.get(name);
4238            if (bp == null) {
4239                return 0;
4240            }
4241
4242            SettingBase sb = (SettingBase) pkg.mExtras;
4243            if (sb == null) {
4244                return 0;
4245            }
4246
4247            PermissionsState permissionsState = sb.getPermissionsState();
4248            return permissionsState.getPermissionFlags(name, userId);
4249        }
4250    }
4251
4252    @Override
4253    public void updatePermissionFlags(String name, String packageName, int flagMask,
4254            int flagValues, int userId) {
4255        if (!sUserManager.exists(userId)) {
4256            return;
4257        }
4258
4259        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4260
4261        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4262                true /* requireFullPermission */, true /* checkShell */,
4263                "updatePermissionFlags");
4264
4265        // Only the system can change these flags and nothing else.
4266        if (getCallingUid() != Process.SYSTEM_UID) {
4267            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4268            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4269            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4270            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4271            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4272        }
4273
4274        synchronized (mPackages) {
4275            final PackageParser.Package pkg = mPackages.get(packageName);
4276            if (pkg == null) {
4277                throw new IllegalArgumentException("Unknown package: " + packageName);
4278            }
4279
4280            final BasePermission bp = mSettings.mPermissions.get(name);
4281            if (bp == null) {
4282                throw new IllegalArgumentException("Unknown permission: " + name);
4283            }
4284
4285            SettingBase sb = (SettingBase) pkg.mExtras;
4286            if (sb == null) {
4287                throw new IllegalArgumentException("Unknown package: " + packageName);
4288            }
4289
4290            PermissionsState permissionsState = sb.getPermissionsState();
4291
4292            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4293
4294            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4295                // Install and runtime permissions are stored in different places,
4296                // so figure out what permission changed and persist the change.
4297                if (permissionsState.getInstallPermissionState(name) != null) {
4298                    scheduleWriteSettingsLocked();
4299                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4300                        || hadState) {
4301                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4302                }
4303            }
4304        }
4305    }
4306
4307    /**
4308     * Update the permission flags for all packages and runtime permissions of a user in order
4309     * to allow device or profile owner to remove POLICY_FIXED.
4310     */
4311    @Override
4312    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4313        if (!sUserManager.exists(userId)) {
4314            return;
4315        }
4316
4317        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4318
4319        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4320                true /* requireFullPermission */, true /* checkShell */,
4321                "updatePermissionFlagsForAllApps");
4322
4323        // Only the system can change system fixed flags.
4324        if (getCallingUid() != Process.SYSTEM_UID) {
4325            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4326            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4327        }
4328
4329        synchronized (mPackages) {
4330            boolean changed = false;
4331            final int packageCount = mPackages.size();
4332            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4333                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4334                SettingBase sb = (SettingBase) pkg.mExtras;
4335                if (sb == null) {
4336                    continue;
4337                }
4338                PermissionsState permissionsState = sb.getPermissionsState();
4339                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4340                        userId, flagMask, flagValues);
4341            }
4342            if (changed) {
4343                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4344            }
4345        }
4346    }
4347
4348    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4349        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4350                != PackageManager.PERMISSION_GRANTED
4351            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4352                != PackageManager.PERMISSION_GRANTED) {
4353            throw new SecurityException(message + " requires "
4354                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4355                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4356        }
4357    }
4358
4359    @Override
4360    public boolean shouldShowRequestPermissionRationale(String permissionName,
4361            String packageName, int userId) {
4362        if (UserHandle.getCallingUserId() != userId) {
4363            mContext.enforceCallingPermission(
4364                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4365                    "canShowRequestPermissionRationale for user " + userId);
4366        }
4367
4368        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4369        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4370            return false;
4371        }
4372
4373        if (checkPermission(permissionName, packageName, userId)
4374                == PackageManager.PERMISSION_GRANTED) {
4375            return false;
4376        }
4377
4378        final int flags;
4379
4380        final long identity = Binder.clearCallingIdentity();
4381        try {
4382            flags = getPermissionFlags(permissionName,
4383                    packageName, userId);
4384        } finally {
4385            Binder.restoreCallingIdentity(identity);
4386        }
4387
4388        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4389                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4390                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4391
4392        if ((flags & fixedFlags) != 0) {
4393            return false;
4394        }
4395
4396        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4397    }
4398
4399    @Override
4400    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4401        mContext.enforceCallingOrSelfPermission(
4402                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4403                "addOnPermissionsChangeListener");
4404
4405        synchronized (mPackages) {
4406            mOnPermissionChangeListeners.addListenerLocked(listener);
4407        }
4408    }
4409
4410    @Override
4411    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4412        synchronized (mPackages) {
4413            mOnPermissionChangeListeners.removeListenerLocked(listener);
4414        }
4415    }
4416
4417    @Override
4418    public boolean isProtectedBroadcast(String actionName) {
4419        synchronized (mPackages) {
4420            if (mProtectedBroadcasts.contains(actionName)) {
4421                return true;
4422            } else if (actionName != null) {
4423                // TODO: remove these terrible hacks
4424                if (actionName.startsWith("android.net.netmon.lingerExpired")
4425                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4426                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4427                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4428                    return true;
4429                }
4430            }
4431        }
4432        return false;
4433    }
4434
4435    @Override
4436    public int checkSignatures(String pkg1, String pkg2) {
4437        synchronized (mPackages) {
4438            final PackageParser.Package p1 = mPackages.get(pkg1);
4439            final PackageParser.Package p2 = mPackages.get(pkg2);
4440            if (p1 == null || p1.mExtras == null
4441                    || p2 == null || p2.mExtras == null) {
4442                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4443            }
4444            return compareSignatures(p1.mSignatures, p2.mSignatures);
4445        }
4446    }
4447
4448    @Override
4449    public int checkUidSignatures(int uid1, int uid2) {
4450        // Map to base uids.
4451        uid1 = UserHandle.getAppId(uid1);
4452        uid2 = UserHandle.getAppId(uid2);
4453        // reader
4454        synchronized (mPackages) {
4455            Signature[] s1;
4456            Signature[] s2;
4457            Object obj = mSettings.getUserIdLPr(uid1);
4458            if (obj != null) {
4459                if (obj instanceof SharedUserSetting) {
4460                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4461                } else if (obj instanceof PackageSetting) {
4462                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4463                } else {
4464                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4465                }
4466            } else {
4467                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4468            }
4469            obj = mSettings.getUserIdLPr(uid2);
4470            if (obj != null) {
4471                if (obj instanceof SharedUserSetting) {
4472                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4473                } else if (obj instanceof PackageSetting) {
4474                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4475                } else {
4476                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4477                }
4478            } else {
4479                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4480            }
4481            return compareSignatures(s1, s2);
4482        }
4483    }
4484
4485    /**
4486     * This method should typically only be used when granting or revoking
4487     * permissions, since the app may immediately restart after this call.
4488     * <p>
4489     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4490     * guard your work against the app being relaunched.
4491     */
4492    private void killUid(int appId, int userId, String reason) {
4493        final long identity = Binder.clearCallingIdentity();
4494        try {
4495            IActivityManager am = ActivityManagerNative.getDefault();
4496            if (am != null) {
4497                try {
4498                    am.killUid(appId, userId, reason);
4499                } catch (RemoteException e) {
4500                    /* ignore - same process */
4501                }
4502            }
4503        } finally {
4504            Binder.restoreCallingIdentity(identity);
4505        }
4506    }
4507
4508    /**
4509     * Compares two sets of signatures. Returns:
4510     * <br />
4511     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4512     * <br />
4513     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4514     * <br />
4515     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4516     * <br />
4517     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4518     * <br />
4519     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4520     */
4521    static int compareSignatures(Signature[] s1, Signature[] s2) {
4522        if (s1 == null) {
4523            return s2 == null
4524                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4525                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4526        }
4527
4528        if (s2 == null) {
4529            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4530        }
4531
4532        if (s1.length != s2.length) {
4533            return PackageManager.SIGNATURE_NO_MATCH;
4534        }
4535
4536        // Since both signature sets are of size 1, we can compare without HashSets.
4537        if (s1.length == 1) {
4538            return s1[0].equals(s2[0]) ?
4539                    PackageManager.SIGNATURE_MATCH :
4540                    PackageManager.SIGNATURE_NO_MATCH;
4541        }
4542
4543        ArraySet<Signature> set1 = new ArraySet<Signature>();
4544        for (Signature sig : s1) {
4545            set1.add(sig);
4546        }
4547        ArraySet<Signature> set2 = new ArraySet<Signature>();
4548        for (Signature sig : s2) {
4549            set2.add(sig);
4550        }
4551        // Make sure s2 contains all signatures in s1.
4552        if (set1.equals(set2)) {
4553            return PackageManager.SIGNATURE_MATCH;
4554        }
4555        return PackageManager.SIGNATURE_NO_MATCH;
4556    }
4557
4558    /**
4559     * If the database version for this type of package (internal storage or
4560     * external storage) is less than the version where package signatures
4561     * were updated, return true.
4562     */
4563    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4564        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4565        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4566    }
4567
4568    /**
4569     * Used for backward compatibility to make sure any packages with
4570     * certificate chains get upgraded to the new style. {@code existingSigs}
4571     * will be in the old format (since they were stored on disk from before the
4572     * system upgrade) and {@code scannedSigs} will be in the newer format.
4573     */
4574    private int compareSignaturesCompat(PackageSignatures existingSigs,
4575            PackageParser.Package scannedPkg) {
4576        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4577            return PackageManager.SIGNATURE_NO_MATCH;
4578        }
4579
4580        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4581        for (Signature sig : existingSigs.mSignatures) {
4582            existingSet.add(sig);
4583        }
4584        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4585        for (Signature sig : scannedPkg.mSignatures) {
4586            try {
4587                Signature[] chainSignatures = sig.getChainSignatures();
4588                for (Signature chainSig : chainSignatures) {
4589                    scannedCompatSet.add(chainSig);
4590                }
4591            } catch (CertificateEncodingException e) {
4592                scannedCompatSet.add(sig);
4593            }
4594        }
4595        /*
4596         * Make sure the expanded scanned set contains all signatures in the
4597         * existing one.
4598         */
4599        if (scannedCompatSet.equals(existingSet)) {
4600            // Migrate the old signatures to the new scheme.
4601            existingSigs.assignSignatures(scannedPkg.mSignatures);
4602            // The new KeySets will be re-added later in the scanning process.
4603            synchronized (mPackages) {
4604                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4605            }
4606            return PackageManager.SIGNATURE_MATCH;
4607        }
4608        return PackageManager.SIGNATURE_NO_MATCH;
4609    }
4610
4611    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4612        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4613        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4614    }
4615
4616    private int compareSignaturesRecover(PackageSignatures existingSigs,
4617            PackageParser.Package scannedPkg) {
4618        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4619            return PackageManager.SIGNATURE_NO_MATCH;
4620        }
4621
4622        String msg = null;
4623        try {
4624            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4625                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4626                        + scannedPkg.packageName);
4627                return PackageManager.SIGNATURE_MATCH;
4628            }
4629        } catch (CertificateException e) {
4630            msg = e.getMessage();
4631        }
4632
4633        logCriticalInfo(Log.INFO,
4634                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4635        return PackageManager.SIGNATURE_NO_MATCH;
4636    }
4637
4638    @Override
4639    public List<String> getAllPackages() {
4640        synchronized (mPackages) {
4641            return new ArrayList<String>(mPackages.keySet());
4642        }
4643    }
4644
4645    @Override
4646    public String[] getPackagesForUid(int uid) {
4647        uid = UserHandle.getAppId(uid);
4648        // reader
4649        synchronized (mPackages) {
4650            Object obj = mSettings.getUserIdLPr(uid);
4651            if (obj instanceof SharedUserSetting) {
4652                final SharedUserSetting sus = (SharedUserSetting) obj;
4653                final int N = sus.packages.size();
4654                final String[] res = new String[N];
4655                for (int i = 0; i < N; i++) {
4656                    res[i] = sus.packages.valueAt(i).name;
4657                }
4658                return res;
4659            } else if (obj instanceof PackageSetting) {
4660                final PackageSetting ps = (PackageSetting) obj;
4661                return new String[] { ps.name };
4662            }
4663        }
4664        return null;
4665    }
4666
4667    @Override
4668    public String getNameForUid(int uid) {
4669        // reader
4670        synchronized (mPackages) {
4671            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4672            if (obj instanceof SharedUserSetting) {
4673                final SharedUserSetting sus = (SharedUserSetting) obj;
4674                return sus.name + ":" + sus.userId;
4675            } else if (obj instanceof PackageSetting) {
4676                final PackageSetting ps = (PackageSetting) obj;
4677                return ps.name;
4678            }
4679        }
4680        return null;
4681    }
4682
4683    @Override
4684    public int getUidForSharedUser(String sharedUserName) {
4685        if(sharedUserName == null) {
4686            return -1;
4687        }
4688        // reader
4689        synchronized (mPackages) {
4690            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4691            if (suid == null) {
4692                return -1;
4693            }
4694            return suid.userId;
4695        }
4696    }
4697
4698    @Override
4699    public int getFlagsForUid(int uid) {
4700        synchronized (mPackages) {
4701            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4702            if (obj instanceof SharedUserSetting) {
4703                final SharedUserSetting sus = (SharedUserSetting) obj;
4704                return sus.pkgFlags;
4705            } else if (obj instanceof PackageSetting) {
4706                final PackageSetting ps = (PackageSetting) obj;
4707                return ps.pkgFlags;
4708            }
4709        }
4710        return 0;
4711    }
4712
4713    @Override
4714    public int getPrivateFlagsForUid(int uid) {
4715        synchronized (mPackages) {
4716            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4717            if (obj instanceof SharedUserSetting) {
4718                final SharedUserSetting sus = (SharedUserSetting) obj;
4719                return sus.pkgPrivateFlags;
4720            } else if (obj instanceof PackageSetting) {
4721                final PackageSetting ps = (PackageSetting) obj;
4722                return ps.pkgPrivateFlags;
4723            }
4724        }
4725        return 0;
4726    }
4727
4728    @Override
4729    public boolean isUidPrivileged(int uid) {
4730        uid = UserHandle.getAppId(uid);
4731        // reader
4732        synchronized (mPackages) {
4733            Object obj = mSettings.getUserIdLPr(uid);
4734            if (obj instanceof SharedUserSetting) {
4735                final SharedUserSetting sus = (SharedUserSetting) obj;
4736                final Iterator<PackageSetting> it = sus.packages.iterator();
4737                while (it.hasNext()) {
4738                    if (it.next().isPrivileged()) {
4739                        return true;
4740                    }
4741                }
4742            } else if (obj instanceof PackageSetting) {
4743                final PackageSetting ps = (PackageSetting) obj;
4744                return ps.isPrivileged();
4745            }
4746        }
4747        return false;
4748    }
4749
4750    @Override
4751    public String[] getAppOpPermissionPackages(String permissionName) {
4752        synchronized (mPackages) {
4753            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4754            if (pkgs == null) {
4755                return null;
4756            }
4757            return pkgs.toArray(new String[pkgs.size()]);
4758        }
4759    }
4760
4761    @Override
4762    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4763            int flags, int userId) {
4764        try {
4765            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4766
4767            if (!sUserManager.exists(userId)) return null;
4768            flags = updateFlagsForResolve(flags, userId, intent);
4769            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4770                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4771
4772            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4773            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4774                    flags, userId);
4775            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4776
4777            final ResolveInfo bestChoice =
4778                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4779            return bestChoice;
4780        } finally {
4781            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4782        }
4783    }
4784
4785    @Override
4786    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4787            IntentFilter filter, int match, ComponentName activity) {
4788        final int userId = UserHandle.getCallingUserId();
4789        if (DEBUG_PREFERRED) {
4790            Log.v(TAG, "setLastChosenActivity intent=" + intent
4791                + " resolvedType=" + resolvedType
4792                + " flags=" + flags
4793                + " filter=" + filter
4794                + " match=" + match
4795                + " activity=" + activity);
4796            filter.dump(new PrintStreamPrinter(System.out), "    ");
4797        }
4798        intent.setComponent(null);
4799        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4800                userId);
4801        // Find any earlier preferred or last chosen entries and nuke them
4802        findPreferredActivity(intent, resolvedType,
4803                flags, query, 0, false, true, false, userId);
4804        // Add the new activity as the last chosen for this filter
4805        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4806                "Setting last chosen");
4807    }
4808
4809    @Override
4810    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4811        final int userId = UserHandle.getCallingUserId();
4812        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4813        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4814                userId);
4815        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4816                false, false, false, userId);
4817    }
4818
4819    private boolean isEphemeralDisabled() {
4820        // ephemeral apps have been disabled across the board
4821        if (DISABLE_EPHEMERAL_APPS) {
4822            return true;
4823        }
4824        // system isn't up yet; can't read settings, so, assume no ephemeral apps
4825        if (!mSystemReady) {
4826            return true;
4827        }
4828        return Secure.getInt(mContext.getContentResolver(), Secure.WEB_ACTION_ENABLED, 1) == 0;
4829    }
4830
4831    private boolean isEphemeralAllowed(
4832            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4833            boolean skipPackageCheck) {
4834        // Short circuit and return early if possible.
4835        if (isEphemeralDisabled()) {
4836            return false;
4837        }
4838        final int callingUser = UserHandle.getCallingUserId();
4839        if (callingUser != UserHandle.USER_SYSTEM) {
4840            return false;
4841        }
4842        if (mEphemeralResolverConnection == null) {
4843            return false;
4844        }
4845        if (intent.getComponent() != null) {
4846            return false;
4847        }
4848        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4849            return false;
4850        }
4851        if (!skipPackageCheck && intent.getPackage() != null) {
4852            return false;
4853        }
4854        final boolean isWebUri = hasWebURI(intent);
4855        if (!isWebUri || intent.getData().getHost() == null) {
4856            return false;
4857        }
4858        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4859        synchronized (mPackages) {
4860            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4861            for (int n = 0; n < count; n++) {
4862                ResolveInfo info = resolvedActivities.get(n);
4863                String packageName = info.activityInfo.packageName;
4864                PackageSetting ps = mSettings.mPackages.get(packageName);
4865                if (ps != null) {
4866                    // Try to get the status from User settings first
4867                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4868                    int status = (int) (packedStatus >> 32);
4869                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4870                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4871                        if (DEBUG_EPHEMERAL) {
4872                            Slog.v(TAG, "DENY ephemeral apps;"
4873                                + " pkg: " + packageName + ", status: " + status);
4874                        }
4875                        return false;
4876                    }
4877                }
4878            }
4879        }
4880        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4881        return true;
4882    }
4883
4884    private static EphemeralResolveInfo getEphemeralResolveInfo(
4885            Context context, EphemeralResolverConnection resolverConnection, Intent intent,
4886            String resolvedType, int userId, String packageName) {
4887        final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(),
4888                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4889        final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(),
4890                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4891        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4892                ephemeralPrefixCount);
4893        final int[] shaPrefix = digest.getDigestPrefix();
4894        final byte[][] digestBytes = digest.getDigestBytes();
4895        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4896                resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask);
4897        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4898            // No hash prefix match; there are no ephemeral apps for this domain.
4899            return null;
4900        }
4901
4902        // Go in reverse order so we match the narrowest scope first.
4903        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4904            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4905                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4906                    continue;
4907                }
4908                final List<IntentFilter> filters = ephemeralApplication.getFilters();
4909                // No filters; this should never happen.
4910                if (filters.isEmpty()) {
4911                    continue;
4912                }
4913                if (packageName != null
4914                        && !packageName.equals(ephemeralApplication.getPackageName())) {
4915                    continue;
4916                }
4917                // We have a domain match; resolve the filters to see if anything matches.
4918                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4919                for (int j = filters.size() - 1; j >= 0; --j) {
4920                    final EphemeralResolveIntentInfo intentInfo =
4921                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4922                    ephemeralResolver.addFilter(intentInfo);
4923                }
4924                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4925                        intent, resolvedType, false /*defaultOnly*/, userId);
4926                if (!matchedResolveInfoList.isEmpty()) {
4927                    return matchedResolveInfoList.get(0);
4928                }
4929            }
4930        }
4931        // Hash or filter mis-match; no ephemeral apps for this domain.
4932        return null;
4933    }
4934
4935    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4936            int flags, List<ResolveInfo> query, int userId) {
4937        if (query != null) {
4938            final int N = query.size();
4939            if (N == 1) {
4940                return query.get(0);
4941            } else if (N > 1) {
4942                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4943                // If there is more than one activity with the same priority,
4944                // then let the user decide between them.
4945                ResolveInfo r0 = query.get(0);
4946                ResolveInfo r1 = query.get(1);
4947                if (DEBUG_INTENT_MATCHING || debug) {
4948                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4949                            + r1.activityInfo.name + "=" + r1.priority);
4950                }
4951                // If the first activity has a higher priority, or a different
4952                // default, then it is always desirable to pick it.
4953                if (r0.priority != r1.priority
4954                        || r0.preferredOrder != r1.preferredOrder
4955                        || r0.isDefault != r1.isDefault) {
4956                    return query.get(0);
4957                }
4958                // If we have saved a preference for a preferred activity for
4959                // this Intent, use that.
4960                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4961                        flags, query, r0.priority, true, false, debug, userId);
4962                if (ri != null) {
4963                    return ri;
4964                }
4965                ri = new ResolveInfo(mResolveInfo);
4966                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4967                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
4968                // If all of the options come from the same package, show the application's
4969                // label and icon instead of the generic resolver's.
4970                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
4971                // and then throw away the ResolveInfo itself, meaning that the caller loses
4972                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
4973                // a fallback for this case; we only set the target package's resources on
4974                // the ResolveInfo, not the ActivityInfo.
4975                final String intentPackage = intent.getPackage();
4976                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
4977                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
4978                    ri.resolvePackageName = intentPackage;
4979                    if (userNeedsBadging(userId)) {
4980                        ri.noResourceId = true;
4981                    } else {
4982                        ri.icon = appi.icon;
4983                    }
4984                    ri.iconResourceId = appi.icon;
4985                    ri.labelRes = appi.labelRes;
4986                }
4987                ri.activityInfo.applicationInfo = new ApplicationInfo(
4988                        ri.activityInfo.applicationInfo);
4989                if (userId != 0) {
4990                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4991                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4992                }
4993                // Make sure that the resolver is displayable in car mode
4994                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4995                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4996                return ri;
4997            }
4998        }
4999        return null;
5000    }
5001
5002    /**
5003     * Return true if the given list is not empty and all of its contents have
5004     * an activityInfo with the given package name.
5005     */
5006    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5007        if (ArrayUtils.isEmpty(list)) {
5008            return false;
5009        }
5010        for (int i = 0, N = list.size(); i < N; i++) {
5011            final ResolveInfo ri = list.get(i);
5012            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5013            if (ai == null || !packageName.equals(ai.packageName)) {
5014                return false;
5015            }
5016        }
5017        return true;
5018    }
5019
5020    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5021            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5022        final int N = query.size();
5023        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5024                .get(userId);
5025        // Get the list of persistent preferred activities that handle the intent
5026        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5027        List<PersistentPreferredActivity> pprefs = ppir != null
5028                ? ppir.queryIntent(intent, resolvedType,
5029                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5030                : null;
5031        if (pprefs != null && pprefs.size() > 0) {
5032            final int M = pprefs.size();
5033            for (int i=0; i<M; i++) {
5034                final PersistentPreferredActivity ppa = pprefs.get(i);
5035                if (DEBUG_PREFERRED || debug) {
5036                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5037                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5038                            + "\n  component=" + ppa.mComponent);
5039                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5040                }
5041                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5042                        flags | MATCH_DISABLED_COMPONENTS, userId);
5043                if (DEBUG_PREFERRED || debug) {
5044                    Slog.v(TAG, "Found persistent preferred activity:");
5045                    if (ai != null) {
5046                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5047                    } else {
5048                        Slog.v(TAG, "  null");
5049                    }
5050                }
5051                if (ai == null) {
5052                    // This previously registered persistent preferred activity
5053                    // component is no longer known. Ignore it and do NOT remove it.
5054                    continue;
5055                }
5056                for (int j=0; j<N; j++) {
5057                    final ResolveInfo ri = query.get(j);
5058                    if (!ri.activityInfo.applicationInfo.packageName
5059                            .equals(ai.applicationInfo.packageName)) {
5060                        continue;
5061                    }
5062                    if (!ri.activityInfo.name.equals(ai.name)) {
5063                        continue;
5064                    }
5065                    //  Found a persistent preference that can handle the intent.
5066                    if (DEBUG_PREFERRED || debug) {
5067                        Slog.v(TAG, "Returning persistent preferred activity: " +
5068                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5069                    }
5070                    return ri;
5071                }
5072            }
5073        }
5074        return null;
5075    }
5076
5077    // TODO: handle preferred activities missing while user has amnesia
5078    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5079            List<ResolveInfo> query, int priority, boolean always,
5080            boolean removeMatches, boolean debug, int userId) {
5081        if (!sUserManager.exists(userId)) return null;
5082        flags = updateFlagsForResolve(flags, userId, intent);
5083        // writer
5084        synchronized (mPackages) {
5085            if (intent.getSelector() != null) {
5086                intent = intent.getSelector();
5087            }
5088            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5089
5090            // Try to find a matching persistent preferred activity.
5091            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5092                    debug, userId);
5093
5094            // If a persistent preferred activity matched, use it.
5095            if (pri != null) {
5096                return pri;
5097            }
5098
5099            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5100            // Get the list of preferred activities that handle the intent
5101            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5102            List<PreferredActivity> prefs = pir != null
5103                    ? pir.queryIntent(intent, resolvedType,
5104                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5105                    : null;
5106            if (prefs != null && prefs.size() > 0) {
5107                boolean changed = false;
5108                try {
5109                    // First figure out how good the original match set is.
5110                    // We will only allow preferred activities that came
5111                    // from the same match quality.
5112                    int match = 0;
5113
5114                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5115
5116                    final int N = query.size();
5117                    for (int j=0; j<N; j++) {
5118                        final ResolveInfo ri = query.get(j);
5119                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5120                                + ": 0x" + Integer.toHexString(match));
5121                        if (ri.match > match) {
5122                            match = ri.match;
5123                        }
5124                    }
5125
5126                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5127                            + Integer.toHexString(match));
5128
5129                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5130                    final int M = prefs.size();
5131                    for (int i=0; i<M; i++) {
5132                        final PreferredActivity pa = prefs.get(i);
5133                        if (DEBUG_PREFERRED || debug) {
5134                            Slog.v(TAG, "Checking PreferredActivity ds="
5135                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5136                                    + "\n  component=" + pa.mPref.mComponent);
5137                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5138                        }
5139                        if (pa.mPref.mMatch != match) {
5140                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5141                                    + Integer.toHexString(pa.mPref.mMatch));
5142                            continue;
5143                        }
5144                        // If it's not an "always" type preferred activity and that's what we're
5145                        // looking for, skip it.
5146                        if (always && !pa.mPref.mAlways) {
5147                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5148                            continue;
5149                        }
5150                        final ActivityInfo ai = getActivityInfo(
5151                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5152                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5153                                userId);
5154                        if (DEBUG_PREFERRED || debug) {
5155                            Slog.v(TAG, "Found preferred activity:");
5156                            if (ai != null) {
5157                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5158                            } else {
5159                                Slog.v(TAG, "  null");
5160                            }
5161                        }
5162                        if (ai == null) {
5163                            // This previously registered preferred activity
5164                            // component is no longer known.  Most likely an update
5165                            // to the app was installed and in the new version this
5166                            // component no longer exists.  Clean it up by removing
5167                            // it from the preferred activities list, and skip it.
5168                            Slog.w(TAG, "Removing dangling preferred activity: "
5169                                    + pa.mPref.mComponent);
5170                            pir.removeFilter(pa);
5171                            changed = true;
5172                            continue;
5173                        }
5174                        for (int j=0; j<N; j++) {
5175                            final ResolveInfo ri = query.get(j);
5176                            if (!ri.activityInfo.applicationInfo.packageName
5177                                    .equals(ai.applicationInfo.packageName)) {
5178                                continue;
5179                            }
5180                            if (!ri.activityInfo.name.equals(ai.name)) {
5181                                continue;
5182                            }
5183
5184                            if (removeMatches) {
5185                                pir.removeFilter(pa);
5186                                changed = true;
5187                                if (DEBUG_PREFERRED) {
5188                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5189                                }
5190                                break;
5191                            }
5192
5193                            // Okay we found a previously set preferred or last chosen app.
5194                            // If the result set is different from when this
5195                            // was created, we need to clear it and re-ask the
5196                            // user their preference, if we're looking for an "always" type entry.
5197                            if (always && !pa.mPref.sameSet(query)) {
5198                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5199                                        + intent + " type " + resolvedType);
5200                                if (DEBUG_PREFERRED) {
5201                                    Slog.v(TAG, "Removing preferred activity since set changed "
5202                                            + pa.mPref.mComponent);
5203                                }
5204                                pir.removeFilter(pa);
5205                                // Re-add the filter as a "last chosen" entry (!always)
5206                                PreferredActivity lastChosen = new PreferredActivity(
5207                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5208                                pir.addFilter(lastChosen);
5209                                changed = true;
5210                                return null;
5211                            }
5212
5213                            // Yay! Either the set matched or we're looking for the last chosen
5214                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5215                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5216                            return ri;
5217                        }
5218                    }
5219                } finally {
5220                    if (changed) {
5221                        if (DEBUG_PREFERRED) {
5222                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5223                        }
5224                        scheduleWritePackageRestrictionsLocked(userId);
5225                    }
5226                }
5227            }
5228        }
5229        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5230        return null;
5231    }
5232
5233    /*
5234     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5235     */
5236    @Override
5237    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5238            int targetUserId) {
5239        mContext.enforceCallingOrSelfPermission(
5240                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5241        List<CrossProfileIntentFilter> matches =
5242                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5243        if (matches != null) {
5244            int size = matches.size();
5245            for (int i = 0; i < size; i++) {
5246                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5247            }
5248        }
5249        if (hasWebURI(intent)) {
5250            // cross-profile app linking works only towards the parent.
5251            final UserInfo parent = getProfileParent(sourceUserId);
5252            synchronized(mPackages) {
5253                int flags = updateFlagsForResolve(0, parent.id, intent);
5254                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5255                        intent, resolvedType, flags, sourceUserId, parent.id);
5256                return xpDomainInfo != null;
5257            }
5258        }
5259        return false;
5260    }
5261
5262    private UserInfo getProfileParent(int userId) {
5263        final long identity = Binder.clearCallingIdentity();
5264        try {
5265            return sUserManager.getProfileParent(userId);
5266        } finally {
5267            Binder.restoreCallingIdentity(identity);
5268        }
5269    }
5270
5271    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5272            String resolvedType, int userId) {
5273        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5274        if (resolver != null) {
5275            return resolver.queryIntent(intent, resolvedType, false, userId);
5276        }
5277        return null;
5278    }
5279
5280    @Override
5281    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5282            String resolvedType, int flags, int userId) {
5283        try {
5284            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5285
5286            return new ParceledListSlice<>(
5287                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5288        } finally {
5289            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5290        }
5291    }
5292
5293    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5294            String resolvedType, int flags, int userId) {
5295        if (!sUserManager.exists(userId)) return Collections.emptyList();
5296        flags = updateFlagsForResolve(flags, userId, intent);
5297        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5298                false /* requireFullPermission */, false /* checkShell */,
5299                "query intent activities");
5300        ComponentName comp = intent.getComponent();
5301        if (comp == null) {
5302            if (intent.getSelector() != null) {
5303                intent = intent.getSelector();
5304                comp = intent.getComponent();
5305            }
5306        }
5307
5308        if (comp != null) {
5309            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5310            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5311            if (ai != null) {
5312                final ResolveInfo ri = new ResolveInfo();
5313                ri.activityInfo = ai;
5314                list.add(ri);
5315            }
5316            return list;
5317        }
5318
5319        // reader
5320        boolean sortResult = false;
5321        boolean addEphemeral = false;
5322        boolean matchEphemeralPackage = false;
5323        List<ResolveInfo> result;
5324        final String pkgName = intent.getPackage();
5325        synchronized (mPackages) {
5326            if (pkgName == null) {
5327                List<CrossProfileIntentFilter> matchingFilters =
5328                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5329                // Check for results that need to skip the current profile.
5330                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5331                        resolvedType, flags, userId);
5332                if (xpResolveInfo != null) {
5333                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5334                    xpResult.add(xpResolveInfo);
5335                    return filterIfNotSystemUser(xpResult, userId);
5336                }
5337
5338                // Check for results in the current profile.
5339                result = filterIfNotSystemUser(mActivities.queryIntent(
5340                        intent, resolvedType, flags, userId), userId);
5341                addEphemeral =
5342                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5343
5344                // Check for cross profile results.
5345                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5346                xpResolveInfo = queryCrossProfileIntents(
5347                        matchingFilters, intent, resolvedType, flags, userId,
5348                        hasNonNegativePriorityResult);
5349                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5350                    boolean isVisibleToUser = filterIfNotSystemUser(
5351                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5352                    if (isVisibleToUser) {
5353                        result.add(xpResolveInfo);
5354                        sortResult = true;
5355                    }
5356                }
5357                if (hasWebURI(intent)) {
5358                    CrossProfileDomainInfo xpDomainInfo = null;
5359                    final UserInfo parent = getProfileParent(userId);
5360                    if (parent != null) {
5361                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5362                                flags, userId, parent.id);
5363                    }
5364                    if (xpDomainInfo != null) {
5365                        if (xpResolveInfo != null) {
5366                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5367                            // in the result.
5368                            result.remove(xpResolveInfo);
5369                        }
5370                        if (result.size() == 0 && !addEphemeral) {
5371                            result.add(xpDomainInfo.resolveInfo);
5372                            return result;
5373                        }
5374                    }
5375                    if (result.size() > 1 || addEphemeral) {
5376                        result = filterCandidatesWithDomainPreferredActivitiesLPr(
5377                                intent, flags, result, xpDomainInfo, userId);
5378                        sortResult = true;
5379                    }
5380                }
5381            } else {
5382                final PackageParser.Package pkg = mPackages.get(pkgName);
5383                if (pkg != null) {
5384                    result = filterIfNotSystemUser(
5385                            mActivities.queryIntentForPackage(
5386                                    intent, resolvedType, flags, pkg.activities, userId),
5387                            userId);
5388                } else {
5389                    // the caller wants to resolve for a particular package; however, there
5390                    // were no installed results, so, try to find an ephemeral result
5391                    addEphemeral = isEphemeralAllowed(
5392                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5393                    matchEphemeralPackage = true;
5394                    result = new ArrayList<ResolveInfo>();
5395                }
5396            }
5397        }
5398        if (addEphemeral) {
5399            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5400            final EphemeralResolveInfo ai = getEphemeralResolveInfo(
5401                    mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5402                    matchEphemeralPackage ? pkgName : null);
5403            if (ai != null) {
5404                if (DEBUG_EPHEMERAL) {
5405                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5406                }
5407                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5408                ephemeralInstaller.ephemeralResolveInfo = ai;
5409                // make sure this resolver is the default
5410                ephemeralInstaller.isDefault = true;
5411                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5412                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5413                // add a non-generic filter
5414                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5415                ephemeralInstaller.filter.addDataPath(
5416                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5417                result.add(ephemeralInstaller);
5418            }
5419            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5420        }
5421        if (sortResult) {
5422            Collections.sort(result, mResolvePrioritySorter);
5423        }
5424        return result;
5425    }
5426
5427    private static class CrossProfileDomainInfo {
5428        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5429        ResolveInfo resolveInfo;
5430        /* Best domain verification status of the activities found in the other profile */
5431        int bestDomainVerificationStatus;
5432    }
5433
5434    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5435            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5436        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5437                sourceUserId)) {
5438            return null;
5439        }
5440        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5441                resolvedType, flags, parentUserId);
5442
5443        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5444            return null;
5445        }
5446        CrossProfileDomainInfo result = null;
5447        int size = resultTargetUser.size();
5448        for (int i = 0; i < size; i++) {
5449            ResolveInfo riTargetUser = resultTargetUser.get(i);
5450            // Intent filter verification is only for filters that specify a host. So don't return
5451            // those that handle all web uris.
5452            if (riTargetUser.handleAllWebDataURI) {
5453                continue;
5454            }
5455            String packageName = riTargetUser.activityInfo.packageName;
5456            PackageSetting ps = mSettings.mPackages.get(packageName);
5457            if (ps == null) {
5458                continue;
5459            }
5460            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5461            int status = (int)(verificationState >> 32);
5462            if (result == null) {
5463                result = new CrossProfileDomainInfo();
5464                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5465                        sourceUserId, parentUserId);
5466                result.bestDomainVerificationStatus = status;
5467            } else {
5468                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5469                        result.bestDomainVerificationStatus);
5470            }
5471        }
5472        // Don't consider matches with status NEVER across profiles.
5473        if (result != null && result.bestDomainVerificationStatus
5474                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5475            return null;
5476        }
5477        return result;
5478    }
5479
5480    /**
5481     * Verification statuses are ordered from the worse to the best, except for
5482     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5483     */
5484    private int bestDomainVerificationStatus(int status1, int status2) {
5485        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5486            return status2;
5487        }
5488        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5489            return status1;
5490        }
5491        return (int) MathUtils.max(status1, status2);
5492    }
5493
5494    private boolean isUserEnabled(int userId) {
5495        long callingId = Binder.clearCallingIdentity();
5496        try {
5497            UserInfo userInfo = sUserManager.getUserInfo(userId);
5498            return userInfo != null && userInfo.isEnabled();
5499        } finally {
5500            Binder.restoreCallingIdentity(callingId);
5501        }
5502    }
5503
5504    /**
5505     * Filter out activities with systemUserOnly flag set, when current user is not System.
5506     *
5507     * @return filtered list
5508     */
5509    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5510        if (userId == UserHandle.USER_SYSTEM) {
5511            return resolveInfos;
5512        }
5513        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5514            ResolveInfo info = resolveInfos.get(i);
5515            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5516                resolveInfos.remove(i);
5517            }
5518        }
5519        return resolveInfos;
5520    }
5521
5522    /**
5523     * @param resolveInfos list of resolve infos in descending priority order
5524     * @return if the list contains a resolve info with non-negative priority
5525     */
5526    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5527        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5528    }
5529
5530    private static boolean hasWebURI(Intent intent) {
5531        if (intent.getData() == null) {
5532            return false;
5533        }
5534        final String scheme = intent.getScheme();
5535        if (TextUtils.isEmpty(scheme)) {
5536            return false;
5537        }
5538        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5539    }
5540
5541    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5542            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5543            int userId) {
5544        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5545
5546        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5547            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5548                    candidates.size());
5549        }
5550
5551        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5552        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5553        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5554        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5555        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5556        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5557
5558        synchronized (mPackages) {
5559            final int count = candidates.size();
5560            // First, try to use linked apps. Partition the candidates into four lists:
5561            // one for the final results, one for the "do not use ever", one for "undefined status"
5562            // and finally one for "browser app type".
5563            for (int n=0; n<count; n++) {
5564                ResolveInfo info = candidates.get(n);
5565                String packageName = info.activityInfo.packageName;
5566                PackageSetting ps = mSettings.mPackages.get(packageName);
5567                if (ps != null) {
5568                    // Add to the special match all list (Browser use case)
5569                    if (info.handleAllWebDataURI) {
5570                        matchAllList.add(info);
5571                        continue;
5572                    }
5573                    // Try to get the status from User settings first
5574                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5575                    int status = (int)(packedStatus >> 32);
5576                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5577                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5578                        if (DEBUG_DOMAIN_VERIFICATION) {
5579                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5580                                    + " : linkgen=" + linkGeneration);
5581                        }
5582                        // Use link-enabled generation as preferredOrder, i.e.
5583                        // prefer newly-enabled over earlier-enabled.
5584                        info.preferredOrder = linkGeneration;
5585                        alwaysList.add(info);
5586                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5587                        if (DEBUG_DOMAIN_VERIFICATION) {
5588                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5589                        }
5590                        neverList.add(info);
5591                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5592                        if (DEBUG_DOMAIN_VERIFICATION) {
5593                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5594                        }
5595                        alwaysAskList.add(info);
5596                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5597                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5598                        if (DEBUG_DOMAIN_VERIFICATION) {
5599                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5600                        }
5601                        undefinedList.add(info);
5602                    }
5603                }
5604            }
5605
5606            // We'll want to include browser possibilities in a few cases
5607            boolean includeBrowser = false;
5608
5609            // First try to add the "always" resolution(s) for the current user, if any
5610            if (alwaysList.size() > 0) {
5611                result.addAll(alwaysList);
5612            } else {
5613                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5614                result.addAll(undefinedList);
5615                // Maybe add one for the other profile.
5616                if (xpDomainInfo != null && (
5617                        xpDomainInfo.bestDomainVerificationStatus
5618                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5619                    result.add(xpDomainInfo.resolveInfo);
5620                }
5621                includeBrowser = true;
5622            }
5623
5624            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5625            // If there were 'always' entries their preferred order has been set, so we also
5626            // back that off to make the alternatives equivalent
5627            if (alwaysAskList.size() > 0) {
5628                for (ResolveInfo i : result) {
5629                    i.preferredOrder = 0;
5630                }
5631                result.addAll(alwaysAskList);
5632                includeBrowser = true;
5633            }
5634
5635            if (includeBrowser) {
5636                // Also add browsers (all of them or only the default one)
5637                if (DEBUG_DOMAIN_VERIFICATION) {
5638                    Slog.v(TAG, "   ...including browsers in candidate set");
5639                }
5640                if ((matchFlags & MATCH_ALL) != 0) {
5641                    result.addAll(matchAllList);
5642                } else {
5643                    // Browser/generic handling case.  If there's a default browser, go straight
5644                    // to that (but only if there is no other higher-priority match).
5645                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5646                    int maxMatchPrio = 0;
5647                    ResolveInfo defaultBrowserMatch = null;
5648                    final int numCandidates = matchAllList.size();
5649                    for (int n = 0; n < numCandidates; n++) {
5650                        ResolveInfo info = matchAllList.get(n);
5651                        // track the highest overall match priority...
5652                        if (info.priority > maxMatchPrio) {
5653                            maxMatchPrio = info.priority;
5654                        }
5655                        // ...and the highest-priority default browser match
5656                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5657                            if (defaultBrowserMatch == null
5658                                    || (defaultBrowserMatch.priority < info.priority)) {
5659                                if (debug) {
5660                                    Slog.v(TAG, "Considering default browser match " + info);
5661                                }
5662                                defaultBrowserMatch = info;
5663                            }
5664                        }
5665                    }
5666                    if (defaultBrowserMatch != null
5667                            && defaultBrowserMatch.priority >= maxMatchPrio
5668                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5669                    {
5670                        if (debug) {
5671                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5672                        }
5673                        result.add(defaultBrowserMatch);
5674                    } else {
5675                        result.addAll(matchAllList);
5676                    }
5677                }
5678
5679                // If there is nothing selected, add all candidates and remove the ones that the user
5680                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5681                if (result.size() == 0) {
5682                    result.addAll(candidates);
5683                    result.removeAll(neverList);
5684                }
5685            }
5686        }
5687        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5688            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5689                    result.size());
5690            for (ResolveInfo info : result) {
5691                Slog.v(TAG, "  + " + info.activityInfo);
5692            }
5693        }
5694        return result;
5695    }
5696
5697    // Returns a packed value as a long:
5698    //
5699    // high 'int'-sized word: link status: undefined/ask/never/always.
5700    // low 'int'-sized word: relative priority among 'always' results.
5701    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5702        long result = ps.getDomainVerificationStatusForUser(userId);
5703        // if none available, get the master status
5704        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5705            if (ps.getIntentFilterVerificationInfo() != null) {
5706                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5707            }
5708        }
5709        return result;
5710    }
5711
5712    private ResolveInfo querySkipCurrentProfileIntents(
5713            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5714            int flags, int sourceUserId) {
5715        if (matchingFilters != null) {
5716            int size = matchingFilters.size();
5717            for (int i = 0; i < size; i ++) {
5718                CrossProfileIntentFilter filter = matchingFilters.get(i);
5719                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5720                    // Checking if there are activities in the target user that can handle the
5721                    // intent.
5722                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5723                            resolvedType, flags, sourceUserId);
5724                    if (resolveInfo != null) {
5725                        return resolveInfo;
5726                    }
5727                }
5728            }
5729        }
5730        return null;
5731    }
5732
5733    // Return matching ResolveInfo in target user if any.
5734    private ResolveInfo queryCrossProfileIntents(
5735            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5736            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5737        if (matchingFilters != null) {
5738            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5739            // match the same intent. For performance reasons, it is better not to
5740            // run queryIntent twice for the same userId
5741            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5742            int size = matchingFilters.size();
5743            for (int i = 0; i < size; i++) {
5744                CrossProfileIntentFilter filter = matchingFilters.get(i);
5745                int targetUserId = filter.getTargetUserId();
5746                boolean skipCurrentProfile =
5747                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5748                boolean skipCurrentProfileIfNoMatchFound =
5749                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5750                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5751                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5752                    // Checking if there are activities in the target user that can handle the
5753                    // intent.
5754                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5755                            resolvedType, flags, sourceUserId);
5756                    if (resolveInfo != null) return resolveInfo;
5757                    alreadyTriedUserIds.put(targetUserId, true);
5758                }
5759            }
5760        }
5761        return null;
5762    }
5763
5764    /**
5765     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5766     * will forward the intent to the filter's target user.
5767     * Otherwise, returns null.
5768     */
5769    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5770            String resolvedType, int flags, int sourceUserId) {
5771        int targetUserId = filter.getTargetUserId();
5772        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5773                resolvedType, flags, targetUserId);
5774        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5775            // If all the matches in the target profile are suspended, return null.
5776            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5777                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5778                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5779                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5780                            targetUserId);
5781                }
5782            }
5783        }
5784        return null;
5785    }
5786
5787    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5788            int sourceUserId, int targetUserId) {
5789        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5790        long ident = Binder.clearCallingIdentity();
5791        boolean targetIsProfile;
5792        try {
5793            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5794        } finally {
5795            Binder.restoreCallingIdentity(ident);
5796        }
5797        String className;
5798        if (targetIsProfile) {
5799            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5800        } else {
5801            className = FORWARD_INTENT_TO_PARENT;
5802        }
5803        ComponentName forwardingActivityComponentName = new ComponentName(
5804                mAndroidApplication.packageName, className);
5805        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5806                sourceUserId);
5807        if (!targetIsProfile) {
5808            forwardingActivityInfo.showUserIcon = targetUserId;
5809            forwardingResolveInfo.noResourceId = true;
5810        }
5811        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5812        forwardingResolveInfo.priority = 0;
5813        forwardingResolveInfo.preferredOrder = 0;
5814        forwardingResolveInfo.match = 0;
5815        forwardingResolveInfo.isDefault = true;
5816        forwardingResolveInfo.filter = filter;
5817        forwardingResolveInfo.targetUserId = targetUserId;
5818        return forwardingResolveInfo;
5819    }
5820
5821    @Override
5822    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5823            Intent[] specifics, String[] specificTypes, Intent intent,
5824            String resolvedType, int flags, int userId) {
5825        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5826                specificTypes, intent, resolvedType, flags, userId));
5827    }
5828
5829    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5830            Intent[] specifics, String[] specificTypes, Intent intent,
5831            String resolvedType, int flags, int userId) {
5832        if (!sUserManager.exists(userId)) return Collections.emptyList();
5833        flags = updateFlagsForResolve(flags, userId, intent);
5834        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5835                false /* requireFullPermission */, false /* checkShell */,
5836                "query intent activity options");
5837        final String resultsAction = intent.getAction();
5838
5839        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5840                | PackageManager.GET_RESOLVED_FILTER, userId);
5841
5842        if (DEBUG_INTENT_MATCHING) {
5843            Log.v(TAG, "Query " + intent + ": " + results);
5844        }
5845
5846        int specificsPos = 0;
5847        int N;
5848
5849        // todo: note that the algorithm used here is O(N^2).  This
5850        // isn't a problem in our current environment, but if we start running
5851        // into situations where we have more than 5 or 10 matches then this
5852        // should probably be changed to something smarter...
5853
5854        // First we go through and resolve each of the specific items
5855        // that were supplied, taking care of removing any corresponding
5856        // duplicate items in the generic resolve list.
5857        if (specifics != null) {
5858            for (int i=0; i<specifics.length; i++) {
5859                final Intent sintent = specifics[i];
5860                if (sintent == null) {
5861                    continue;
5862                }
5863
5864                if (DEBUG_INTENT_MATCHING) {
5865                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5866                }
5867
5868                String action = sintent.getAction();
5869                if (resultsAction != null && resultsAction.equals(action)) {
5870                    // If this action was explicitly requested, then don't
5871                    // remove things that have it.
5872                    action = null;
5873                }
5874
5875                ResolveInfo ri = null;
5876                ActivityInfo ai = null;
5877
5878                ComponentName comp = sintent.getComponent();
5879                if (comp == null) {
5880                    ri = resolveIntent(
5881                        sintent,
5882                        specificTypes != null ? specificTypes[i] : null,
5883                            flags, userId);
5884                    if (ri == null) {
5885                        continue;
5886                    }
5887                    if (ri == mResolveInfo) {
5888                        // ACK!  Must do something better with this.
5889                    }
5890                    ai = ri.activityInfo;
5891                    comp = new ComponentName(ai.applicationInfo.packageName,
5892                            ai.name);
5893                } else {
5894                    ai = getActivityInfo(comp, flags, userId);
5895                    if (ai == null) {
5896                        continue;
5897                    }
5898                }
5899
5900                // Look for any generic query activities that are duplicates
5901                // of this specific one, and remove them from the results.
5902                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5903                N = results.size();
5904                int j;
5905                for (j=specificsPos; j<N; j++) {
5906                    ResolveInfo sri = results.get(j);
5907                    if ((sri.activityInfo.name.equals(comp.getClassName())
5908                            && sri.activityInfo.applicationInfo.packageName.equals(
5909                                    comp.getPackageName()))
5910                        || (action != null && sri.filter.matchAction(action))) {
5911                        results.remove(j);
5912                        if (DEBUG_INTENT_MATCHING) Log.v(
5913                            TAG, "Removing duplicate item from " + j
5914                            + " due to specific " + specificsPos);
5915                        if (ri == null) {
5916                            ri = sri;
5917                        }
5918                        j--;
5919                        N--;
5920                    }
5921                }
5922
5923                // Add this specific item to its proper place.
5924                if (ri == null) {
5925                    ri = new ResolveInfo();
5926                    ri.activityInfo = ai;
5927                }
5928                results.add(specificsPos, ri);
5929                ri.specificIndex = i;
5930                specificsPos++;
5931            }
5932        }
5933
5934        // Now we go through the remaining generic results and remove any
5935        // duplicate actions that are found here.
5936        N = results.size();
5937        for (int i=specificsPos; i<N-1; i++) {
5938            final ResolveInfo rii = results.get(i);
5939            if (rii.filter == null) {
5940                continue;
5941            }
5942
5943            // Iterate over all of the actions of this result's intent
5944            // filter...  typically this should be just one.
5945            final Iterator<String> it = rii.filter.actionsIterator();
5946            if (it == null) {
5947                continue;
5948            }
5949            while (it.hasNext()) {
5950                final String action = it.next();
5951                if (resultsAction != null && resultsAction.equals(action)) {
5952                    // If this action was explicitly requested, then don't
5953                    // remove things that have it.
5954                    continue;
5955                }
5956                for (int j=i+1; j<N; j++) {
5957                    final ResolveInfo rij = results.get(j);
5958                    if (rij.filter != null && rij.filter.hasAction(action)) {
5959                        results.remove(j);
5960                        if (DEBUG_INTENT_MATCHING) Log.v(
5961                            TAG, "Removing duplicate item from " + j
5962                            + " due to action " + action + " at " + i);
5963                        j--;
5964                        N--;
5965                    }
5966                }
5967            }
5968
5969            // If the caller didn't request filter information, drop it now
5970            // so we don't have to marshall/unmarshall it.
5971            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5972                rii.filter = null;
5973            }
5974        }
5975
5976        // Filter out the caller activity if so requested.
5977        if (caller != null) {
5978            N = results.size();
5979            for (int i=0; i<N; i++) {
5980                ActivityInfo ainfo = results.get(i).activityInfo;
5981                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5982                        && caller.getClassName().equals(ainfo.name)) {
5983                    results.remove(i);
5984                    break;
5985                }
5986            }
5987        }
5988
5989        // If the caller didn't request filter information,
5990        // drop them now so we don't have to
5991        // marshall/unmarshall it.
5992        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5993            N = results.size();
5994            for (int i=0; i<N; i++) {
5995                results.get(i).filter = null;
5996            }
5997        }
5998
5999        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6000        return results;
6001    }
6002
6003    @Override
6004    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6005            String resolvedType, int flags, int userId) {
6006        return new ParceledListSlice<>(
6007                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6008    }
6009
6010    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6011            String resolvedType, int flags, int userId) {
6012        if (!sUserManager.exists(userId)) return Collections.emptyList();
6013        flags = updateFlagsForResolve(flags, userId, intent);
6014        ComponentName comp = intent.getComponent();
6015        if (comp == null) {
6016            if (intent.getSelector() != null) {
6017                intent = intent.getSelector();
6018                comp = intent.getComponent();
6019            }
6020        }
6021        if (comp != null) {
6022            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6023            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6024            if (ai != null) {
6025                ResolveInfo ri = new ResolveInfo();
6026                ri.activityInfo = ai;
6027                list.add(ri);
6028            }
6029            return list;
6030        }
6031
6032        // reader
6033        synchronized (mPackages) {
6034            String pkgName = intent.getPackage();
6035            if (pkgName == null) {
6036                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6037            }
6038            final PackageParser.Package pkg = mPackages.get(pkgName);
6039            if (pkg != null) {
6040                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6041                        userId);
6042            }
6043            return Collections.emptyList();
6044        }
6045    }
6046
6047    @Override
6048    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6049        if (!sUserManager.exists(userId)) return null;
6050        flags = updateFlagsForResolve(flags, userId, intent);
6051        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6052        if (query != null) {
6053            if (query.size() >= 1) {
6054                // If there is more than one service with the same priority,
6055                // just arbitrarily pick the first one.
6056                return query.get(0);
6057            }
6058        }
6059        return null;
6060    }
6061
6062    @Override
6063    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6064            String resolvedType, int flags, int userId) {
6065        return new ParceledListSlice<>(
6066                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6067    }
6068
6069    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6070            String resolvedType, int flags, int userId) {
6071        if (!sUserManager.exists(userId)) return Collections.emptyList();
6072        flags = updateFlagsForResolve(flags, userId, intent);
6073        ComponentName comp = intent.getComponent();
6074        if (comp == null) {
6075            if (intent.getSelector() != null) {
6076                intent = intent.getSelector();
6077                comp = intent.getComponent();
6078            }
6079        }
6080        if (comp != null) {
6081            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6082            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6083            if (si != null) {
6084                final ResolveInfo ri = new ResolveInfo();
6085                ri.serviceInfo = si;
6086                list.add(ri);
6087            }
6088            return list;
6089        }
6090
6091        // reader
6092        synchronized (mPackages) {
6093            String pkgName = intent.getPackage();
6094            if (pkgName == null) {
6095                return mServices.queryIntent(intent, resolvedType, flags, userId);
6096            }
6097            final PackageParser.Package pkg = mPackages.get(pkgName);
6098            if (pkg != null) {
6099                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6100                        userId);
6101            }
6102            return Collections.emptyList();
6103        }
6104    }
6105
6106    @Override
6107    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6108            String resolvedType, int flags, int userId) {
6109        return new ParceledListSlice<>(
6110                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6111    }
6112
6113    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6114            Intent intent, String resolvedType, int flags, int userId) {
6115        if (!sUserManager.exists(userId)) return Collections.emptyList();
6116        flags = updateFlagsForResolve(flags, userId, intent);
6117        ComponentName comp = intent.getComponent();
6118        if (comp == null) {
6119            if (intent.getSelector() != null) {
6120                intent = intent.getSelector();
6121                comp = intent.getComponent();
6122            }
6123        }
6124        if (comp != null) {
6125            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6126            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6127            if (pi != null) {
6128                final ResolveInfo ri = new ResolveInfo();
6129                ri.providerInfo = pi;
6130                list.add(ri);
6131            }
6132            return list;
6133        }
6134
6135        // reader
6136        synchronized (mPackages) {
6137            String pkgName = intent.getPackage();
6138            if (pkgName == null) {
6139                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6140            }
6141            final PackageParser.Package pkg = mPackages.get(pkgName);
6142            if (pkg != null) {
6143                return mProviders.queryIntentForPackage(
6144                        intent, resolvedType, flags, pkg.providers, userId);
6145            }
6146            return Collections.emptyList();
6147        }
6148    }
6149
6150    @Override
6151    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6152        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6153        flags = updateFlagsForPackage(flags, userId, null);
6154        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6155        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6156                true /* requireFullPermission */, false /* checkShell */,
6157                "get installed packages");
6158
6159        // writer
6160        synchronized (mPackages) {
6161            ArrayList<PackageInfo> list;
6162            if (listUninstalled) {
6163                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6164                for (PackageSetting ps : mSettings.mPackages.values()) {
6165                    final PackageInfo pi;
6166                    if (ps.pkg != null) {
6167                        pi = generatePackageInfo(ps, flags, userId);
6168                    } else {
6169                        pi = generatePackageInfo(ps, flags, userId);
6170                    }
6171                    if (pi != null) {
6172                        list.add(pi);
6173                    }
6174                }
6175            } else {
6176                list = new ArrayList<PackageInfo>(mPackages.size());
6177                for (PackageParser.Package p : mPackages.values()) {
6178                    final PackageInfo pi =
6179                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6180                    if (pi != null) {
6181                        list.add(pi);
6182                    }
6183                }
6184            }
6185
6186            return new ParceledListSlice<PackageInfo>(list);
6187        }
6188    }
6189
6190    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6191            String[] permissions, boolean[] tmp, int flags, int userId) {
6192        int numMatch = 0;
6193        final PermissionsState permissionsState = ps.getPermissionsState();
6194        for (int i=0; i<permissions.length; i++) {
6195            final String permission = permissions[i];
6196            if (permissionsState.hasPermission(permission, userId)) {
6197                tmp[i] = true;
6198                numMatch++;
6199            } else {
6200                tmp[i] = false;
6201            }
6202        }
6203        if (numMatch == 0) {
6204            return;
6205        }
6206        final PackageInfo pi;
6207        if (ps.pkg != null) {
6208            pi = generatePackageInfo(ps, flags, userId);
6209        } else {
6210            pi = generatePackageInfo(ps, flags, userId);
6211        }
6212        // The above might return null in cases of uninstalled apps or install-state
6213        // skew across users/profiles.
6214        if (pi != null) {
6215            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6216                if (numMatch == permissions.length) {
6217                    pi.requestedPermissions = permissions;
6218                } else {
6219                    pi.requestedPermissions = new String[numMatch];
6220                    numMatch = 0;
6221                    for (int i=0; i<permissions.length; i++) {
6222                        if (tmp[i]) {
6223                            pi.requestedPermissions[numMatch] = permissions[i];
6224                            numMatch++;
6225                        }
6226                    }
6227                }
6228            }
6229            list.add(pi);
6230        }
6231    }
6232
6233    @Override
6234    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6235            String[] permissions, int flags, int userId) {
6236        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6237        flags = updateFlagsForPackage(flags, userId, permissions);
6238        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6239
6240        // writer
6241        synchronized (mPackages) {
6242            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6243            boolean[] tmpBools = new boolean[permissions.length];
6244            if (listUninstalled) {
6245                for (PackageSetting ps : mSettings.mPackages.values()) {
6246                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6247                }
6248            } else {
6249                for (PackageParser.Package pkg : mPackages.values()) {
6250                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6251                    if (ps != null) {
6252                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6253                                userId);
6254                    }
6255                }
6256            }
6257
6258            return new ParceledListSlice<PackageInfo>(list);
6259        }
6260    }
6261
6262    @Override
6263    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6264        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6265        flags = updateFlagsForApplication(flags, userId, null);
6266        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6267
6268        // writer
6269        synchronized (mPackages) {
6270            ArrayList<ApplicationInfo> list;
6271            if (listUninstalled) {
6272                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6273                for (PackageSetting ps : mSettings.mPackages.values()) {
6274                    ApplicationInfo ai;
6275                    if (ps.pkg != null) {
6276                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6277                                ps.readUserState(userId), userId);
6278                    } else {
6279                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6280                    }
6281                    if (ai != null) {
6282                        list.add(ai);
6283                    }
6284                }
6285            } else {
6286                list = new ArrayList<ApplicationInfo>(mPackages.size());
6287                for (PackageParser.Package p : mPackages.values()) {
6288                    if (p.mExtras != null) {
6289                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6290                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6291                        if (ai != null) {
6292                            list.add(ai);
6293                        }
6294                    }
6295                }
6296            }
6297
6298            return new ParceledListSlice<ApplicationInfo>(list);
6299        }
6300    }
6301
6302    @Override
6303    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6304        if (isEphemeralDisabled()) {
6305            return null;
6306        }
6307
6308        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6309                "getEphemeralApplications");
6310        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6311                true /* requireFullPermission */, false /* checkShell */,
6312                "getEphemeralApplications");
6313        synchronized (mPackages) {
6314            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6315                    .getEphemeralApplicationsLPw(userId);
6316            if (ephemeralApps != null) {
6317                return new ParceledListSlice<>(ephemeralApps);
6318            }
6319        }
6320        return null;
6321    }
6322
6323    @Override
6324    public boolean isEphemeralApplication(String packageName, int userId) {
6325        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6326                true /* requireFullPermission */, false /* checkShell */,
6327                "isEphemeral");
6328        if (isEphemeralDisabled()) {
6329            return false;
6330        }
6331
6332        if (!isCallerSameApp(packageName)) {
6333            return false;
6334        }
6335        synchronized (mPackages) {
6336            PackageParser.Package pkg = mPackages.get(packageName);
6337            if (pkg != null) {
6338                return pkg.applicationInfo.isEphemeralApp();
6339            }
6340        }
6341        return false;
6342    }
6343
6344    @Override
6345    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6346        if (isEphemeralDisabled()) {
6347            return null;
6348        }
6349
6350        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6351                true /* requireFullPermission */, false /* checkShell */,
6352                "getCookie");
6353        if (!isCallerSameApp(packageName)) {
6354            return null;
6355        }
6356        synchronized (mPackages) {
6357            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6358                    packageName, userId);
6359        }
6360    }
6361
6362    @Override
6363    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6364        if (isEphemeralDisabled()) {
6365            return true;
6366        }
6367
6368        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6369                true /* requireFullPermission */, true /* checkShell */,
6370                "setCookie");
6371        if (!isCallerSameApp(packageName)) {
6372            return false;
6373        }
6374        synchronized (mPackages) {
6375            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6376                    packageName, cookie, userId);
6377        }
6378    }
6379
6380    @Override
6381    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6382        if (isEphemeralDisabled()) {
6383            return null;
6384        }
6385
6386        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6387                "getEphemeralApplicationIcon");
6388        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6389                true /* requireFullPermission */, false /* checkShell */,
6390                "getEphemeralApplicationIcon");
6391        synchronized (mPackages) {
6392            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6393                    packageName, userId);
6394        }
6395    }
6396
6397    private boolean isCallerSameApp(String packageName) {
6398        PackageParser.Package pkg = mPackages.get(packageName);
6399        return pkg != null
6400                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6401    }
6402
6403    @Override
6404    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6405        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6406    }
6407
6408    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6409        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6410
6411        // reader
6412        synchronized (mPackages) {
6413            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6414            final int userId = UserHandle.getCallingUserId();
6415            while (i.hasNext()) {
6416                final PackageParser.Package p = i.next();
6417                if (p.applicationInfo == null) continue;
6418
6419                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6420                        && !p.applicationInfo.isDirectBootAware();
6421                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6422                        && p.applicationInfo.isDirectBootAware();
6423
6424                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6425                        && (!mSafeMode || isSystemApp(p))
6426                        && (matchesUnaware || matchesAware)) {
6427                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6428                    if (ps != null) {
6429                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6430                                ps.readUserState(userId), userId);
6431                        if (ai != null) {
6432                            finalList.add(ai);
6433                        }
6434                    }
6435                }
6436            }
6437        }
6438
6439        return finalList;
6440    }
6441
6442    @Override
6443    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6444        if (!sUserManager.exists(userId)) return null;
6445        flags = updateFlagsForComponent(flags, userId, name);
6446        // reader
6447        synchronized (mPackages) {
6448            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6449            PackageSetting ps = provider != null
6450                    ? mSettings.mPackages.get(provider.owner.packageName)
6451                    : null;
6452            return ps != null
6453                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6454                    ? PackageParser.generateProviderInfo(provider, flags,
6455                            ps.readUserState(userId), userId)
6456                    : null;
6457        }
6458    }
6459
6460    /**
6461     * @deprecated
6462     */
6463    @Deprecated
6464    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6465        // reader
6466        synchronized (mPackages) {
6467            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6468                    .entrySet().iterator();
6469            final int userId = UserHandle.getCallingUserId();
6470            while (i.hasNext()) {
6471                Map.Entry<String, PackageParser.Provider> entry = i.next();
6472                PackageParser.Provider p = entry.getValue();
6473                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6474
6475                if (ps != null && p.syncable
6476                        && (!mSafeMode || (p.info.applicationInfo.flags
6477                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6478                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6479                            ps.readUserState(userId), userId);
6480                    if (info != null) {
6481                        outNames.add(entry.getKey());
6482                        outInfo.add(info);
6483                    }
6484                }
6485            }
6486        }
6487    }
6488
6489    @Override
6490    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6491            int uid, int flags) {
6492        final int userId = processName != null ? UserHandle.getUserId(uid)
6493                : UserHandle.getCallingUserId();
6494        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6495        flags = updateFlagsForComponent(flags, userId, processName);
6496
6497        ArrayList<ProviderInfo> finalList = null;
6498        // reader
6499        synchronized (mPackages) {
6500            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6501            while (i.hasNext()) {
6502                final PackageParser.Provider p = i.next();
6503                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6504                if (ps != null && p.info.authority != null
6505                        && (processName == null
6506                                || (p.info.processName.equals(processName)
6507                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6508                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6509                    if (finalList == null) {
6510                        finalList = new ArrayList<ProviderInfo>(3);
6511                    }
6512                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6513                            ps.readUserState(userId), userId);
6514                    if (info != null) {
6515                        finalList.add(info);
6516                    }
6517                }
6518            }
6519        }
6520
6521        if (finalList != null) {
6522            Collections.sort(finalList, mProviderInitOrderSorter);
6523            return new ParceledListSlice<ProviderInfo>(finalList);
6524        }
6525
6526        return ParceledListSlice.emptyList();
6527    }
6528
6529    @Override
6530    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6531        // reader
6532        synchronized (mPackages) {
6533            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6534            return PackageParser.generateInstrumentationInfo(i, flags);
6535        }
6536    }
6537
6538    @Override
6539    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6540            String targetPackage, int flags) {
6541        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6542    }
6543
6544    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6545            int flags) {
6546        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6547
6548        // reader
6549        synchronized (mPackages) {
6550            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6551            while (i.hasNext()) {
6552                final PackageParser.Instrumentation p = i.next();
6553                if (targetPackage == null
6554                        || targetPackage.equals(p.info.targetPackage)) {
6555                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6556                            flags);
6557                    if (ii != null) {
6558                        finalList.add(ii);
6559                    }
6560                }
6561            }
6562        }
6563
6564        return finalList;
6565    }
6566
6567    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6568        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6569        if (overlays == null) {
6570            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6571            return;
6572        }
6573        for (PackageParser.Package opkg : overlays.values()) {
6574            // Not much to do if idmap fails: we already logged the error
6575            // and we certainly don't want to abort installation of pkg simply
6576            // because an overlay didn't fit properly. For these reasons,
6577            // ignore the return value of createIdmapForPackagePairLI.
6578            createIdmapForPackagePairLI(pkg, opkg);
6579        }
6580    }
6581
6582    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6583            PackageParser.Package opkg) {
6584        if (!opkg.mTrustedOverlay) {
6585            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6586                    opkg.baseCodePath + ": overlay not trusted");
6587            return false;
6588        }
6589        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6590        if (overlaySet == null) {
6591            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6592                    opkg.baseCodePath + " but target package has no known overlays");
6593            return false;
6594        }
6595        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6596        // TODO: generate idmap for split APKs
6597        try {
6598            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6599        } catch (InstallerException e) {
6600            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6601                    + opkg.baseCodePath);
6602            return false;
6603        }
6604        PackageParser.Package[] overlayArray =
6605            overlaySet.values().toArray(new PackageParser.Package[0]);
6606        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6607            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6608                return p1.mOverlayPriority - p2.mOverlayPriority;
6609            }
6610        };
6611        Arrays.sort(overlayArray, cmp);
6612
6613        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6614        int i = 0;
6615        for (PackageParser.Package p : overlayArray) {
6616            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6617        }
6618        return true;
6619    }
6620
6621    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6622        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
6623        try {
6624            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6625        } finally {
6626            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6627        }
6628    }
6629
6630    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6631        final File[] files = dir.listFiles();
6632        if (ArrayUtils.isEmpty(files)) {
6633            Log.d(TAG, "No files in app dir " + dir);
6634            return;
6635        }
6636
6637        if (DEBUG_PACKAGE_SCANNING) {
6638            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6639                    + " flags=0x" + Integer.toHexString(parseFlags));
6640        }
6641
6642        for (File file : files) {
6643            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6644                    && !PackageInstallerService.isStageName(file.getName());
6645            if (!isPackage) {
6646                // Ignore entries which are not packages
6647                continue;
6648            }
6649            try {
6650                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6651                        scanFlags, currentTime, null);
6652            } catch (PackageManagerException e) {
6653                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6654
6655                // Delete invalid userdata apps
6656                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6657                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6658                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6659                    removeCodePathLI(file);
6660                }
6661            }
6662        }
6663    }
6664
6665    private static File getSettingsProblemFile() {
6666        File dataDir = Environment.getDataDirectory();
6667        File systemDir = new File(dataDir, "system");
6668        File fname = new File(systemDir, "uiderrors.txt");
6669        return fname;
6670    }
6671
6672    static void reportSettingsProblem(int priority, String msg) {
6673        logCriticalInfo(priority, msg);
6674    }
6675
6676    static void logCriticalInfo(int priority, String msg) {
6677        Slog.println(priority, TAG, msg);
6678        EventLogTags.writePmCriticalInfo(msg);
6679        try {
6680            File fname = getSettingsProblemFile();
6681            FileOutputStream out = new FileOutputStream(fname, true);
6682            PrintWriter pw = new FastPrintWriter(out);
6683            SimpleDateFormat formatter = new SimpleDateFormat();
6684            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6685            pw.println(dateString + ": " + msg);
6686            pw.close();
6687            FileUtils.setPermissions(
6688                    fname.toString(),
6689                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6690                    -1, -1);
6691        } catch (java.io.IOException e) {
6692        }
6693    }
6694
6695    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6696        if (srcFile.isDirectory()) {
6697            final File baseFile = new File(pkg.baseCodePath);
6698            long maxModifiedTime = baseFile.lastModified();
6699            if (pkg.splitCodePaths != null) {
6700                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6701                    final File splitFile = new File(pkg.splitCodePaths[i]);
6702                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6703                }
6704            }
6705            return maxModifiedTime;
6706        }
6707        return srcFile.lastModified();
6708    }
6709
6710    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6711            final int policyFlags) throws PackageManagerException {
6712        // When upgrading from pre-N MR1, verify the package time stamp using the package
6713        // directory and not the APK file.
6714        final long lastModifiedTime = mIsPreNMR1Upgrade
6715                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6716        if (ps != null
6717                && ps.codePath.equals(srcFile)
6718                && ps.timeStamp == lastModifiedTime
6719                && !isCompatSignatureUpdateNeeded(pkg)
6720                && !isRecoverSignatureUpdateNeeded(pkg)) {
6721            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6722            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6723            ArraySet<PublicKey> signingKs;
6724            synchronized (mPackages) {
6725                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6726            }
6727            if (ps.signatures.mSignatures != null
6728                    && ps.signatures.mSignatures.length != 0
6729                    && signingKs != null) {
6730                // Optimization: reuse the existing cached certificates
6731                // if the package appears to be unchanged.
6732                pkg.mSignatures = ps.signatures.mSignatures;
6733                pkg.mSigningKeys = signingKs;
6734                return;
6735            }
6736
6737            Slog.w(TAG, "PackageSetting for " + ps.name
6738                    + " is missing signatures.  Collecting certs again to recover them.");
6739        } else {
6740            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6741        }
6742
6743        try {
6744            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
6745            PackageParser.collectCertificates(pkg, policyFlags);
6746        } catch (PackageParserException e) {
6747            throw PackageManagerException.from(e);
6748        } finally {
6749            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6750        }
6751    }
6752
6753    /**
6754     *  Traces a package scan.
6755     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6756     */
6757    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6758            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6759        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
6760        try {
6761            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6762        } finally {
6763            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6764        }
6765    }
6766
6767    /**
6768     *  Scans a package and returns the newly parsed package.
6769     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6770     */
6771    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6772            long currentTime, UserHandle user) throws PackageManagerException {
6773        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6774        PackageParser pp = new PackageParser();
6775        pp.setSeparateProcesses(mSeparateProcesses);
6776        pp.setOnlyCoreApps(mOnlyCore);
6777        pp.setDisplayMetrics(mMetrics);
6778
6779        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6780            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6781        }
6782
6783        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6784        final PackageParser.Package pkg;
6785        try {
6786            pkg = pp.parsePackage(scanFile, parseFlags);
6787        } catch (PackageParserException e) {
6788            throw PackageManagerException.from(e);
6789        } finally {
6790            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6791        }
6792
6793        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6794    }
6795
6796    /**
6797     *  Scans a package and returns the newly parsed package.
6798     *  @throws PackageManagerException on a parse error.
6799     */
6800    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6801            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6802            throws PackageManagerException {
6803        // If the package has children and this is the first dive in the function
6804        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6805        // packages (parent and children) would be successfully scanned before the
6806        // actual scan since scanning mutates internal state and we want to atomically
6807        // install the package and its children.
6808        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6809            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6810                scanFlags |= SCAN_CHECK_ONLY;
6811            }
6812        } else {
6813            scanFlags &= ~SCAN_CHECK_ONLY;
6814        }
6815
6816        // Scan the parent
6817        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6818                scanFlags, currentTime, user);
6819
6820        // Scan the children
6821        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6822        for (int i = 0; i < childCount; i++) {
6823            PackageParser.Package childPackage = pkg.childPackages.get(i);
6824            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6825                    currentTime, user);
6826        }
6827
6828
6829        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6830            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6831        }
6832
6833        return scannedPkg;
6834    }
6835
6836    /**
6837     *  Scans a package and returns the newly parsed package.
6838     *  @throws PackageManagerException on a parse error.
6839     */
6840    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6841            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6842            throws PackageManagerException {
6843        PackageSetting ps = null;
6844        PackageSetting updatedPkg;
6845        // reader
6846        synchronized (mPackages) {
6847            // Look to see if we already know about this package.
6848            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
6849            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6850                // This package has been renamed to its original name.  Let's
6851                // use that.
6852                ps = mSettings.peekPackageLPr(oldName);
6853            }
6854            // If there was no original package, see one for the real package name.
6855            if (ps == null) {
6856                ps = mSettings.peekPackageLPr(pkg.packageName);
6857            }
6858            // Check to see if this package could be hiding/updating a system
6859            // package.  Must look for it either under the original or real
6860            // package name depending on our state.
6861            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6862            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6863
6864            // If this is a package we don't know about on the system partition, we
6865            // may need to remove disabled child packages on the system partition
6866            // or may need to not add child packages if the parent apk is updated
6867            // on the data partition and no longer defines this child package.
6868            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6869                // If this is a parent package for an updated system app and this system
6870                // app got an OTA update which no longer defines some of the child packages
6871                // we have to prune them from the disabled system packages.
6872                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6873                if (disabledPs != null) {
6874                    final int scannedChildCount = (pkg.childPackages != null)
6875                            ? pkg.childPackages.size() : 0;
6876                    final int disabledChildCount = disabledPs.childPackageNames != null
6877                            ? disabledPs.childPackageNames.size() : 0;
6878                    for (int i = 0; i < disabledChildCount; i++) {
6879                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6880                        boolean disabledPackageAvailable = false;
6881                        for (int j = 0; j < scannedChildCount; j++) {
6882                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6883                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6884                                disabledPackageAvailable = true;
6885                                break;
6886                            }
6887                         }
6888                         if (!disabledPackageAvailable) {
6889                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6890                         }
6891                    }
6892                }
6893            }
6894        }
6895
6896        boolean updatedPkgBetter = false;
6897        // First check if this is a system package that may involve an update
6898        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6899            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6900            // it needs to drop FLAG_PRIVILEGED.
6901            if (locationIsPrivileged(scanFile)) {
6902                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6903            } else {
6904                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6905            }
6906
6907            if (ps != null && !ps.codePath.equals(scanFile)) {
6908                // The path has changed from what was last scanned...  check the
6909                // version of the new path against what we have stored to determine
6910                // what to do.
6911                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6912                if (pkg.mVersionCode <= ps.versionCode) {
6913                    // The system package has been updated and the code path does not match
6914                    // Ignore entry. Skip it.
6915                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6916                            + " ignored: updated version " + ps.versionCode
6917                            + " better than this " + pkg.mVersionCode);
6918                    if (!updatedPkg.codePath.equals(scanFile)) {
6919                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6920                                + ps.name + " changing from " + updatedPkg.codePathString
6921                                + " to " + scanFile);
6922                        updatedPkg.codePath = scanFile;
6923                        updatedPkg.codePathString = scanFile.toString();
6924                        updatedPkg.resourcePath = scanFile;
6925                        updatedPkg.resourcePathString = scanFile.toString();
6926                    }
6927                    updatedPkg.pkg = pkg;
6928                    updatedPkg.versionCode = pkg.mVersionCode;
6929
6930                    // Update the disabled system child packages to point to the package too.
6931                    final int childCount = updatedPkg.childPackageNames != null
6932                            ? updatedPkg.childPackageNames.size() : 0;
6933                    for (int i = 0; i < childCount; i++) {
6934                        String childPackageName = updatedPkg.childPackageNames.get(i);
6935                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6936                                childPackageName);
6937                        if (updatedChildPkg != null) {
6938                            updatedChildPkg.pkg = pkg;
6939                            updatedChildPkg.versionCode = pkg.mVersionCode;
6940                        }
6941                    }
6942
6943                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6944                            + scanFile + " ignored: updated version " + ps.versionCode
6945                            + " better than this " + pkg.mVersionCode);
6946                } else {
6947                    // The current app on the system partition is better than
6948                    // what we have updated to on the data partition; switch
6949                    // back to the system partition version.
6950                    // At this point, its safely assumed that package installation for
6951                    // apps in system partition will go through. If not there won't be a working
6952                    // version of the app
6953                    // writer
6954                    synchronized (mPackages) {
6955                        // Just remove the loaded entries from package lists.
6956                        mPackages.remove(ps.name);
6957                    }
6958
6959                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6960                            + " reverting from " + ps.codePathString
6961                            + ": new version " + pkg.mVersionCode
6962                            + " better than installed " + ps.versionCode);
6963
6964                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6965                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6966                    synchronized (mInstallLock) {
6967                        args.cleanUpResourcesLI();
6968                    }
6969                    synchronized (mPackages) {
6970                        mSettings.enableSystemPackageLPw(ps.name);
6971                    }
6972                    updatedPkgBetter = true;
6973                }
6974            }
6975        }
6976
6977        if (updatedPkg != null) {
6978            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6979            // initially
6980            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6981
6982            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6983            // flag set initially
6984            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6985                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6986            }
6987        }
6988
6989        // Verify certificates against what was last scanned
6990        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6991
6992        /*
6993         * A new system app appeared, but we already had a non-system one of the
6994         * same name installed earlier.
6995         */
6996        boolean shouldHideSystemApp = false;
6997        if (updatedPkg == null && ps != null
6998                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6999            /*
7000             * Check to make sure the signatures match first. If they don't,
7001             * wipe the installed application and its data.
7002             */
7003            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7004                    != PackageManager.SIGNATURE_MATCH) {
7005                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7006                        + " signatures don't match existing userdata copy; removing");
7007                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7008                        "scanPackageInternalLI")) {
7009                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7010                }
7011                ps = null;
7012            } else {
7013                /*
7014                 * If the newly-added system app is an older version than the
7015                 * already installed version, hide it. It will be scanned later
7016                 * and re-added like an update.
7017                 */
7018                if (pkg.mVersionCode <= ps.versionCode) {
7019                    shouldHideSystemApp = true;
7020                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7021                            + " but new version " + pkg.mVersionCode + " better than installed "
7022                            + ps.versionCode + "; hiding system");
7023                } else {
7024                    /*
7025                     * The newly found system app is a newer version that the
7026                     * one previously installed. Simply remove the
7027                     * already-installed application and replace it with our own
7028                     * while keeping the application data.
7029                     */
7030                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7031                            + " reverting from " + ps.codePathString + ": new version "
7032                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7033                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7034                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7035                    synchronized (mInstallLock) {
7036                        args.cleanUpResourcesLI();
7037                    }
7038                }
7039            }
7040        }
7041
7042        // The apk is forward locked (not public) if its code and resources
7043        // are kept in different files. (except for app in either system or
7044        // vendor path).
7045        // TODO grab this value from PackageSettings
7046        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7047            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7048                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7049            }
7050        }
7051
7052        // TODO: extend to support forward-locked splits
7053        String resourcePath = null;
7054        String baseResourcePath = null;
7055        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7056            if (ps != null && ps.resourcePathString != null) {
7057                resourcePath = ps.resourcePathString;
7058                baseResourcePath = ps.resourcePathString;
7059            } else {
7060                // Should not happen at all. Just log an error.
7061                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7062            }
7063        } else {
7064            resourcePath = pkg.codePath;
7065            baseResourcePath = pkg.baseCodePath;
7066        }
7067
7068        // Set application objects path explicitly.
7069        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7070        pkg.setApplicationInfoCodePath(pkg.codePath);
7071        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7072        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7073        pkg.setApplicationInfoResourcePath(resourcePath);
7074        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7075        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7076
7077        // Note that we invoke the following method only if we are about to unpack an application
7078        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7079                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7080
7081        /*
7082         * If the system app should be overridden by a previously installed
7083         * data, hide the system app now and let the /data/app scan pick it up
7084         * again.
7085         */
7086        if (shouldHideSystemApp) {
7087            synchronized (mPackages) {
7088                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7089            }
7090        }
7091
7092        return scannedPkg;
7093    }
7094
7095    private static String fixProcessName(String defProcessName,
7096            String processName, int uid) {
7097        if (processName == null) {
7098            return defProcessName;
7099        }
7100        return processName;
7101    }
7102
7103    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7104            throws PackageManagerException {
7105        if (pkgSetting.signatures.mSignatures != null) {
7106            // Already existing package. Make sure signatures match
7107            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7108                    == PackageManager.SIGNATURE_MATCH;
7109            if (!match) {
7110                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7111                        == PackageManager.SIGNATURE_MATCH;
7112            }
7113            if (!match) {
7114                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7115                        == PackageManager.SIGNATURE_MATCH;
7116            }
7117            if (!match) {
7118                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7119                        + pkg.packageName + " signatures do not match the "
7120                        + "previously installed version; ignoring!");
7121            }
7122        }
7123
7124        // Check for shared user signatures
7125        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7126            // Already existing package. Make sure signatures match
7127            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7128                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7129            if (!match) {
7130                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7131                        == PackageManager.SIGNATURE_MATCH;
7132            }
7133            if (!match) {
7134                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7135                        == PackageManager.SIGNATURE_MATCH;
7136            }
7137            if (!match) {
7138                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7139                        "Package " + pkg.packageName
7140                        + " has no signatures that match those in shared user "
7141                        + pkgSetting.sharedUser.name + "; ignoring!");
7142            }
7143        }
7144    }
7145
7146    /**
7147     * Enforces that only the system UID or root's UID can call a method exposed
7148     * via Binder.
7149     *
7150     * @param message used as message if SecurityException is thrown
7151     * @throws SecurityException if the caller is not system or root
7152     */
7153    private static final void enforceSystemOrRoot(String message) {
7154        final int uid = Binder.getCallingUid();
7155        if (uid != Process.SYSTEM_UID && uid != 0) {
7156            throw new SecurityException(message);
7157        }
7158    }
7159
7160    @Override
7161    public void performFstrimIfNeeded() {
7162        enforceSystemOrRoot("Only the system can request fstrim");
7163
7164        // Before everything else, see whether we need to fstrim.
7165        try {
7166            IMountService ms = PackageHelper.getMountService();
7167            if (ms != null) {
7168                boolean doTrim = false;
7169                final long interval = android.provider.Settings.Global.getLong(
7170                        mContext.getContentResolver(),
7171                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7172                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7173                if (interval > 0) {
7174                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7175                    if (timeSinceLast > interval) {
7176                        doTrim = true;
7177                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7178                                + "; running immediately");
7179                    }
7180                }
7181                if (doTrim) {
7182                    final boolean dexOptDialogShown;
7183                    synchronized (mPackages) {
7184                        dexOptDialogShown = mDexOptDialogShown;
7185                    }
7186                    if (!isFirstBoot() && dexOptDialogShown) {
7187                        try {
7188                            ActivityManagerNative.getDefault().showBootMessage(
7189                                    mContext.getResources().getString(
7190                                            R.string.android_upgrading_fstrim), true);
7191                        } catch (RemoteException e) {
7192                        }
7193                    }
7194                    ms.runMaintenance();
7195                }
7196            } else {
7197                Slog.e(TAG, "Mount service unavailable!");
7198            }
7199        } catch (RemoteException e) {
7200            // Can't happen; MountService is local
7201        }
7202    }
7203
7204    @Override
7205    public void updatePackagesIfNeeded() {
7206        enforceSystemOrRoot("Only the system can request package update");
7207
7208        // We need to re-extract after an OTA.
7209        boolean causeUpgrade = isUpgrade();
7210
7211        // First boot or factory reset.
7212        // Note: we also handle devices that are upgrading to N right now as if it is their
7213        //       first boot, as they do not have profile data.
7214        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7215
7216        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7217        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7218
7219        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7220            return;
7221        }
7222
7223        List<PackageParser.Package> pkgs;
7224        synchronized (mPackages) {
7225            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7226        }
7227
7228        final long startTime = System.nanoTime();
7229        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7230                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7231
7232        final int elapsedTimeSeconds =
7233                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7234
7235        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7236        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7237        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7238        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7239        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7240    }
7241
7242    /**
7243     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7244     * containing statistics about the invocation. The array consists of three elements,
7245     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7246     * and {@code numberOfPackagesFailed}.
7247     */
7248    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7249            String compilerFilter) {
7250
7251        int numberOfPackagesVisited = 0;
7252        int numberOfPackagesOptimized = 0;
7253        int numberOfPackagesSkipped = 0;
7254        int numberOfPackagesFailed = 0;
7255        final int numberOfPackagesToDexopt = pkgs.size();
7256
7257        for (PackageParser.Package pkg : pkgs) {
7258            numberOfPackagesVisited++;
7259
7260            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7261                if (DEBUG_DEXOPT) {
7262                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7263                }
7264                numberOfPackagesSkipped++;
7265                continue;
7266            }
7267
7268            if (DEBUG_DEXOPT) {
7269                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7270                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7271            }
7272
7273            if (showDialog) {
7274                try {
7275                    ActivityManagerNative.getDefault().showBootMessage(
7276                            mContext.getResources().getString(R.string.android_upgrading_apk,
7277                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7278                } catch (RemoteException e) {
7279                }
7280                synchronized (mPackages) {
7281                    mDexOptDialogShown = true;
7282                }
7283            }
7284
7285            // If the OTA updates a system app which was previously preopted to a non-preopted state
7286            // the app might end up being verified at runtime. That's because by default the apps
7287            // are verify-profile but for preopted apps there's no profile.
7288            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7289            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7290            // filter (by default interpret-only).
7291            // Note that at this stage unused apps are already filtered.
7292            if (isSystemApp(pkg) &&
7293                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7294                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7295                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7296            }
7297
7298            // If the OTA updates a system app which was previously preopted to a non-preopted state
7299            // the app might end up being verified at runtime. That's because by default the apps
7300            // are verify-profile but for preopted apps there's no profile.
7301            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7302            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7303            // filter (by default interpret-only).
7304            // Note that at this stage unused apps are already filtered.
7305            if (isSystemApp(pkg) &&
7306                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7307                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7308                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7309            }
7310
7311            // checkProfiles is false to avoid merging profiles during boot which
7312            // might interfere with background compilation (b/28612421).
7313            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7314            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7315            // trade-off worth doing to save boot time work.
7316            int dexOptStatus = performDexOptTraced(pkg.packageName,
7317                    false /* checkProfiles */,
7318                    compilerFilter,
7319                    false /* force */);
7320            switch (dexOptStatus) {
7321                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7322                    numberOfPackagesOptimized++;
7323                    break;
7324                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7325                    numberOfPackagesSkipped++;
7326                    break;
7327                case PackageDexOptimizer.DEX_OPT_FAILED:
7328                    numberOfPackagesFailed++;
7329                    break;
7330                default:
7331                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7332                    break;
7333            }
7334        }
7335
7336        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7337                numberOfPackagesFailed };
7338    }
7339
7340    @Override
7341    public void notifyPackageUse(String packageName, int reason) {
7342        synchronized (mPackages) {
7343            PackageParser.Package p = mPackages.get(packageName);
7344            if (p == null) {
7345                return;
7346            }
7347            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7348        }
7349    }
7350
7351    // TODO: this is not used nor needed. Delete it.
7352    @Override
7353    public boolean performDexOptIfNeeded(String packageName) {
7354        int dexOptStatus = performDexOptTraced(packageName,
7355                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7356        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7357    }
7358
7359    @Override
7360    public boolean performDexOpt(String packageName,
7361            boolean checkProfiles, int compileReason, boolean force) {
7362        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7363                getCompilerFilterForReason(compileReason), force);
7364        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7365    }
7366
7367    @Override
7368    public boolean performDexOptMode(String packageName,
7369            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7370        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7371                targetCompilerFilter, force);
7372        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7373    }
7374
7375    private int performDexOptTraced(String packageName,
7376                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7377        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7378        try {
7379            return performDexOptInternal(packageName, checkProfiles,
7380                    targetCompilerFilter, force);
7381        } finally {
7382            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7383        }
7384    }
7385
7386    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7387    // if the package can now be considered up to date for the given filter.
7388    private int performDexOptInternal(String packageName,
7389                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7390        PackageParser.Package p;
7391        synchronized (mPackages) {
7392            p = mPackages.get(packageName);
7393            if (p == null) {
7394                // Package could not be found. Report failure.
7395                return PackageDexOptimizer.DEX_OPT_FAILED;
7396            }
7397            mPackageUsage.maybeWriteAsync(mPackages);
7398            mCompilerStats.maybeWriteAsync();
7399        }
7400        long callingId = Binder.clearCallingIdentity();
7401        try {
7402            synchronized (mInstallLock) {
7403                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7404                        targetCompilerFilter, force);
7405            }
7406        } finally {
7407            Binder.restoreCallingIdentity(callingId);
7408        }
7409    }
7410
7411    public ArraySet<String> getOptimizablePackages() {
7412        ArraySet<String> pkgs = new ArraySet<String>();
7413        synchronized (mPackages) {
7414            for (PackageParser.Package p : mPackages.values()) {
7415                if (PackageDexOptimizer.canOptimizePackage(p)) {
7416                    pkgs.add(p.packageName);
7417                }
7418            }
7419        }
7420        return pkgs;
7421    }
7422
7423    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7424            boolean checkProfiles, String targetCompilerFilter,
7425            boolean force) {
7426        // Select the dex optimizer based on the force parameter.
7427        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7428        //       allocate an object here.
7429        PackageDexOptimizer pdo = force
7430                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7431                : mPackageDexOptimizer;
7432
7433        // Optimize all dependencies first. Note: we ignore the return value and march on
7434        // on errors.
7435        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7436        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7437        if (!deps.isEmpty()) {
7438            for (PackageParser.Package depPackage : deps) {
7439                // TODO: Analyze and investigate if we (should) profile libraries.
7440                // Currently this will do a full compilation of the library by default.
7441                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7442                        false /* checkProfiles */,
7443                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7444                        getOrCreateCompilerPackageStats(depPackage));
7445            }
7446        }
7447        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7448                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7449    }
7450
7451    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7452        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7453            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7454            Set<String> collectedNames = new HashSet<>();
7455            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7456
7457            retValue.remove(p);
7458
7459            return retValue;
7460        } else {
7461            return Collections.emptyList();
7462        }
7463    }
7464
7465    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7466            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7467        if (!collectedNames.contains(p.packageName)) {
7468            collectedNames.add(p.packageName);
7469            collected.add(p);
7470
7471            if (p.usesLibraries != null) {
7472                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7473            }
7474            if (p.usesOptionalLibraries != null) {
7475                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7476                        collectedNames);
7477            }
7478        }
7479    }
7480
7481    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7482            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7483        for (String libName : libs) {
7484            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7485            if (libPkg != null) {
7486                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7487            }
7488        }
7489    }
7490
7491    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7492        synchronized (mPackages) {
7493            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7494            if (lib != null && lib.apk != null) {
7495                return mPackages.get(lib.apk);
7496            }
7497        }
7498        return null;
7499    }
7500
7501    public void shutdown() {
7502        mPackageUsage.writeNow(mPackages);
7503        mCompilerStats.writeNow();
7504    }
7505
7506    @Override
7507    public void dumpProfiles(String packageName) {
7508        PackageParser.Package pkg;
7509        synchronized (mPackages) {
7510            pkg = mPackages.get(packageName);
7511            if (pkg == null) {
7512                throw new IllegalArgumentException("Unknown package: " + packageName);
7513            }
7514        }
7515        /* Only the shell, root, or the app user should be able to dump profiles. */
7516        int callingUid = Binder.getCallingUid();
7517        if (callingUid != Process.SHELL_UID &&
7518            callingUid != Process.ROOT_UID &&
7519            callingUid != pkg.applicationInfo.uid) {
7520            throw new SecurityException("dumpProfiles");
7521        }
7522
7523        synchronized (mInstallLock) {
7524            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7525            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7526            try {
7527                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7528                String gid = Integer.toString(sharedGid);
7529                String codePaths = TextUtils.join(";", allCodePaths);
7530                mInstaller.dumpProfiles(gid, packageName, codePaths);
7531            } catch (InstallerException e) {
7532                Slog.w(TAG, "Failed to dump profiles", e);
7533            }
7534            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7535        }
7536    }
7537
7538    @Override
7539    public void forceDexOpt(String packageName) {
7540        enforceSystemOrRoot("forceDexOpt");
7541
7542        PackageParser.Package pkg;
7543        synchronized (mPackages) {
7544            pkg = mPackages.get(packageName);
7545            if (pkg == null) {
7546                throw new IllegalArgumentException("Unknown package: " + packageName);
7547            }
7548        }
7549
7550        synchronized (mInstallLock) {
7551            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7552
7553            // Whoever is calling forceDexOpt wants a fully compiled package.
7554            // Don't use profiles since that may cause compilation to be skipped.
7555            final int res = performDexOptInternalWithDependenciesLI(pkg,
7556                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7557                    true /* force */);
7558
7559            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7560            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7561                throw new IllegalStateException("Failed to dexopt: " + res);
7562            }
7563        }
7564    }
7565
7566    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7567        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7568            Slog.w(TAG, "Unable to update from " + oldPkg.name
7569                    + " to " + newPkg.packageName
7570                    + ": old package not in system partition");
7571            return false;
7572        } else if (mPackages.get(oldPkg.name) != null) {
7573            Slog.w(TAG, "Unable to update from " + oldPkg.name
7574                    + " to " + newPkg.packageName
7575                    + ": old package still exists");
7576            return false;
7577        }
7578        return true;
7579    }
7580
7581    void removeCodePathLI(File codePath) {
7582        if (codePath.isDirectory()) {
7583            try {
7584                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7585            } catch (InstallerException e) {
7586                Slog.w(TAG, "Failed to remove code path", e);
7587            }
7588        } else {
7589            codePath.delete();
7590        }
7591    }
7592
7593    private int[] resolveUserIds(int userId) {
7594        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7595    }
7596
7597    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7598        if (pkg == null) {
7599            Slog.wtf(TAG, "Package was null!", new Throwable());
7600            return;
7601        }
7602        clearAppDataLeafLIF(pkg, userId, flags);
7603        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7604        for (int i = 0; i < childCount; i++) {
7605            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7606        }
7607    }
7608
7609    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7610        final PackageSetting ps;
7611        synchronized (mPackages) {
7612            ps = mSettings.mPackages.get(pkg.packageName);
7613        }
7614        for (int realUserId : resolveUserIds(userId)) {
7615            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7616            try {
7617                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7618                        ceDataInode);
7619            } catch (InstallerException e) {
7620                Slog.w(TAG, String.valueOf(e));
7621            }
7622        }
7623    }
7624
7625    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7626        if (pkg == null) {
7627            Slog.wtf(TAG, "Package was null!", new Throwable());
7628            return;
7629        }
7630        destroyAppDataLeafLIF(pkg, userId, flags);
7631        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7632        for (int i = 0; i < childCount; i++) {
7633            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7634        }
7635    }
7636
7637    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7638        final PackageSetting ps;
7639        synchronized (mPackages) {
7640            ps = mSettings.mPackages.get(pkg.packageName);
7641        }
7642        for (int realUserId : resolveUserIds(userId)) {
7643            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7644            try {
7645                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7646                        ceDataInode);
7647            } catch (InstallerException e) {
7648                Slog.w(TAG, String.valueOf(e));
7649            }
7650        }
7651    }
7652
7653    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7654        if (pkg == null) {
7655            Slog.wtf(TAG, "Package was null!", new Throwable());
7656            return;
7657        }
7658        destroyAppProfilesLeafLIF(pkg);
7659        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7660        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7661        for (int i = 0; i < childCount; i++) {
7662            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7663            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7664                    true /* removeBaseMarker */);
7665        }
7666    }
7667
7668    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7669            boolean removeBaseMarker) {
7670        if (pkg.isForwardLocked()) {
7671            return;
7672        }
7673
7674        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7675            try {
7676                path = PackageManagerServiceUtils.realpath(new File(path));
7677            } catch (IOException e) {
7678                // TODO: Should we return early here ?
7679                Slog.w(TAG, "Failed to get canonical path", e);
7680                continue;
7681            }
7682
7683            final String useMarker = path.replace('/', '@');
7684            for (int realUserId : resolveUserIds(userId)) {
7685                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7686                if (removeBaseMarker) {
7687                    File foreignUseMark = new File(profileDir, useMarker);
7688                    if (foreignUseMark.exists()) {
7689                        if (!foreignUseMark.delete()) {
7690                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7691                                    + pkg.packageName);
7692                        }
7693                    }
7694                }
7695
7696                File[] markers = profileDir.listFiles();
7697                if (markers != null) {
7698                    final String searchString = "@" + pkg.packageName + "@";
7699                    // We also delete all markers that contain the package name we're
7700                    // uninstalling. These are associated with secondary dex-files belonging
7701                    // to the package. Reconstructing the path of these dex files is messy
7702                    // in general.
7703                    for (File marker : markers) {
7704                        if (marker.getName().indexOf(searchString) > 0) {
7705                            if (!marker.delete()) {
7706                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7707                                    + pkg.packageName);
7708                            }
7709                        }
7710                    }
7711                }
7712            }
7713        }
7714    }
7715
7716    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7717        try {
7718            mInstaller.destroyAppProfiles(pkg.packageName);
7719        } catch (InstallerException e) {
7720            Slog.w(TAG, String.valueOf(e));
7721        }
7722    }
7723
7724    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7725        if (pkg == null) {
7726            Slog.wtf(TAG, "Package was null!", new Throwable());
7727            return;
7728        }
7729        clearAppProfilesLeafLIF(pkg);
7730        // We don't remove the base foreign use marker when clearing profiles because
7731        // we will rename it when the app is updated. Unlike the actual profile contents,
7732        // the foreign use marker is good across installs.
7733        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7734        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7735        for (int i = 0; i < childCount; i++) {
7736            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7737        }
7738    }
7739
7740    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7741        try {
7742            mInstaller.clearAppProfiles(pkg.packageName);
7743        } catch (InstallerException e) {
7744            Slog.w(TAG, String.valueOf(e));
7745        }
7746    }
7747
7748    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7749            long lastUpdateTime) {
7750        // Set parent install/update time
7751        PackageSetting ps = (PackageSetting) pkg.mExtras;
7752        if (ps != null) {
7753            ps.firstInstallTime = firstInstallTime;
7754            ps.lastUpdateTime = lastUpdateTime;
7755        }
7756        // Set children install/update time
7757        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7758        for (int i = 0; i < childCount; i++) {
7759            PackageParser.Package childPkg = pkg.childPackages.get(i);
7760            ps = (PackageSetting) childPkg.mExtras;
7761            if (ps != null) {
7762                ps.firstInstallTime = firstInstallTime;
7763                ps.lastUpdateTime = lastUpdateTime;
7764            }
7765        }
7766    }
7767
7768    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7769            PackageParser.Package changingLib) {
7770        if (file.path != null) {
7771            usesLibraryFiles.add(file.path);
7772            return;
7773        }
7774        PackageParser.Package p = mPackages.get(file.apk);
7775        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7776            // If we are doing this while in the middle of updating a library apk,
7777            // then we need to make sure to use that new apk for determining the
7778            // dependencies here.  (We haven't yet finished committing the new apk
7779            // to the package manager state.)
7780            if (p == null || p.packageName.equals(changingLib.packageName)) {
7781                p = changingLib;
7782            }
7783        }
7784        if (p != null) {
7785            usesLibraryFiles.addAll(p.getAllCodePaths());
7786        }
7787    }
7788
7789    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7790            PackageParser.Package changingLib) throws PackageManagerException {
7791        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7792            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7793            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7794            for (int i=0; i<N; i++) {
7795                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7796                if (file == null) {
7797                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7798                            "Package " + pkg.packageName + " requires unavailable shared library "
7799                            + pkg.usesLibraries.get(i) + "; failing!");
7800                }
7801                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7802            }
7803            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7804            for (int i=0; i<N; i++) {
7805                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7806                if (file == null) {
7807                    Slog.w(TAG, "Package " + pkg.packageName
7808                            + " desires unavailable shared library "
7809                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7810                } else {
7811                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7812                }
7813            }
7814            N = usesLibraryFiles.size();
7815            if (N > 0) {
7816                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7817            } else {
7818                pkg.usesLibraryFiles = null;
7819            }
7820        }
7821    }
7822
7823    private static boolean hasString(List<String> list, List<String> which) {
7824        if (list == null) {
7825            return false;
7826        }
7827        for (int i=list.size()-1; i>=0; i--) {
7828            for (int j=which.size()-1; j>=0; j--) {
7829                if (which.get(j).equals(list.get(i))) {
7830                    return true;
7831                }
7832            }
7833        }
7834        return false;
7835    }
7836
7837    private void updateAllSharedLibrariesLPw() {
7838        for (PackageParser.Package pkg : mPackages.values()) {
7839            try {
7840                updateSharedLibrariesLPw(pkg, null);
7841            } catch (PackageManagerException e) {
7842                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7843            }
7844        }
7845    }
7846
7847    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7848            PackageParser.Package changingPkg) {
7849        ArrayList<PackageParser.Package> res = null;
7850        for (PackageParser.Package pkg : mPackages.values()) {
7851            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7852                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7853                if (res == null) {
7854                    res = new ArrayList<PackageParser.Package>();
7855                }
7856                res.add(pkg);
7857                try {
7858                    updateSharedLibrariesLPw(pkg, changingPkg);
7859                } catch (PackageManagerException e) {
7860                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7861                }
7862            }
7863        }
7864        return res;
7865    }
7866
7867    /**
7868     * Derive the value of the {@code cpuAbiOverride} based on the provided
7869     * value and an optional stored value from the package settings.
7870     */
7871    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7872        String cpuAbiOverride = null;
7873
7874        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7875            cpuAbiOverride = null;
7876        } else if (abiOverride != null) {
7877            cpuAbiOverride = abiOverride;
7878        } else if (settings != null) {
7879            cpuAbiOverride = settings.cpuAbiOverrideString;
7880        }
7881
7882        return cpuAbiOverride;
7883    }
7884
7885    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7886            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7887                    throws PackageManagerException {
7888        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7889        // If the package has children and this is the first dive in the function
7890        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7891        // whether all packages (parent and children) would be successfully scanned
7892        // before the actual scan since scanning mutates internal state and we want
7893        // to atomically install the package and its children.
7894        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7895            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7896                scanFlags |= SCAN_CHECK_ONLY;
7897            }
7898        } else {
7899            scanFlags &= ~SCAN_CHECK_ONLY;
7900        }
7901
7902        final PackageParser.Package scannedPkg;
7903        try {
7904            // Scan the parent
7905            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7906            // Scan the children
7907            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7908            for (int i = 0; i < childCount; i++) {
7909                PackageParser.Package childPkg = pkg.childPackages.get(i);
7910                scanPackageLI(childPkg, policyFlags,
7911                        scanFlags, currentTime, user);
7912            }
7913        } finally {
7914            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7915        }
7916
7917        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7918            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7919        }
7920
7921        return scannedPkg;
7922    }
7923
7924    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7925            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7926        boolean success = false;
7927        try {
7928            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7929                    currentTime, user);
7930            success = true;
7931            return res;
7932        } finally {
7933            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7934                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7935                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7936                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7937                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7938            }
7939        }
7940    }
7941
7942    /**
7943     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7944     */
7945    private static boolean apkHasCode(String fileName) {
7946        StrictJarFile jarFile = null;
7947        try {
7948            jarFile = new StrictJarFile(fileName,
7949                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7950            return jarFile.findEntry("classes.dex") != null;
7951        } catch (IOException ignore) {
7952        } finally {
7953            try {
7954                if (jarFile != null) {
7955                    jarFile.close();
7956                }
7957            } catch (IOException ignore) {}
7958        }
7959        return false;
7960    }
7961
7962    /**
7963     * Enforces code policy for the package. This ensures that if an APK has
7964     * declared hasCode="true" in its manifest that the APK actually contains
7965     * code.
7966     *
7967     * @throws PackageManagerException If bytecode could not be found when it should exist
7968     */
7969    private static void enforceCodePolicy(PackageParser.Package pkg)
7970            throws PackageManagerException {
7971        final boolean shouldHaveCode =
7972                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7973        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7974            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7975                    "Package " + pkg.baseCodePath + " code is missing");
7976        }
7977
7978        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7979            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7980                final boolean splitShouldHaveCode =
7981                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7982                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7983                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7984                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7985                }
7986            }
7987        }
7988    }
7989
7990    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7991            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7992            throws PackageManagerException {
7993        final File scanFile = new File(pkg.codePath);
7994        if (pkg.applicationInfo.getCodePath() == null ||
7995                pkg.applicationInfo.getResourcePath() == null) {
7996            // Bail out. The resource and code paths haven't been set.
7997            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7998                    "Code and resource paths haven't been set correctly");
7999        }
8000
8001        // Apply policy
8002        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8003            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8004            if (pkg.applicationInfo.isDirectBootAware()) {
8005                // we're direct boot aware; set for all components
8006                for (PackageParser.Service s : pkg.services) {
8007                    s.info.encryptionAware = s.info.directBootAware = true;
8008                }
8009                for (PackageParser.Provider p : pkg.providers) {
8010                    p.info.encryptionAware = p.info.directBootAware = true;
8011                }
8012                for (PackageParser.Activity a : pkg.activities) {
8013                    a.info.encryptionAware = a.info.directBootAware = true;
8014                }
8015                for (PackageParser.Activity r : pkg.receivers) {
8016                    r.info.encryptionAware = r.info.directBootAware = true;
8017                }
8018            }
8019        } else {
8020            // Only allow system apps to be flagged as core apps.
8021            pkg.coreApp = false;
8022            // clear flags not applicable to regular apps
8023            pkg.applicationInfo.privateFlags &=
8024                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8025            pkg.applicationInfo.privateFlags &=
8026                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8027        }
8028        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8029
8030        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8031            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8032        }
8033
8034        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8035            enforceCodePolicy(pkg);
8036        }
8037
8038        if (mCustomResolverComponentName != null &&
8039                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8040            setUpCustomResolverActivity(pkg);
8041        }
8042
8043        if (pkg.packageName.equals("android")) {
8044            synchronized (mPackages) {
8045                if (mAndroidApplication != null) {
8046                    Slog.w(TAG, "*************************************************");
8047                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8048                    Slog.w(TAG, " file=" + scanFile);
8049                    Slog.w(TAG, "*************************************************");
8050                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8051                            "Core android package being redefined.  Skipping.");
8052                }
8053
8054                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8055                    // Set up information for our fall-back user intent resolution activity.
8056                    mPlatformPackage = pkg;
8057                    pkg.mVersionCode = mSdkVersion;
8058                    mAndroidApplication = pkg.applicationInfo;
8059
8060                    if (!mResolverReplaced) {
8061                        mResolveActivity.applicationInfo = mAndroidApplication;
8062                        mResolveActivity.name = ResolverActivity.class.getName();
8063                        mResolveActivity.packageName = mAndroidApplication.packageName;
8064                        mResolveActivity.processName = "system:ui";
8065                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8066                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8067                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8068                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8069                        mResolveActivity.exported = true;
8070                        mResolveActivity.enabled = true;
8071                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8072                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8073                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8074                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8075                                | ActivityInfo.CONFIG_ORIENTATION
8076                                | ActivityInfo.CONFIG_KEYBOARD
8077                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8078                        mResolveInfo.activityInfo = mResolveActivity;
8079                        mResolveInfo.priority = 0;
8080                        mResolveInfo.preferredOrder = 0;
8081                        mResolveInfo.match = 0;
8082                        mResolveComponentName = new ComponentName(
8083                                mAndroidApplication.packageName, mResolveActivity.name);
8084                    }
8085                }
8086            }
8087        }
8088
8089        if (DEBUG_PACKAGE_SCANNING) {
8090            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8091                Log.d(TAG, "Scanning package " + pkg.packageName);
8092        }
8093
8094        synchronized (mPackages) {
8095            if (mPackages.containsKey(pkg.packageName)
8096                    || mSharedLibraries.containsKey(pkg.packageName)) {
8097                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8098                        "Application package " + pkg.packageName
8099                                + " already installed.  Skipping duplicate.");
8100            }
8101
8102            // If we're only installing presumed-existing packages, require that the
8103            // scanned APK is both already known and at the path previously established
8104            // for it.  Previously unknown packages we pick up normally, but if we have an
8105            // a priori expectation about this package's install presence, enforce it.
8106            // With a singular exception for new system packages. When an OTA contains
8107            // a new system package, we allow the codepath to change from a system location
8108            // to the user-installed location. If we don't allow this change, any newer,
8109            // user-installed version of the application will be ignored.
8110            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8111                if (mExpectingBetter.containsKey(pkg.packageName)) {
8112                    logCriticalInfo(Log.WARN,
8113                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8114                } else {
8115                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8116                    if (known != null) {
8117                        if (DEBUG_PACKAGE_SCANNING) {
8118                            Log.d(TAG, "Examining " + pkg.codePath
8119                                    + " and requiring known paths " + known.codePathString
8120                                    + " & " + known.resourcePathString);
8121                        }
8122                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8123                                || !pkg.applicationInfo.getResourcePath().equals(
8124                                known.resourcePathString)) {
8125                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8126                                    "Application package " + pkg.packageName
8127                                            + " found at " + pkg.applicationInfo.getCodePath()
8128                                            + " but expected at " + known.codePathString
8129                                            + "; ignoring.");
8130                        }
8131                    }
8132                }
8133            }
8134        }
8135
8136        // Initialize package source and resource directories
8137        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8138        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8139
8140        SharedUserSetting suid = null;
8141        PackageSetting pkgSetting = null;
8142
8143        if (!isSystemApp(pkg)) {
8144            // Only system apps can use these features.
8145            pkg.mOriginalPackages = null;
8146            pkg.mRealPackage = null;
8147            pkg.mAdoptPermissions = null;
8148        }
8149
8150        // Getting the package setting may have a side-effect, so if we
8151        // are only checking if scan would succeed, stash a copy of the
8152        // old setting to restore at the end.
8153        PackageSetting nonMutatedPs = null;
8154
8155        // writer
8156        synchronized (mPackages) {
8157            if (pkg.mSharedUserId != null) {
8158                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8159                if (suid == null) {
8160                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8161                            "Creating application package " + pkg.packageName
8162                            + " for shared user failed");
8163                }
8164                if (DEBUG_PACKAGE_SCANNING) {
8165                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8166                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8167                                + "): packages=" + suid.packages);
8168                }
8169            }
8170
8171            // Check if we are renaming from an original package name.
8172            PackageSetting origPackage = null;
8173            String realName = null;
8174            if (pkg.mOriginalPackages != null) {
8175                // This package may need to be renamed to a previously
8176                // installed name.  Let's check on that...
8177                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8178                if (pkg.mOriginalPackages.contains(renamed)) {
8179                    // This package had originally been installed as the
8180                    // original name, and we have already taken care of
8181                    // transitioning to the new one.  Just update the new
8182                    // one to continue using the old name.
8183                    realName = pkg.mRealPackage;
8184                    if (!pkg.packageName.equals(renamed)) {
8185                        // Callers into this function may have already taken
8186                        // care of renaming the package; only do it here if
8187                        // it is not already done.
8188                        pkg.setPackageName(renamed);
8189                    }
8190
8191                } else {
8192                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8193                        if ((origPackage = mSettings.peekPackageLPr(
8194                                pkg.mOriginalPackages.get(i))) != null) {
8195                            // We do have the package already installed under its
8196                            // original name...  should we use it?
8197                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8198                                // New package is not compatible with original.
8199                                origPackage = null;
8200                                continue;
8201                            } else if (origPackage.sharedUser != null) {
8202                                // Make sure uid is compatible between packages.
8203                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8204                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8205                                            + " to " + pkg.packageName + ": old uid "
8206                                            + origPackage.sharedUser.name
8207                                            + " differs from " + pkg.mSharedUserId);
8208                                    origPackage = null;
8209                                    continue;
8210                                }
8211                                // TODO: Add case when shared user id is added [b/28144775]
8212                            } else {
8213                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8214                                        + pkg.packageName + " to old name " + origPackage.name);
8215                            }
8216                            break;
8217                        }
8218                    }
8219                }
8220            }
8221
8222            if (mTransferedPackages.contains(pkg.packageName)) {
8223                Slog.w(TAG, "Package " + pkg.packageName
8224                        + " was transferred to another, but its .apk remains");
8225            }
8226
8227            // See comments in nonMutatedPs declaration
8228            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8229                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8230                if (foundPs != null) {
8231                    nonMutatedPs = new PackageSetting(foundPs);
8232                }
8233            }
8234
8235            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8236            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
8237                PackageManagerService.reportSettingsProblem(Log.WARN,
8238                        "Package " + pkg.packageName + " shared user changed from "
8239                        + (pkgSetting.sharedUser != null ? pkgSetting.sharedUser.name : "<nothing>")
8240                        + " to "
8241                        + (suid != null ? suid.name : "<nothing>")
8242                        + "; replacing with new");
8243                pkgSetting = null;
8244            }
8245            final PackageSetting oldPkgSetting =
8246                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
8247            final PackageSetting disabledPkgSetting =
8248                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8249            if (pkgSetting == null) {
8250                final String parentPackageName = (pkg.parentPackage != null)
8251                        ? pkg.parentPackage.packageName : null;
8252                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
8253                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
8254                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
8255                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
8256                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
8257                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
8258                        UserManagerService.getInstance());
8259                if (origPackage != null) {
8260                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
8261                }
8262                mSettings.addUserToSettingLPw(pkgSetting);
8263            } else {
8264                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
8265                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
8266                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
8267                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
8268                        UserManagerService.getInstance());
8269            }
8270            mSettings.writeUserRestrictions(pkgSetting, oldPkgSetting);
8271
8272            if (pkgSetting.origPackage != null) {
8273                // If we are first transitioning from an original package,
8274                // fix up the new package's name now.  We need to do this after
8275                // looking up the package under its new name, so getPackageLP
8276                // can take care of fiddling things correctly.
8277                pkg.setPackageName(origPackage.name);
8278
8279                // File a report about this.
8280                String msg = "New package " + pkgSetting.realName
8281                        + " renamed to replace old package " + pkgSetting.name;
8282                reportSettingsProblem(Log.WARN, msg);
8283
8284                // Make a note of it.
8285                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8286                    mTransferedPackages.add(origPackage.name);
8287                }
8288
8289                // No longer need to retain this.
8290                pkgSetting.origPackage = null;
8291            }
8292
8293            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8294                // Make a note of it.
8295                mTransferedPackages.add(pkg.packageName);
8296            }
8297
8298            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8299                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8300            }
8301
8302            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8303                // Check all shared libraries and map to their actual file path.
8304                // We only do this here for apps not on a system dir, because those
8305                // are the only ones that can fail an install due to this.  We
8306                // will take care of the system apps by updating all of their
8307                // library paths after the scan is done.
8308                updateSharedLibrariesLPw(pkg, null);
8309            }
8310
8311            if (mFoundPolicyFile) {
8312                SELinuxMMAC.assignSeinfoValue(pkg);
8313            }
8314
8315            pkg.applicationInfo.uid = pkgSetting.appId;
8316            pkg.mExtras = pkgSetting;
8317            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8318                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8319                    // We just determined the app is signed correctly, so bring
8320                    // over the latest parsed certs.
8321                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8322                } else {
8323                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8324                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8325                                "Package " + pkg.packageName + " upgrade keys do not match the "
8326                                + "previously installed version");
8327                    } else {
8328                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8329                        String msg = "System package " + pkg.packageName
8330                            + " signature changed; retaining data.";
8331                        reportSettingsProblem(Log.WARN, msg);
8332                    }
8333                }
8334            } else {
8335                try {
8336                    verifySignaturesLP(pkgSetting, pkg);
8337                    // We just determined the app is signed correctly, so bring
8338                    // over the latest parsed certs.
8339                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8340                } catch (PackageManagerException e) {
8341                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8342                        throw e;
8343                    }
8344                    // The signature has changed, but this package is in the system
8345                    // image...  let's recover!
8346                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8347                    // However...  if this package is part of a shared user, but it
8348                    // doesn't match the signature of the shared user, let's fail.
8349                    // What this means is that you can't change the signatures
8350                    // associated with an overall shared user, which doesn't seem all
8351                    // that unreasonable.
8352                    if (pkgSetting.sharedUser != null) {
8353                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8354                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8355                            throw new PackageManagerException(
8356                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8357                                            "Signature mismatch for shared user: "
8358                                            + pkgSetting.sharedUser);
8359                        }
8360                    }
8361                    // File a report about this.
8362                    String msg = "System package " + pkg.packageName
8363                        + " signature changed; retaining data.";
8364                    reportSettingsProblem(Log.WARN, msg);
8365                }
8366            }
8367            // Verify that this new package doesn't have any content providers
8368            // that conflict with existing packages.  Only do this if the
8369            // package isn't already installed, since we don't want to break
8370            // things that are installed.
8371            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8372                final int N = pkg.providers.size();
8373                int i;
8374                for (i=0; i<N; i++) {
8375                    PackageParser.Provider p = pkg.providers.get(i);
8376                    if (p.info.authority != null) {
8377                        String names[] = p.info.authority.split(";");
8378                        for (int j = 0; j < names.length; j++) {
8379                            if (mProvidersByAuthority.containsKey(names[j])) {
8380                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8381                                final String otherPackageName =
8382                                        ((other != null && other.getComponentName() != null) ?
8383                                                other.getComponentName().getPackageName() : "?");
8384                                throw new PackageManagerException(
8385                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8386                                                "Can't install because provider name " + names[j]
8387                                                + " (in package " + pkg.applicationInfo.packageName
8388                                                + ") is already used by " + otherPackageName);
8389                            }
8390                        }
8391                    }
8392                }
8393            }
8394
8395            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8396                // This package wants to adopt ownership of permissions from
8397                // another package.
8398                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8399                    final String origName = pkg.mAdoptPermissions.get(i);
8400                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8401                    if (orig != null) {
8402                        if (verifyPackageUpdateLPr(orig, pkg)) {
8403                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8404                                    + pkg.packageName);
8405                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8406                        }
8407                    }
8408                }
8409            }
8410        }
8411
8412        final String pkgName = pkg.packageName;
8413
8414        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8415        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8416        pkg.applicationInfo.processName = fixProcessName(
8417                pkg.applicationInfo.packageName,
8418                pkg.applicationInfo.processName,
8419                pkg.applicationInfo.uid);
8420
8421        if (pkg != mPlatformPackage) {
8422            // Get all of our default paths setup
8423            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8424        }
8425
8426        final String path = scanFile.getPath();
8427        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8428
8429        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8430            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
8431            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /*extractLibs*/);
8432            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8433
8434            // Some system apps still use directory structure for native libraries
8435            // in which case we might end up not detecting abi solely based on apk
8436            // structure. Try to detect abi based on directory structure.
8437            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8438                    pkg.applicationInfo.primaryCpuAbi == null) {
8439                setBundledAppAbisAndRoots(pkg, pkgSetting);
8440                setNativeLibraryPaths(pkg);
8441            }
8442
8443        } else {
8444            if ((scanFlags & SCAN_MOVE) != 0) {
8445                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8446                // but we already have this packages package info in the PackageSetting. We just
8447                // use that and derive the native library path based on the new codepath.
8448                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8449                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8450            }
8451
8452            // Set native library paths again. For moves, the path will be updated based on the
8453            // ABIs we've determined above. For non-moves, the path will be updated based on the
8454            // ABIs we determined during compilation, but the path will depend on the final
8455            // package path (after the rename away from the stage path).
8456            setNativeLibraryPaths(pkg);
8457        }
8458
8459        // This is a special case for the "system" package, where the ABI is
8460        // dictated by the zygote configuration (and init.rc). We should keep track
8461        // of this ABI so that we can deal with "normal" applications that run under
8462        // the same UID correctly.
8463        if (mPlatformPackage == pkg) {
8464            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8465                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8466        }
8467
8468        // If there's a mismatch between the abi-override in the package setting
8469        // and the abiOverride specified for the install. Warn about this because we
8470        // would've already compiled the app without taking the package setting into
8471        // account.
8472        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8473            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8474                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8475                        " for package " + pkg.packageName);
8476            }
8477        }
8478
8479        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8480        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8481        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8482
8483        // Copy the derived override back to the parsed package, so that we can
8484        // update the package settings accordingly.
8485        pkg.cpuAbiOverride = cpuAbiOverride;
8486
8487        if (DEBUG_ABI_SELECTION) {
8488            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8489                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8490                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8491        }
8492
8493        // Push the derived path down into PackageSettings so we know what to
8494        // clean up at uninstall time.
8495        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8496
8497        if (DEBUG_ABI_SELECTION) {
8498            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8499                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8500                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8501        }
8502
8503        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8504            // We don't do this here during boot because we can do it all
8505            // at once after scanning all existing packages.
8506            //
8507            // We also do this *before* we perform dexopt on this package, so that
8508            // we can avoid redundant dexopts, and also to make sure we've got the
8509            // code and package path correct.
8510            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8511                    pkg, true /* boot complete */);
8512        }
8513
8514        if (mFactoryTest && pkg.requestedPermissions.contains(
8515                android.Manifest.permission.FACTORY_TEST)) {
8516            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8517        }
8518
8519        if (isSystemApp(pkg)) {
8520            pkgSetting.isOrphaned = true;
8521        }
8522
8523        ArrayList<PackageParser.Package> clientLibPkgs = null;
8524
8525        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8526            if (nonMutatedPs != null) {
8527                synchronized (mPackages) {
8528                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8529                }
8530            }
8531            return pkg;
8532        }
8533
8534        // Only privileged apps and updated privileged apps can add child packages.
8535        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8536            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8537                throw new PackageManagerException("Only privileged apps and updated "
8538                        + "privileged apps can add child packages. Ignoring package "
8539                        + pkg.packageName);
8540            }
8541            final int childCount = pkg.childPackages.size();
8542            for (int i = 0; i < childCount; i++) {
8543                PackageParser.Package childPkg = pkg.childPackages.get(i);
8544                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8545                        childPkg.packageName)) {
8546                    throw new PackageManagerException("Cannot override a child package of "
8547                            + "another disabled system app. Ignoring package " + pkg.packageName);
8548                }
8549            }
8550        }
8551
8552        // writer
8553        synchronized (mPackages) {
8554            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8555                // Only system apps can add new shared libraries.
8556                if (pkg.libraryNames != null) {
8557                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8558                        String name = pkg.libraryNames.get(i);
8559                        boolean allowed = false;
8560                        if (pkg.isUpdatedSystemApp()) {
8561                            // New library entries can only be added through the
8562                            // system image.  This is important to get rid of a lot
8563                            // of nasty edge cases: for example if we allowed a non-
8564                            // system update of the app to add a library, then uninstalling
8565                            // the update would make the library go away, and assumptions
8566                            // we made such as through app install filtering would now
8567                            // have allowed apps on the device which aren't compatible
8568                            // with it.  Better to just have the restriction here, be
8569                            // conservative, and create many fewer cases that can negatively
8570                            // impact the user experience.
8571                            final PackageSetting sysPs = mSettings
8572                                    .getDisabledSystemPkgLPr(pkg.packageName);
8573                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8574                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8575                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8576                                        allowed = true;
8577                                        break;
8578                                    }
8579                                }
8580                            }
8581                        } else {
8582                            allowed = true;
8583                        }
8584                        if (allowed) {
8585                            if (!mSharedLibraries.containsKey(name)) {
8586                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8587                            } else if (!name.equals(pkg.packageName)) {
8588                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8589                                        + name + " already exists; skipping");
8590                            }
8591                        } else {
8592                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8593                                    + name + " that is not declared on system image; skipping");
8594                        }
8595                    }
8596                    if ((scanFlags & SCAN_BOOTING) == 0) {
8597                        // If we are not booting, we need to update any applications
8598                        // that are clients of our shared library.  If we are booting,
8599                        // this will all be done once the scan is complete.
8600                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8601                    }
8602                }
8603            }
8604        }
8605
8606        if ((scanFlags & SCAN_BOOTING) != 0) {
8607            // No apps can run during boot scan, so they don't need to be frozen
8608        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8609            // Caller asked to not kill app, so it's probably not frozen
8610        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8611            // Caller asked us to ignore frozen check for some reason; they
8612            // probably didn't know the package name
8613        } else {
8614            // We're doing major surgery on this package, so it better be frozen
8615            // right now to keep it from launching
8616            checkPackageFrozen(pkgName);
8617        }
8618
8619        // Also need to kill any apps that are dependent on the library.
8620        if (clientLibPkgs != null) {
8621            for (int i=0; i<clientLibPkgs.size(); i++) {
8622                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8623                killApplication(clientPkg.applicationInfo.packageName,
8624                        clientPkg.applicationInfo.uid, "update lib");
8625            }
8626        }
8627
8628        // Make sure we're not adding any bogus keyset info
8629        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8630        ksms.assertScannedPackageValid(pkg);
8631
8632        // writer
8633        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8634
8635        boolean createIdmapFailed = false;
8636        synchronized (mPackages) {
8637            // We don't expect installation to fail beyond this point
8638
8639            if (pkgSetting.pkg != null) {
8640                // Note that |user| might be null during the initial boot scan. If a codePath
8641                // for an app has changed during a boot scan, it's due to an app update that's
8642                // part of the system partition and marker changes must be applied to all users.
8643                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8644                    (user != null) ? user : UserHandle.ALL);
8645            }
8646
8647            // Add the new setting to mSettings
8648            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8649            // Add the new setting to mPackages
8650            mPackages.put(pkg.applicationInfo.packageName, pkg);
8651            // Make sure we don't accidentally delete its data.
8652            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8653            while (iter.hasNext()) {
8654                PackageCleanItem item = iter.next();
8655                if (pkgName.equals(item.packageName)) {
8656                    iter.remove();
8657                }
8658            }
8659
8660            // Take care of first install / last update times.
8661            if (currentTime != 0) {
8662                if (pkgSetting.firstInstallTime == 0) {
8663                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8664                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8665                    pkgSetting.lastUpdateTime = currentTime;
8666                }
8667            } else if (pkgSetting.firstInstallTime == 0) {
8668                // We need *something*.  Take time time stamp of the file.
8669                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8670            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8671                if (scanFileTime != pkgSetting.timeStamp) {
8672                    // A package on the system image has changed; consider this
8673                    // to be an update.
8674                    pkgSetting.lastUpdateTime = scanFileTime;
8675                }
8676            }
8677
8678            // Add the package's KeySets to the global KeySetManagerService
8679            ksms.addScannedPackageLPw(pkg);
8680
8681            int N = pkg.providers.size();
8682            StringBuilder r = null;
8683            int i;
8684            for (i=0; i<N; i++) {
8685                PackageParser.Provider p = pkg.providers.get(i);
8686                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8687                        p.info.processName, pkg.applicationInfo.uid);
8688                mProviders.addProvider(p);
8689                p.syncable = p.info.isSyncable;
8690                if (p.info.authority != null) {
8691                    String names[] = p.info.authority.split(";");
8692                    p.info.authority = null;
8693                    for (int j = 0; j < names.length; j++) {
8694                        if (j == 1 && p.syncable) {
8695                            // We only want the first authority for a provider to possibly be
8696                            // syncable, so if we already added this provider using a different
8697                            // authority clear the syncable flag. We copy the provider before
8698                            // changing it because the mProviders object contains a reference
8699                            // to a provider that we don't want to change.
8700                            // Only do this for the second authority since the resulting provider
8701                            // object can be the same for all future authorities for this provider.
8702                            p = new PackageParser.Provider(p);
8703                            p.syncable = false;
8704                        }
8705                        if (!mProvidersByAuthority.containsKey(names[j])) {
8706                            mProvidersByAuthority.put(names[j], p);
8707                            if (p.info.authority == null) {
8708                                p.info.authority = names[j];
8709                            } else {
8710                                p.info.authority = p.info.authority + ";" + names[j];
8711                            }
8712                            if (DEBUG_PACKAGE_SCANNING) {
8713                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8714                                    Log.d(TAG, "Registered content provider: " + names[j]
8715                                            + ", className = " + p.info.name + ", isSyncable = "
8716                                            + p.info.isSyncable);
8717                            }
8718                        } else {
8719                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8720                            Slog.w(TAG, "Skipping provider name " + names[j] +
8721                                    " (in package " + pkg.applicationInfo.packageName +
8722                                    "): name already used by "
8723                                    + ((other != null && other.getComponentName() != null)
8724                                            ? other.getComponentName().getPackageName() : "?"));
8725                        }
8726                    }
8727                }
8728                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8729                    if (r == null) {
8730                        r = new StringBuilder(256);
8731                    } else {
8732                        r.append(' ');
8733                    }
8734                    r.append(p.info.name);
8735                }
8736            }
8737            if (r != null) {
8738                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8739            }
8740
8741            N = pkg.services.size();
8742            r = null;
8743            for (i=0; i<N; i++) {
8744                PackageParser.Service s = pkg.services.get(i);
8745                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8746                        s.info.processName, pkg.applicationInfo.uid);
8747                mServices.addService(s);
8748                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8749                    if (r == null) {
8750                        r = new StringBuilder(256);
8751                    } else {
8752                        r.append(' ');
8753                    }
8754                    r.append(s.info.name);
8755                }
8756            }
8757            if (r != null) {
8758                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8759            }
8760
8761            N = pkg.receivers.size();
8762            r = null;
8763            for (i=0; i<N; i++) {
8764                PackageParser.Activity a = pkg.receivers.get(i);
8765                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8766                        a.info.processName, pkg.applicationInfo.uid);
8767                mReceivers.addActivity(a, "receiver");
8768                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8769                    if (r == null) {
8770                        r = new StringBuilder(256);
8771                    } else {
8772                        r.append(' ');
8773                    }
8774                    r.append(a.info.name);
8775                }
8776            }
8777            if (r != null) {
8778                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8779            }
8780
8781            N = pkg.activities.size();
8782            r = null;
8783            for (i=0; i<N; i++) {
8784                PackageParser.Activity a = pkg.activities.get(i);
8785                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8786                        a.info.processName, pkg.applicationInfo.uid);
8787                mActivities.addActivity(a, "activity");
8788                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8789                    if (r == null) {
8790                        r = new StringBuilder(256);
8791                    } else {
8792                        r.append(' ');
8793                    }
8794                    r.append(a.info.name);
8795                }
8796            }
8797            if (r != null) {
8798                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8799            }
8800
8801            N = pkg.permissionGroups.size();
8802            r = null;
8803            for (i=0; i<N; i++) {
8804                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8805                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8806                final String curPackageName = cur == null ? null : cur.info.packageName;
8807                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8808                if (cur == null || isPackageUpdate) {
8809                    mPermissionGroups.put(pg.info.name, pg);
8810                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8811                        if (r == null) {
8812                            r = new StringBuilder(256);
8813                        } else {
8814                            r.append(' ');
8815                        }
8816                        if (isPackageUpdate) {
8817                            r.append("UPD:");
8818                        }
8819                        r.append(pg.info.name);
8820                    }
8821                } else {
8822                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8823                            + pg.info.packageName + " ignored: original from "
8824                            + cur.info.packageName);
8825                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8826                        if (r == null) {
8827                            r = new StringBuilder(256);
8828                        } else {
8829                            r.append(' ');
8830                        }
8831                        r.append("DUP:");
8832                        r.append(pg.info.name);
8833                    }
8834                }
8835            }
8836            if (r != null) {
8837                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8838            }
8839
8840            N = pkg.permissions.size();
8841            r = null;
8842            for (i=0; i<N; i++) {
8843                PackageParser.Permission p = pkg.permissions.get(i);
8844
8845                // Assume by default that we did not install this permission into the system.
8846                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8847
8848                // Now that permission groups have a special meaning, we ignore permission
8849                // groups for legacy apps to prevent unexpected behavior. In particular,
8850                // permissions for one app being granted to someone just becase they happen
8851                // to be in a group defined by another app (before this had no implications).
8852                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8853                    p.group = mPermissionGroups.get(p.info.group);
8854                    // Warn for a permission in an unknown group.
8855                    if (p.info.group != null && p.group == null) {
8856                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8857                                + p.info.packageName + " in an unknown group " + p.info.group);
8858                    }
8859                }
8860
8861                ArrayMap<String, BasePermission> permissionMap =
8862                        p.tree ? mSettings.mPermissionTrees
8863                                : mSettings.mPermissions;
8864                BasePermission bp = permissionMap.get(p.info.name);
8865
8866                // Allow system apps to redefine non-system permissions
8867                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8868                    final boolean currentOwnerIsSystem = (bp.perm != null
8869                            && isSystemApp(bp.perm.owner));
8870                    if (isSystemApp(p.owner)) {
8871                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8872                            // It's a built-in permission and no owner, take ownership now
8873                            bp.packageSetting = pkgSetting;
8874                            bp.perm = p;
8875                            bp.uid = pkg.applicationInfo.uid;
8876                            bp.sourcePackage = p.info.packageName;
8877                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8878                        } else if (!currentOwnerIsSystem) {
8879                            String msg = "New decl " + p.owner + " of permission  "
8880                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8881                            reportSettingsProblem(Log.WARN, msg);
8882                            bp = null;
8883                        }
8884                    }
8885                }
8886
8887                if (bp == null) {
8888                    bp = new BasePermission(p.info.name, p.info.packageName,
8889                            BasePermission.TYPE_NORMAL);
8890                    permissionMap.put(p.info.name, bp);
8891                }
8892
8893                if (bp.perm == null) {
8894                    if (bp.sourcePackage == null
8895                            || bp.sourcePackage.equals(p.info.packageName)) {
8896                        BasePermission tree = findPermissionTreeLP(p.info.name);
8897                        if (tree == null
8898                                || tree.sourcePackage.equals(p.info.packageName)) {
8899                            bp.packageSetting = pkgSetting;
8900                            bp.perm = p;
8901                            bp.uid = pkg.applicationInfo.uid;
8902                            bp.sourcePackage = p.info.packageName;
8903                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8904                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8905                                if (r == null) {
8906                                    r = new StringBuilder(256);
8907                                } else {
8908                                    r.append(' ');
8909                                }
8910                                r.append(p.info.name);
8911                            }
8912                        } else {
8913                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8914                                    + p.info.packageName + " ignored: base tree "
8915                                    + tree.name + " is from package "
8916                                    + tree.sourcePackage);
8917                        }
8918                    } else {
8919                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8920                                + p.info.packageName + " ignored: original from "
8921                                + bp.sourcePackage);
8922                    }
8923                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8924                    if (r == null) {
8925                        r = new StringBuilder(256);
8926                    } else {
8927                        r.append(' ');
8928                    }
8929                    r.append("DUP:");
8930                    r.append(p.info.name);
8931                }
8932                if (bp.perm == p) {
8933                    bp.protectionLevel = p.info.protectionLevel;
8934                }
8935            }
8936
8937            if (r != null) {
8938                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8939            }
8940
8941            N = pkg.instrumentation.size();
8942            r = null;
8943            for (i=0; i<N; i++) {
8944                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8945                a.info.packageName = pkg.applicationInfo.packageName;
8946                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8947                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8948                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8949                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8950                a.info.dataDir = pkg.applicationInfo.dataDir;
8951                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8952                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8953
8954                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8955                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8956                mInstrumentation.put(a.getComponentName(), a);
8957                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8958                    if (r == null) {
8959                        r = new StringBuilder(256);
8960                    } else {
8961                        r.append(' ');
8962                    }
8963                    r.append(a.info.name);
8964                }
8965            }
8966            if (r != null) {
8967                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8968            }
8969
8970            if (pkg.protectedBroadcasts != null) {
8971                N = pkg.protectedBroadcasts.size();
8972                for (i=0; i<N; i++) {
8973                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8974                }
8975            }
8976
8977            pkgSetting.setTimeStamp(scanFileTime);
8978
8979            // Create idmap files for pairs of (packages, overlay packages).
8980            // Note: "android", ie framework-res.apk, is handled by native layers.
8981            if (pkg.mOverlayTarget != null) {
8982                // This is an overlay package.
8983                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8984                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8985                        mOverlays.put(pkg.mOverlayTarget,
8986                                new ArrayMap<String, PackageParser.Package>());
8987                    }
8988                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8989                    map.put(pkg.packageName, pkg);
8990                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8991                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8992                        createIdmapFailed = true;
8993                    }
8994                }
8995            } else if (mOverlays.containsKey(pkg.packageName) &&
8996                    !pkg.packageName.equals("android")) {
8997                // This is a regular package, with one or more known overlay packages.
8998                createIdmapsForPackageLI(pkg);
8999            }
9000        }
9001
9002        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9003
9004        if (createIdmapFailed) {
9005            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9006                    "scanPackageLI failed to createIdmap");
9007        }
9008        return pkg;
9009    }
9010
9011    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9012            PackageParser.Package update, UserHandle user) {
9013        if (existing.applicationInfo == null || update.applicationInfo == null) {
9014            // This isn't due to an app installation.
9015            return;
9016        }
9017
9018        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9019        final File newCodePath = new File(update.applicationInfo.getCodePath());
9020
9021        // The codePath hasn't changed, so there's nothing for us to do.
9022        if (Objects.equals(oldCodePath, newCodePath)) {
9023            return;
9024        }
9025
9026        File canonicalNewCodePath;
9027        try {
9028            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9029        } catch (IOException e) {
9030            Slog.w(TAG, "Failed to get canonical path.", e);
9031            return;
9032        }
9033
9034        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9035        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9036        // that the last component of the path (i.e, the name) doesn't need canonicalization
9037        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9038        // but may change in the future. Hopefully this function won't exist at that point.
9039        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9040                oldCodePath.getName());
9041
9042        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9043        // with "@".
9044        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9045        if (!oldMarkerPrefix.endsWith("@")) {
9046            oldMarkerPrefix += "@";
9047        }
9048        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9049        if (!newMarkerPrefix.endsWith("@")) {
9050            newMarkerPrefix += "@";
9051        }
9052
9053        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9054        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9055        for (String updatedPath : updatedPaths) {
9056            String updatedPathName = new File(updatedPath).getName();
9057            markerSuffixes.add(updatedPathName.replace('/', '@'));
9058        }
9059
9060        for (int userId : resolveUserIds(user.getIdentifier())) {
9061            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9062
9063            for (String markerSuffix : markerSuffixes) {
9064                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9065                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9066                if (oldForeignUseMark.exists()) {
9067                    try {
9068                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9069                                newForeignUseMark.getAbsolutePath());
9070                    } catch (ErrnoException e) {
9071                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9072                        oldForeignUseMark.delete();
9073                    }
9074                }
9075            }
9076        }
9077    }
9078
9079    /**
9080     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9081     * is derived purely on the basis of the contents of {@code scanFile} and
9082     * {@code cpuAbiOverride}.
9083     *
9084     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9085     */
9086    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9087                                 String cpuAbiOverride, boolean extractLibs)
9088            throws PackageManagerException {
9089        // TODO: We can probably be smarter about this stuff. For installed apps,
9090        // we can calculate this information at install time once and for all. For
9091        // system apps, we can probably assume that this information doesn't change
9092        // after the first boot scan. As things stand, we do lots of unnecessary work.
9093
9094        // Give ourselves some initial paths; we'll come back for another
9095        // pass once we've determined ABI below.
9096        setNativeLibraryPaths(pkg);
9097
9098        // We would never need to extract libs for forward-locked and external packages,
9099        // since the container service will do it for us. We shouldn't attempt to
9100        // extract libs from system app when it was not updated.
9101        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9102                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9103            extractLibs = false;
9104        }
9105
9106        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9107        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9108
9109        NativeLibraryHelper.Handle handle = null;
9110        try {
9111            handle = NativeLibraryHelper.Handle.create(pkg);
9112            // TODO(multiArch): This can be null for apps that didn't go through the
9113            // usual installation process. We can calculate it again, like we
9114            // do during install time.
9115            //
9116            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9117            // unnecessary.
9118            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9119
9120            // Null out the abis so that they can be recalculated.
9121            pkg.applicationInfo.primaryCpuAbi = null;
9122            pkg.applicationInfo.secondaryCpuAbi = null;
9123            if (isMultiArch(pkg.applicationInfo)) {
9124                // Warn if we've set an abiOverride for multi-lib packages..
9125                // By definition, we need to copy both 32 and 64 bit libraries for
9126                // such packages.
9127                if (pkg.cpuAbiOverride != null
9128                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9129                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9130                }
9131
9132                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9133                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9134                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9135                    if (extractLibs) {
9136                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9137                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9138                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9139                                useIsaSpecificSubdirs);
9140                    } else {
9141                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9142                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9143                    }
9144                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9145                }
9146
9147                maybeThrowExceptionForMultiArchCopy(
9148                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9149
9150                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9151                    if (extractLibs) {
9152                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9153                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9154                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9155                                useIsaSpecificSubdirs);
9156                    } else {
9157                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9158                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9159                    }
9160                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9161                }
9162
9163                maybeThrowExceptionForMultiArchCopy(
9164                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9165
9166                if (abi64 >= 0) {
9167                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9168                }
9169
9170                if (abi32 >= 0) {
9171                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9172                    if (abi64 >= 0) {
9173                        if (pkg.use32bitAbi) {
9174                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9175                            pkg.applicationInfo.primaryCpuAbi = abi;
9176                        } else {
9177                            pkg.applicationInfo.secondaryCpuAbi = abi;
9178                        }
9179                    } else {
9180                        pkg.applicationInfo.primaryCpuAbi = abi;
9181                    }
9182                }
9183
9184            } else {
9185                String[] abiList = (cpuAbiOverride != null) ?
9186                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9187
9188                // Enable gross and lame hacks for apps that are built with old
9189                // SDK tools. We must scan their APKs for renderscript bitcode and
9190                // not launch them if it's present. Don't bother checking on devices
9191                // that don't have 64 bit support.
9192                boolean needsRenderScriptOverride = false;
9193                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9194                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9195                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9196                    needsRenderScriptOverride = true;
9197                }
9198
9199                final int copyRet;
9200                if (extractLibs) {
9201                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9202                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9203                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9204                } else {
9205                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9206                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9207                }
9208                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9209
9210                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9211                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9212                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9213                }
9214
9215                if (copyRet >= 0) {
9216                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9217                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9218                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9219                } else if (needsRenderScriptOverride) {
9220                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9221                }
9222            }
9223        } catch (IOException ioe) {
9224            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9225        } finally {
9226            IoUtils.closeQuietly(handle);
9227        }
9228
9229        // Now that we've calculated the ABIs and determined if it's an internal app,
9230        // we will go ahead and populate the nativeLibraryPath.
9231        setNativeLibraryPaths(pkg);
9232    }
9233
9234    /**
9235     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9236     * i.e, so that all packages can be run inside a single process if required.
9237     *
9238     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9239     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9240     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9241     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9242     * updating a package that belongs to a shared user.
9243     *
9244     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9245     * adds unnecessary complexity.
9246     */
9247    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9248            PackageParser.Package scannedPackage, boolean bootComplete) {
9249        String requiredInstructionSet = null;
9250        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9251            requiredInstructionSet = VMRuntime.getInstructionSet(
9252                     scannedPackage.applicationInfo.primaryCpuAbi);
9253        }
9254
9255        PackageSetting requirer = null;
9256        for (PackageSetting ps : packagesForUser) {
9257            // If packagesForUser contains scannedPackage, we skip it. This will happen
9258            // when scannedPackage is an update of an existing package. Without this check,
9259            // we will never be able to change the ABI of any package belonging to a shared
9260            // user, even if it's compatible with other packages.
9261            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9262                if (ps.primaryCpuAbiString == null) {
9263                    continue;
9264                }
9265
9266                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9267                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9268                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9269                    // this but there's not much we can do.
9270                    String errorMessage = "Instruction set mismatch, "
9271                            + ((requirer == null) ? "[caller]" : requirer)
9272                            + " requires " + requiredInstructionSet + " whereas " + ps
9273                            + " requires " + instructionSet;
9274                    Slog.w(TAG, errorMessage);
9275                }
9276
9277                if (requiredInstructionSet == null) {
9278                    requiredInstructionSet = instructionSet;
9279                    requirer = ps;
9280                }
9281            }
9282        }
9283
9284        if (requiredInstructionSet != null) {
9285            String adjustedAbi;
9286            if (requirer != null) {
9287                // requirer != null implies that either scannedPackage was null or that scannedPackage
9288                // did not require an ABI, in which case we have to adjust scannedPackage to match
9289                // the ABI of the set (which is the same as requirer's ABI)
9290                adjustedAbi = requirer.primaryCpuAbiString;
9291                if (scannedPackage != null) {
9292                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9293                }
9294            } else {
9295                // requirer == null implies that we're updating all ABIs in the set to
9296                // match scannedPackage.
9297                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9298            }
9299
9300            for (PackageSetting ps : packagesForUser) {
9301                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9302                    if (ps.primaryCpuAbiString != null) {
9303                        continue;
9304                    }
9305
9306                    ps.primaryCpuAbiString = adjustedAbi;
9307                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9308                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9309                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9310                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9311                                + " (requirer="
9312                                + (requirer == null ? "null" : requirer.pkg.packageName)
9313                                + ", scannedPackage="
9314                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9315                                + ")");
9316                        try {
9317                            mInstaller.rmdex(ps.codePathString,
9318                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9319                        } catch (InstallerException ignored) {
9320                        }
9321                    }
9322                }
9323            }
9324        }
9325    }
9326
9327    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9328        synchronized (mPackages) {
9329            mResolverReplaced = true;
9330            // Set up information for custom user intent resolution activity.
9331            mResolveActivity.applicationInfo = pkg.applicationInfo;
9332            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9333            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9334            mResolveActivity.processName = pkg.applicationInfo.packageName;
9335            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9336            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9337                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9338            mResolveActivity.theme = 0;
9339            mResolveActivity.exported = true;
9340            mResolveActivity.enabled = true;
9341            mResolveInfo.activityInfo = mResolveActivity;
9342            mResolveInfo.priority = 0;
9343            mResolveInfo.preferredOrder = 0;
9344            mResolveInfo.match = 0;
9345            mResolveComponentName = mCustomResolverComponentName;
9346            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9347                    mResolveComponentName);
9348        }
9349    }
9350
9351    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9352        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9353
9354        // Set up information for ephemeral installer activity
9355        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9356        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9357        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9358        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9359        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9360        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9361                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9362        mEphemeralInstallerActivity.theme = 0;
9363        mEphemeralInstallerActivity.exported = true;
9364        mEphemeralInstallerActivity.enabled = true;
9365        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9366        mEphemeralInstallerInfo.priority = 0;
9367        mEphemeralInstallerInfo.preferredOrder = 1;
9368        mEphemeralInstallerInfo.isDefault = true;
9369        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9370                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9371
9372        if (DEBUG_EPHEMERAL) {
9373            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9374        }
9375    }
9376
9377    private static String calculateBundledApkRoot(final String codePathString) {
9378        final File codePath = new File(codePathString);
9379        final File codeRoot;
9380        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9381            codeRoot = Environment.getRootDirectory();
9382        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9383            codeRoot = Environment.getOemDirectory();
9384        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9385            codeRoot = Environment.getVendorDirectory();
9386        } else {
9387            // Unrecognized code path; take its top real segment as the apk root:
9388            // e.g. /something/app/blah.apk => /something
9389            try {
9390                File f = codePath.getCanonicalFile();
9391                File parent = f.getParentFile();    // non-null because codePath is a file
9392                File tmp;
9393                while ((tmp = parent.getParentFile()) != null) {
9394                    f = parent;
9395                    parent = tmp;
9396                }
9397                codeRoot = f;
9398                Slog.w(TAG, "Unrecognized code path "
9399                        + codePath + " - using " + codeRoot);
9400            } catch (IOException e) {
9401                // Can't canonicalize the code path -- shenanigans?
9402                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9403                return Environment.getRootDirectory().getPath();
9404            }
9405        }
9406        return codeRoot.getPath();
9407    }
9408
9409    /**
9410     * Derive and set the location of native libraries for the given package,
9411     * which varies depending on where and how the package was installed.
9412     */
9413    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9414        final ApplicationInfo info = pkg.applicationInfo;
9415        final String codePath = pkg.codePath;
9416        final File codeFile = new File(codePath);
9417        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9418        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9419
9420        info.nativeLibraryRootDir = null;
9421        info.nativeLibraryRootRequiresIsa = false;
9422        info.nativeLibraryDir = null;
9423        info.secondaryNativeLibraryDir = null;
9424
9425        if (isApkFile(codeFile)) {
9426            // Monolithic install
9427            if (bundledApp) {
9428                // If "/system/lib64/apkname" exists, assume that is the per-package
9429                // native library directory to use; otherwise use "/system/lib/apkname".
9430                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9431                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9432                        getPrimaryInstructionSet(info));
9433
9434                // This is a bundled system app so choose the path based on the ABI.
9435                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9436                // is just the default path.
9437                final String apkName = deriveCodePathName(codePath);
9438                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9439                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9440                        apkName).getAbsolutePath();
9441
9442                if (info.secondaryCpuAbi != null) {
9443                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9444                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9445                            secondaryLibDir, apkName).getAbsolutePath();
9446                }
9447            } else if (asecApp) {
9448                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9449                        .getAbsolutePath();
9450            } else {
9451                final String apkName = deriveCodePathName(codePath);
9452                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9453                        .getAbsolutePath();
9454            }
9455
9456            info.nativeLibraryRootRequiresIsa = false;
9457            info.nativeLibraryDir = info.nativeLibraryRootDir;
9458        } else {
9459            // Cluster install
9460            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9461            info.nativeLibraryRootRequiresIsa = true;
9462
9463            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9464                    getPrimaryInstructionSet(info)).getAbsolutePath();
9465
9466            if (info.secondaryCpuAbi != null) {
9467                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9468                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9469            }
9470        }
9471    }
9472
9473    /**
9474     * Calculate the abis and roots for a bundled app. These can uniquely
9475     * be determined from the contents of the system partition, i.e whether
9476     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9477     * of this information, and instead assume that the system was built
9478     * sensibly.
9479     */
9480    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9481                                           PackageSetting pkgSetting) {
9482        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9483
9484        // If "/system/lib64/apkname" exists, assume that is the per-package
9485        // native library directory to use; otherwise use "/system/lib/apkname".
9486        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9487        setBundledAppAbi(pkg, apkRoot, apkName);
9488        // pkgSetting might be null during rescan following uninstall of updates
9489        // to a bundled app, so accommodate that possibility.  The settings in
9490        // that case will be established later from the parsed package.
9491        //
9492        // If the settings aren't null, sync them up with what we've just derived.
9493        // note that apkRoot isn't stored in the package settings.
9494        if (pkgSetting != null) {
9495            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9496            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9497        }
9498    }
9499
9500    /**
9501     * Deduces the ABI of a bundled app and sets the relevant fields on the
9502     * parsed pkg object.
9503     *
9504     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9505     *        under which system libraries are installed.
9506     * @param apkName the name of the installed package.
9507     */
9508    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9509        final File codeFile = new File(pkg.codePath);
9510
9511        final boolean has64BitLibs;
9512        final boolean has32BitLibs;
9513        if (isApkFile(codeFile)) {
9514            // Monolithic install
9515            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9516            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9517        } else {
9518            // Cluster install
9519            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9520            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9521                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9522                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9523                has64BitLibs = (new File(rootDir, isa)).exists();
9524            } else {
9525                has64BitLibs = false;
9526            }
9527            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9528                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9529                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9530                has32BitLibs = (new File(rootDir, isa)).exists();
9531            } else {
9532                has32BitLibs = false;
9533            }
9534        }
9535
9536        if (has64BitLibs && !has32BitLibs) {
9537            // The package has 64 bit libs, but not 32 bit libs. Its primary
9538            // ABI should be 64 bit. We can safely assume here that the bundled
9539            // native libraries correspond to the most preferred ABI in the list.
9540
9541            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9542            pkg.applicationInfo.secondaryCpuAbi = null;
9543        } else if (has32BitLibs && !has64BitLibs) {
9544            // The package has 32 bit libs but not 64 bit libs. Its primary
9545            // ABI should be 32 bit.
9546
9547            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9548            pkg.applicationInfo.secondaryCpuAbi = null;
9549        } else if (has32BitLibs && has64BitLibs) {
9550            // The application has both 64 and 32 bit bundled libraries. We check
9551            // here that the app declares multiArch support, and warn if it doesn't.
9552            //
9553            // We will be lenient here and record both ABIs. The primary will be the
9554            // ABI that's higher on the list, i.e, a device that's configured to prefer
9555            // 64 bit apps will see a 64 bit primary ABI,
9556
9557            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9558                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9559            }
9560
9561            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9562                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9563                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9564            } else {
9565                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9566                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9567            }
9568        } else {
9569            pkg.applicationInfo.primaryCpuAbi = null;
9570            pkg.applicationInfo.secondaryCpuAbi = null;
9571        }
9572    }
9573
9574    private void killApplication(String pkgName, int appId, String reason) {
9575        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9576    }
9577
9578    private void killApplication(String pkgName, int appId, int userId, String reason) {
9579        // Request the ActivityManager to kill the process(only for existing packages)
9580        // so that we do not end up in a confused state while the user is still using the older
9581        // version of the application while the new one gets installed.
9582        final long token = Binder.clearCallingIdentity();
9583        try {
9584            IActivityManager am = ActivityManagerNative.getDefault();
9585            if (am != null) {
9586                try {
9587                    am.killApplication(pkgName, appId, userId, reason);
9588                } catch (RemoteException e) {
9589                }
9590            }
9591        } finally {
9592            Binder.restoreCallingIdentity(token);
9593        }
9594    }
9595
9596    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9597        // Remove the parent package setting
9598        PackageSetting ps = (PackageSetting) pkg.mExtras;
9599        if (ps != null) {
9600            removePackageLI(ps, chatty);
9601        }
9602        // Remove the child package setting
9603        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9604        for (int i = 0; i < childCount; i++) {
9605            PackageParser.Package childPkg = pkg.childPackages.get(i);
9606            ps = (PackageSetting) childPkg.mExtras;
9607            if (ps != null) {
9608                removePackageLI(ps, chatty);
9609            }
9610        }
9611    }
9612
9613    void removePackageLI(PackageSetting ps, boolean chatty) {
9614        if (DEBUG_INSTALL) {
9615            if (chatty)
9616                Log.d(TAG, "Removing package " + ps.name);
9617        }
9618
9619        // writer
9620        synchronized (mPackages) {
9621            mPackages.remove(ps.name);
9622            final PackageParser.Package pkg = ps.pkg;
9623            if (pkg != null) {
9624                cleanPackageDataStructuresLILPw(pkg, chatty);
9625            }
9626        }
9627    }
9628
9629    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9630        if (DEBUG_INSTALL) {
9631            if (chatty)
9632                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9633        }
9634
9635        // writer
9636        synchronized (mPackages) {
9637            // Remove the parent package
9638            mPackages.remove(pkg.applicationInfo.packageName);
9639            cleanPackageDataStructuresLILPw(pkg, chatty);
9640
9641            // Remove the child packages
9642            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9643            for (int i = 0; i < childCount; i++) {
9644                PackageParser.Package childPkg = pkg.childPackages.get(i);
9645                mPackages.remove(childPkg.applicationInfo.packageName);
9646                cleanPackageDataStructuresLILPw(childPkg, chatty);
9647            }
9648        }
9649    }
9650
9651    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9652        int N = pkg.providers.size();
9653        StringBuilder r = null;
9654        int i;
9655        for (i=0; i<N; i++) {
9656            PackageParser.Provider p = pkg.providers.get(i);
9657            mProviders.removeProvider(p);
9658            if (p.info.authority == null) {
9659
9660                /* There was another ContentProvider with this authority when
9661                 * this app was installed so this authority is null,
9662                 * Ignore it as we don't have to unregister the provider.
9663                 */
9664                continue;
9665            }
9666            String names[] = p.info.authority.split(";");
9667            for (int j = 0; j < names.length; j++) {
9668                if (mProvidersByAuthority.get(names[j]) == p) {
9669                    mProvidersByAuthority.remove(names[j]);
9670                    if (DEBUG_REMOVE) {
9671                        if (chatty)
9672                            Log.d(TAG, "Unregistered content provider: " + names[j]
9673                                    + ", className = " + p.info.name + ", isSyncable = "
9674                                    + p.info.isSyncable);
9675                    }
9676                }
9677            }
9678            if (DEBUG_REMOVE && chatty) {
9679                if (r == null) {
9680                    r = new StringBuilder(256);
9681                } else {
9682                    r.append(' ');
9683                }
9684                r.append(p.info.name);
9685            }
9686        }
9687        if (r != null) {
9688            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9689        }
9690
9691        N = pkg.services.size();
9692        r = null;
9693        for (i=0; i<N; i++) {
9694            PackageParser.Service s = pkg.services.get(i);
9695            mServices.removeService(s);
9696            if (chatty) {
9697                if (r == null) {
9698                    r = new StringBuilder(256);
9699                } else {
9700                    r.append(' ');
9701                }
9702                r.append(s.info.name);
9703            }
9704        }
9705        if (r != null) {
9706            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9707        }
9708
9709        N = pkg.receivers.size();
9710        r = null;
9711        for (i=0; i<N; i++) {
9712            PackageParser.Activity a = pkg.receivers.get(i);
9713            mReceivers.removeActivity(a, "receiver");
9714            if (DEBUG_REMOVE && chatty) {
9715                if (r == null) {
9716                    r = new StringBuilder(256);
9717                } else {
9718                    r.append(' ');
9719                }
9720                r.append(a.info.name);
9721            }
9722        }
9723        if (r != null) {
9724            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9725        }
9726
9727        N = pkg.activities.size();
9728        r = null;
9729        for (i=0; i<N; i++) {
9730            PackageParser.Activity a = pkg.activities.get(i);
9731            mActivities.removeActivity(a, "activity");
9732            if (DEBUG_REMOVE && chatty) {
9733                if (r == null) {
9734                    r = new StringBuilder(256);
9735                } else {
9736                    r.append(' ');
9737                }
9738                r.append(a.info.name);
9739            }
9740        }
9741        if (r != null) {
9742            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9743        }
9744
9745        N = pkg.permissions.size();
9746        r = null;
9747        for (i=0; i<N; i++) {
9748            PackageParser.Permission p = pkg.permissions.get(i);
9749            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9750            if (bp == null) {
9751                bp = mSettings.mPermissionTrees.get(p.info.name);
9752            }
9753            if (bp != null && bp.perm == p) {
9754                bp.perm = null;
9755                if (DEBUG_REMOVE && chatty) {
9756                    if (r == null) {
9757                        r = new StringBuilder(256);
9758                    } else {
9759                        r.append(' ');
9760                    }
9761                    r.append(p.info.name);
9762                }
9763            }
9764            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9765                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9766                if (appOpPkgs != null) {
9767                    appOpPkgs.remove(pkg.packageName);
9768                }
9769            }
9770        }
9771        if (r != null) {
9772            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9773        }
9774
9775        N = pkg.requestedPermissions.size();
9776        r = null;
9777        for (i=0; i<N; i++) {
9778            String perm = pkg.requestedPermissions.get(i);
9779            BasePermission bp = mSettings.mPermissions.get(perm);
9780            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9781                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9782                if (appOpPkgs != null) {
9783                    appOpPkgs.remove(pkg.packageName);
9784                    if (appOpPkgs.isEmpty()) {
9785                        mAppOpPermissionPackages.remove(perm);
9786                    }
9787                }
9788            }
9789        }
9790        if (r != null) {
9791            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9792        }
9793
9794        N = pkg.instrumentation.size();
9795        r = null;
9796        for (i=0; i<N; i++) {
9797            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9798            mInstrumentation.remove(a.getComponentName());
9799            if (DEBUG_REMOVE && chatty) {
9800                if (r == null) {
9801                    r = new StringBuilder(256);
9802                } else {
9803                    r.append(' ');
9804                }
9805                r.append(a.info.name);
9806            }
9807        }
9808        if (r != null) {
9809            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9810        }
9811
9812        r = null;
9813        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9814            // Only system apps can hold shared libraries.
9815            if (pkg.libraryNames != null) {
9816                for (i=0; i<pkg.libraryNames.size(); i++) {
9817                    String name = pkg.libraryNames.get(i);
9818                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9819                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9820                        mSharedLibraries.remove(name);
9821                        if (DEBUG_REMOVE && chatty) {
9822                            if (r == null) {
9823                                r = new StringBuilder(256);
9824                            } else {
9825                                r.append(' ');
9826                            }
9827                            r.append(name);
9828                        }
9829                    }
9830                }
9831            }
9832        }
9833        if (r != null) {
9834            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9835        }
9836    }
9837
9838    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9839        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9840            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9841                return true;
9842            }
9843        }
9844        return false;
9845    }
9846
9847    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9848    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9849    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9850
9851    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9852        // Update the parent permissions
9853        updatePermissionsLPw(pkg.packageName, pkg, flags);
9854        // Update the child permissions
9855        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9856        for (int i = 0; i < childCount; i++) {
9857            PackageParser.Package childPkg = pkg.childPackages.get(i);
9858            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9859        }
9860    }
9861
9862    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9863            int flags) {
9864        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9865        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9866    }
9867
9868    private void updatePermissionsLPw(String changingPkg,
9869            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9870        // Make sure there are no dangling permission trees.
9871        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9872        while (it.hasNext()) {
9873            final BasePermission bp = it.next();
9874            if (bp.packageSetting == null) {
9875                // We may not yet have parsed the package, so just see if
9876                // we still know about its settings.
9877                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9878            }
9879            if (bp.packageSetting == null) {
9880                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9881                        + " from package " + bp.sourcePackage);
9882                it.remove();
9883            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9884                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9885                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9886                            + " from package " + bp.sourcePackage);
9887                    flags |= UPDATE_PERMISSIONS_ALL;
9888                    it.remove();
9889                }
9890            }
9891        }
9892
9893        // Make sure all dynamic permissions have been assigned to a package,
9894        // and make sure there are no dangling permissions.
9895        it = mSettings.mPermissions.values().iterator();
9896        while (it.hasNext()) {
9897            final BasePermission bp = it.next();
9898            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9899                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9900                        + bp.name + " pkg=" + bp.sourcePackage
9901                        + " info=" + bp.pendingInfo);
9902                if (bp.packageSetting == null && bp.pendingInfo != null) {
9903                    final BasePermission tree = findPermissionTreeLP(bp.name);
9904                    if (tree != null && tree.perm != null) {
9905                        bp.packageSetting = tree.packageSetting;
9906                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9907                                new PermissionInfo(bp.pendingInfo));
9908                        bp.perm.info.packageName = tree.perm.info.packageName;
9909                        bp.perm.info.name = bp.name;
9910                        bp.uid = tree.uid;
9911                    }
9912                }
9913            }
9914            if (bp.packageSetting == null) {
9915                // We may not yet have parsed the package, so just see if
9916                // we still know about its settings.
9917                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9918            }
9919            if (bp.packageSetting == null) {
9920                Slog.w(TAG, "Removing dangling permission: " + bp.name
9921                        + " from package " + bp.sourcePackage);
9922                it.remove();
9923            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9924                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9925                    Slog.i(TAG, "Removing old permission: " + bp.name
9926                            + " from package " + bp.sourcePackage);
9927                    flags |= UPDATE_PERMISSIONS_ALL;
9928                    it.remove();
9929                }
9930            }
9931        }
9932
9933        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9934        // Now update the permissions for all packages, in particular
9935        // replace the granted permissions of the system packages.
9936        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9937            for (PackageParser.Package pkg : mPackages.values()) {
9938                if (pkg != pkgInfo) {
9939                    // Only replace for packages on requested volume
9940                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9941                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9942                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9943                    grantPermissionsLPw(pkg, replace, changingPkg);
9944                }
9945            }
9946        }
9947
9948        if (pkgInfo != null) {
9949            // Only replace for packages on requested volume
9950            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9951            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9952                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9953            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9954        }
9955        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9956    }
9957
9958    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9959            String packageOfInterest) {
9960        // IMPORTANT: There are two types of permissions: install and runtime.
9961        // Install time permissions are granted when the app is installed to
9962        // all device users and users added in the future. Runtime permissions
9963        // are granted at runtime explicitly to specific users. Normal and signature
9964        // protected permissions are install time permissions. Dangerous permissions
9965        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9966        // otherwise they are runtime permissions. This function does not manage
9967        // runtime permissions except for the case an app targeting Lollipop MR1
9968        // being upgraded to target a newer SDK, in which case dangerous permissions
9969        // are transformed from install time to runtime ones.
9970
9971        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9972        if (ps == null) {
9973            return;
9974        }
9975
9976        PermissionsState permissionsState = ps.getPermissionsState();
9977        PermissionsState origPermissions = permissionsState;
9978
9979        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9980
9981        boolean runtimePermissionsRevoked = false;
9982        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9983
9984        boolean changedInstallPermission = false;
9985
9986        if (replace) {
9987            ps.installPermissionsFixed = false;
9988            if (!ps.isSharedUser()) {
9989                origPermissions = new PermissionsState(permissionsState);
9990                permissionsState.reset();
9991            } else {
9992                // We need to know only about runtime permission changes since the
9993                // calling code always writes the install permissions state but
9994                // the runtime ones are written only if changed. The only cases of
9995                // changed runtime permissions here are promotion of an install to
9996                // runtime and revocation of a runtime from a shared user.
9997                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9998                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9999                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10000                    runtimePermissionsRevoked = true;
10001                }
10002            }
10003        }
10004
10005        permissionsState.setGlobalGids(mGlobalGids);
10006
10007        final int N = pkg.requestedPermissions.size();
10008        for (int i=0; i<N; i++) {
10009            final String name = pkg.requestedPermissions.get(i);
10010            final BasePermission bp = mSettings.mPermissions.get(name);
10011
10012            if (DEBUG_INSTALL) {
10013                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10014            }
10015
10016            if (bp == null || bp.packageSetting == null) {
10017                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10018                    Slog.w(TAG, "Unknown permission " + name
10019                            + " in package " + pkg.packageName);
10020                }
10021                continue;
10022            }
10023
10024            final String perm = bp.name;
10025            boolean allowedSig = false;
10026            int grant = GRANT_DENIED;
10027
10028            // Keep track of app op permissions.
10029            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10030                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10031                if (pkgs == null) {
10032                    pkgs = new ArraySet<>();
10033                    mAppOpPermissionPackages.put(bp.name, pkgs);
10034                }
10035                pkgs.add(pkg.packageName);
10036            }
10037
10038            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10039            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10040                    >= Build.VERSION_CODES.M;
10041            switch (level) {
10042                case PermissionInfo.PROTECTION_NORMAL: {
10043                    // For all apps normal permissions are install time ones.
10044                    grant = GRANT_INSTALL;
10045                } break;
10046
10047                case PermissionInfo.PROTECTION_DANGEROUS: {
10048                    // If a permission review is required for legacy apps we represent
10049                    // their permissions as always granted runtime ones since we need
10050                    // to keep the review required permission flag per user while an
10051                    // install permission's state is shared across all users.
10052                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
10053                        // For legacy apps dangerous permissions are install time ones.
10054                        grant = GRANT_INSTALL;
10055                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10056                        // For legacy apps that became modern, install becomes runtime.
10057                        grant = GRANT_UPGRADE;
10058                    } else if (mPromoteSystemApps
10059                            && isSystemApp(ps)
10060                            && mExistingSystemPackages.contains(ps.name)) {
10061                        // For legacy system apps, install becomes runtime.
10062                        // We cannot check hasInstallPermission() for system apps since those
10063                        // permissions were granted implicitly and not persisted pre-M.
10064                        grant = GRANT_UPGRADE;
10065                    } else {
10066                        // For modern apps keep runtime permissions unchanged.
10067                        grant = GRANT_RUNTIME;
10068                    }
10069                } break;
10070
10071                case PermissionInfo.PROTECTION_SIGNATURE: {
10072                    // For all apps signature permissions are install time ones.
10073                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10074                    if (allowedSig) {
10075                        grant = GRANT_INSTALL;
10076                    }
10077                } break;
10078            }
10079
10080            if (DEBUG_INSTALL) {
10081                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10082            }
10083
10084            if (grant != GRANT_DENIED) {
10085                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10086                    // If this is an existing, non-system package, then
10087                    // we can't add any new permissions to it.
10088                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10089                        // Except...  if this is a permission that was added
10090                        // to the platform (note: need to only do this when
10091                        // updating the platform).
10092                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10093                            grant = GRANT_DENIED;
10094                        }
10095                    }
10096                }
10097
10098                switch (grant) {
10099                    case GRANT_INSTALL: {
10100                        // Revoke this as runtime permission to handle the case of
10101                        // a runtime permission being downgraded to an install one.
10102                        // Also in permission review mode we keep dangerous permissions
10103                        // for legacy apps
10104                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10105                            if (origPermissions.getRuntimePermissionState(
10106                                    bp.name, userId) != null) {
10107                                // Revoke the runtime permission and clear the flags.
10108                                origPermissions.revokeRuntimePermission(bp, userId);
10109                                origPermissions.updatePermissionFlags(bp, userId,
10110                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10111                                // If we revoked a permission permission, we have to write.
10112                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10113                                        changedRuntimePermissionUserIds, userId);
10114                            }
10115                        }
10116                        // Grant an install permission.
10117                        if (permissionsState.grantInstallPermission(bp) !=
10118                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10119                            changedInstallPermission = true;
10120                        }
10121                    } break;
10122
10123                    case GRANT_RUNTIME: {
10124                        // Grant previously granted runtime permissions.
10125                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10126                            PermissionState permissionState = origPermissions
10127                                    .getRuntimePermissionState(bp.name, userId);
10128                            int flags = permissionState != null
10129                                    ? permissionState.getFlags() : 0;
10130                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10131                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10132                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10133                                    // If we cannot put the permission as it was, we have to write.
10134                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10135                                            changedRuntimePermissionUserIds, userId);
10136                                }
10137                                // If the app supports runtime permissions no need for a review.
10138                                if (mPermissionReviewRequired
10139                                        && appSupportsRuntimePermissions
10140                                        && (flags & PackageManager
10141                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10142                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10143                                    // Since we changed the flags, we have to write.
10144                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10145                                            changedRuntimePermissionUserIds, userId);
10146                                }
10147                            } else if (mPermissionReviewRequired
10148                                    && !appSupportsRuntimePermissions) {
10149                                // For legacy apps that need a permission review, every new
10150                                // runtime permission is granted but it is pending a review.
10151                                // We also need to review only platform defined runtime
10152                                // permissions as these are the only ones the platform knows
10153                                // how to disable the API to simulate revocation as legacy
10154                                // apps don't expect to run with revoked permissions.
10155                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10156                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10157                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10158                                        // We changed the flags, hence have to write.
10159                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10160                                                changedRuntimePermissionUserIds, userId);
10161                                    }
10162                                }
10163                                if (permissionsState.grantRuntimePermission(bp, userId)
10164                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10165                                    // We changed the permission, hence have to write.
10166                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10167                                            changedRuntimePermissionUserIds, userId);
10168                                }
10169                            }
10170                            // Propagate the permission flags.
10171                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10172                        }
10173                    } break;
10174
10175                    case GRANT_UPGRADE: {
10176                        // Grant runtime permissions for a previously held install permission.
10177                        PermissionState permissionState = origPermissions
10178                                .getInstallPermissionState(bp.name);
10179                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10180
10181                        if (origPermissions.revokeInstallPermission(bp)
10182                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10183                            // We will be transferring the permission flags, so clear them.
10184                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10185                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10186                            changedInstallPermission = true;
10187                        }
10188
10189                        // If the permission is not to be promoted to runtime we ignore it and
10190                        // also its other flags as they are not applicable to install permissions.
10191                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10192                            for (int userId : currentUserIds) {
10193                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10194                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10195                                    // Transfer the permission flags.
10196                                    permissionsState.updatePermissionFlags(bp, userId,
10197                                            flags, flags);
10198                                    // If we granted the permission, we have to write.
10199                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10200                                            changedRuntimePermissionUserIds, userId);
10201                                }
10202                            }
10203                        }
10204                    } break;
10205
10206                    default: {
10207                        if (packageOfInterest == null
10208                                || packageOfInterest.equals(pkg.packageName)) {
10209                            Slog.w(TAG, "Not granting permission " + perm
10210                                    + " to package " + pkg.packageName
10211                                    + " because it was previously installed without");
10212                        }
10213                    } break;
10214                }
10215            } else {
10216                if (permissionsState.revokeInstallPermission(bp) !=
10217                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10218                    // Also drop the permission flags.
10219                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10220                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10221                    changedInstallPermission = true;
10222                    Slog.i(TAG, "Un-granting permission " + perm
10223                            + " from package " + pkg.packageName
10224                            + " (protectionLevel=" + bp.protectionLevel
10225                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10226                            + ")");
10227                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10228                    // Don't print warning for app op permissions, since it is fine for them
10229                    // not to be granted, there is a UI for the user to decide.
10230                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10231                        Slog.w(TAG, "Not granting permission " + perm
10232                                + " to package " + pkg.packageName
10233                                + " (protectionLevel=" + bp.protectionLevel
10234                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10235                                + ")");
10236                    }
10237                }
10238            }
10239        }
10240
10241        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10242                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10243            // This is the first that we have heard about this package, so the
10244            // permissions we have now selected are fixed until explicitly
10245            // changed.
10246            ps.installPermissionsFixed = true;
10247        }
10248
10249        // Persist the runtime permissions state for users with changes. If permissions
10250        // were revoked because no app in the shared user declares them we have to
10251        // write synchronously to avoid losing runtime permissions state.
10252        for (int userId : changedRuntimePermissionUserIds) {
10253            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10254        }
10255    }
10256
10257    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10258        boolean allowed = false;
10259        final int NP = PackageParser.NEW_PERMISSIONS.length;
10260        for (int ip=0; ip<NP; ip++) {
10261            final PackageParser.NewPermissionInfo npi
10262                    = PackageParser.NEW_PERMISSIONS[ip];
10263            if (npi.name.equals(perm)
10264                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10265                allowed = true;
10266                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10267                        + pkg.packageName);
10268                break;
10269            }
10270        }
10271        return allowed;
10272    }
10273
10274    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10275            BasePermission bp, PermissionsState origPermissions) {
10276        boolean allowed;
10277        allowed = (compareSignatures(
10278                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10279                        == PackageManager.SIGNATURE_MATCH)
10280                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10281                        == PackageManager.SIGNATURE_MATCH);
10282        if (!allowed && (bp.protectionLevel
10283                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10284            if (isSystemApp(pkg)) {
10285                // For updated system applications, a system permission
10286                // is granted only if it had been defined by the original application.
10287                if (pkg.isUpdatedSystemApp()) {
10288                    final PackageSetting sysPs = mSettings
10289                            .getDisabledSystemPkgLPr(pkg.packageName);
10290                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10291                        // If the original was granted this permission, we take
10292                        // that grant decision as read and propagate it to the
10293                        // update.
10294                        if (sysPs.isPrivileged()) {
10295                            allowed = true;
10296                        }
10297                    } else {
10298                        // The system apk may have been updated with an older
10299                        // version of the one on the data partition, but which
10300                        // granted a new system permission that it didn't have
10301                        // before.  In this case we do want to allow the app to
10302                        // now get the new permission if the ancestral apk is
10303                        // privileged to get it.
10304                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10305                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10306                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10307                                    allowed = true;
10308                                    break;
10309                                }
10310                            }
10311                        }
10312                        // Also if a privileged parent package on the system image or any of
10313                        // its children requested a privileged permission, the updated child
10314                        // packages can also get the permission.
10315                        if (pkg.parentPackage != null) {
10316                            final PackageSetting disabledSysParentPs = mSettings
10317                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10318                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10319                                    && disabledSysParentPs.isPrivileged()) {
10320                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10321                                    allowed = true;
10322                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10323                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10324                                    for (int i = 0; i < count; i++) {
10325                                        PackageParser.Package disabledSysChildPkg =
10326                                                disabledSysParentPs.pkg.childPackages.get(i);
10327                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10328                                                perm)) {
10329                                            allowed = true;
10330                                            break;
10331                                        }
10332                                    }
10333                                }
10334                            }
10335                        }
10336                    }
10337                } else {
10338                    allowed = isPrivilegedApp(pkg);
10339                }
10340            }
10341        }
10342        if (!allowed) {
10343            if (!allowed && (bp.protectionLevel
10344                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10345                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10346                // If this was a previously normal/dangerous permission that got moved
10347                // to a system permission as part of the runtime permission redesign, then
10348                // we still want to blindly grant it to old apps.
10349                allowed = true;
10350            }
10351            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10352                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10353                // If this permission is to be granted to the system installer and
10354                // this app is an installer, then it gets the permission.
10355                allowed = true;
10356            }
10357            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10358                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10359                // If this permission is to be granted to the system verifier and
10360                // this app is a verifier, then it gets the permission.
10361                allowed = true;
10362            }
10363            if (!allowed && (bp.protectionLevel
10364                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10365                    && isSystemApp(pkg)) {
10366                // Any pre-installed system app is allowed to get this permission.
10367                allowed = true;
10368            }
10369            if (!allowed && (bp.protectionLevel
10370                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10371                // For development permissions, a development permission
10372                // is granted only if it was already granted.
10373                allowed = origPermissions.hasInstallPermission(perm);
10374            }
10375            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10376                    && pkg.packageName.equals(mSetupWizardPackage)) {
10377                // If this permission is to be granted to the system setup wizard and
10378                // this app is a setup wizard, then it gets the permission.
10379                allowed = true;
10380            }
10381        }
10382        return allowed;
10383    }
10384
10385    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10386        final int permCount = pkg.requestedPermissions.size();
10387        for (int j = 0; j < permCount; j++) {
10388            String requestedPermission = pkg.requestedPermissions.get(j);
10389            if (permission.equals(requestedPermission)) {
10390                return true;
10391            }
10392        }
10393        return false;
10394    }
10395
10396    final class ActivityIntentResolver
10397            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10398        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10399                boolean defaultOnly, int userId) {
10400            if (!sUserManager.exists(userId)) return null;
10401            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10402            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10403        }
10404
10405        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10406                int userId) {
10407            if (!sUserManager.exists(userId)) return null;
10408            mFlags = flags;
10409            return super.queryIntent(intent, resolvedType,
10410                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10411        }
10412
10413        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10414                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10415            if (!sUserManager.exists(userId)) return null;
10416            if (packageActivities == null) {
10417                return null;
10418            }
10419            mFlags = flags;
10420            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10421            final int N = packageActivities.size();
10422            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10423                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10424
10425            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10426            for (int i = 0; i < N; ++i) {
10427                intentFilters = packageActivities.get(i).intents;
10428                if (intentFilters != null && intentFilters.size() > 0) {
10429                    PackageParser.ActivityIntentInfo[] array =
10430                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10431                    intentFilters.toArray(array);
10432                    listCut.add(array);
10433                }
10434            }
10435            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10436        }
10437
10438        /**
10439         * Finds a privileged activity that matches the specified activity names.
10440         */
10441        private PackageParser.Activity findMatchingActivity(
10442                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10443            for (PackageParser.Activity sysActivity : activityList) {
10444                if (sysActivity.info.name.equals(activityInfo.name)) {
10445                    return sysActivity;
10446                }
10447                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10448                    return sysActivity;
10449                }
10450                if (sysActivity.info.targetActivity != null) {
10451                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10452                        return sysActivity;
10453                    }
10454                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10455                        return sysActivity;
10456                    }
10457                }
10458            }
10459            return null;
10460        }
10461
10462        public class IterGenerator<E> {
10463            public Iterator<E> generate(ActivityIntentInfo info) {
10464                return null;
10465            }
10466        }
10467
10468        public class ActionIterGenerator extends IterGenerator<String> {
10469            @Override
10470            public Iterator<String> generate(ActivityIntentInfo info) {
10471                return info.actionsIterator();
10472            }
10473        }
10474
10475        public class CategoriesIterGenerator extends IterGenerator<String> {
10476            @Override
10477            public Iterator<String> generate(ActivityIntentInfo info) {
10478                return info.categoriesIterator();
10479            }
10480        }
10481
10482        public class SchemesIterGenerator extends IterGenerator<String> {
10483            @Override
10484            public Iterator<String> generate(ActivityIntentInfo info) {
10485                return info.schemesIterator();
10486            }
10487        }
10488
10489        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10490            @Override
10491            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10492                return info.authoritiesIterator();
10493            }
10494        }
10495
10496        /**
10497         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10498         * MODIFIED. Do not pass in a list that should not be changed.
10499         */
10500        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10501                IterGenerator<T> generator, Iterator<T> searchIterator) {
10502            // loop through the set of actions; every one must be found in the intent filter
10503            while (searchIterator.hasNext()) {
10504                // we must have at least one filter in the list to consider a match
10505                if (intentList.size() == 0) {
10506                    break;
10507                }
10508
10509                final T searchAction = searchIterator.next();
10510
10511                // loop through the set of intent filters
10512                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10513                while (intentIter.hasNext()) {
10514                    final ActivityIntentInfo intentInfo = intentIter.next();
10515                    boolean selectionFound = false;
10516
10517                    // loop through the intent filter's selection criteria; at least one
10518                    // of them must match the searched criteria
10519                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10520                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10521                        final T intentSelection = intentSelectionIter.next();
10522                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10523                            selectionFound = true;
10524                            break;
10525                        }
10526                    }
10527
10528                    // the selection criteria wasn't found in this filter's set; this filter
10529                    // is not a potential match
10530                    if (!selectionFound) {
10531                        intentIter.remove();
10532                    }
10533                }
10534            }
10535        }
10536
10537        private boolean isProtectedAction(ActivityIntentInfo filter) {
10538            final Iterator<String> actionsIter = filter.actionsIterator();
10539            while (actionsIter != null && actionsIter.hasNext()) {
10540                final String filterAction = actionsIter.next();
10541                if (PROTECTED_ACTIONS.contains(filterAction)) {
10542                    return true;
10543                }
10544            }
10545            return false;
10546        }
10547
10548        /**
10549         * Adjusts the priority of the given intent filter according to policy.
10550         * <p>
10551         * <ul>
10552         * <li>The priority for non privileged applications is capped to '0'</li>
10553         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10554         * <li>The priority for unbundled updates to privileged applications is capped to the
10555         *      priority defined on the system partition</li>
10556         * </ul>
10557         * <p>
10558         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10559         * allowed to obtain any priority on any action.
10560         */
10561        private void adjustPriority(
10562                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10563            // nothing to do; priority is fine as-is
10564            if (intent.getPriority() <= 0) {
10565                return;
10566            }
10567
10568            final ActivityInfo activityInfo = intent.activity.info;
10569            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10570
10571            final boolean privilegedApp =
10572                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10573            if (!privilegedApp) {
10574                // non-privileged applications can never define a priority >0
10575                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10576                        + " package: " + applicationInfo.packageName
10577                        + " activity: " + intent.activity.className
10578                        + " origPrio: " + intent.getPriority());
10579                intent.setPriority(0);
10580                return;
10581            }
10582
10583            if (systemActivities == null) {
10584                // the system package is not disabled; we're parsing the system partition
10585                if (isProtectedAction(intent)) {
10586                    if (mDeferProtectedFilters) {
10587                        // We can't deal with these just yet. No component should ever obtain a
10588                        // >0 priority for a protected actions, with ONE exception -- the setup
10589                        // wizard. The setup wizard, however, cannot be known until we're able to
10590                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10591                        // until all intent filters have been processed. Chicken, meet egg.
10592                        // Let the filter temporarily have a high priority and rectify the
10593                        // priorities after all system packages have been scanned.
10594                        mProtectedFilters.add(intent);
10595                        if (DEBUG_FILTERS) {
10596                            Slog.i(TAG, "Protected action; save for later;"
10597                                    + " package: " + applicationInfo.packageName
10598                                    + " activity: " + intent.activity.className
10599                                    + " origPrio: " + intent.getPriority());
10600                        }
10601                        return;
10602                    } else {
10603                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10604                            Slog.i(TAG, "No setup wizard;"
10605                                + " All protected intents capped to priority 0");
10606                        }
10607                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10608                            if (DEBUG_FILTERS) {
10609                                Slog.i(TAG, "Found setup wizard;"
10610                                    + " allow priority " + intent.getPriority() + ";"
10611                                    + " package: " + intent.activity.info.packageName
10612                                    + " activity: " + intent.activity.className
10613                                    + " priority: " + intent.getPriority());
10614                            }
10615                            // setup wizard gets whatever it wants
10616                            return;
10617                        }
10618                        Slog.w(TAG, "Protected action; cap priority to 0;"
10619                                + " package: " + intent.activity.info.packageName
10620                                + " activity: " + intent.activity.className
10621                                + " origPrio: " + intent.getPriority());
10622                        intent.setPriority(0);
10623                        return;
10624                    }
10625                }
10626                // privileged apps on the system image get whatever priority they request
10627                return;
10628            }
10629
10630            // privileged app unbundled update ... try to find the same activity
10631            final PackageParser.Activity foundActivity =
10632                    findMatchingActivity(systemActivities, activityInfo);
10633            if (foundActivity == null) {
10634                // this is a new activity; it cannot obtain >0 priority
10635                if (DEBUG_FILTERS) {
10636                    Slog.i(TAG, "New activity; cap priority to 0;"
10637                            + " package: " + applicationInfo.packageName
10638                            + " activity: " + intent.activity.className
10639                            + " origPrio: " + intent.getPriority());
10640                }
10641                intent.setPriority(0);
10642                return;
10643            }
10644
10645            // found activity, now check for filter equivalence
10646
10647            // a shallow copy is enough; we modify the list, not its contents
10648            final List<ActivityIntentInfo> intentListCopy =
10649                    new ArrayList<>(foundActivity.intents);
10650            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10651
10652            // find matching action subsets
10653            final Iterator<String> actionsIterator = intent.actionsIterator();
10654            if (actionsIterator != null) {
10655                getIntentListSubset(
10656                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10657                if (intentListCopy.size() == 0) {
10658                    // no more intents to match; we're not equivalent
10659                    if (DEBUG_FILTERS) {
10660                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10661                                + " package: " + applicationInfo.packageName
10662                                + " activity: " + intent.activity.className
10663                                + " origPrio: " + intent.getPriority());
10664                    }
10665                    intent.setPriority(0);
10666                    return;
10667                }
10668            }
10669
10670            // find matching category subsets
10671            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10672            if (categoriesIterator != null) {
10673                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10674                        categoriesIterator);
10675                if (intentListCopy.size() == 0) {
10676                    // no more intents to match; we're not equivalent
10677                    if (DEBUG_FILTERS) {
10678                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10679                                + " package: " + applicationInfo.packageName
10680                                + " activity: " + intent.activity.className
10681                                + " origPrio: " + intent.getPriority());
10682                    }
10683                    intent.setPriority(0);
10684                    return;
10685                }
10686            }
10687
10688            // find matching schemes subsets
10689            final Iterator<String> schemesIterator = intent.schemesIterator();
10690            if (schemesIterator != null) {
10691                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10692                        schemesIterator);
10693                if (intentListCopy.size() == 0) {
10694                    // no more intents to match; we're not equivalent
10695                    if (DEBUG_FILTERS) {
10696                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10697                                + " package: " + applicationInfo.packageName
10698                                + " activity: " + intent.activity.className
10699                                + " origPrio: " + intent.getPriority());
10700                    }
10701                    intent.setPriority(0);
10702                    return;
10703                }
10704            }
10705
10706            // find matching authorities subsets
10707            final Iterator<IntentFilter.AuthorityEntry>
10708                    authoritiesIterator = intent.authoritiesIterator();
10709            if (authoritiesIterator != null) {
10710                getIntentListSubset(intentListCopy,
10711                        new AuthoritiesIterGenerator(),
10712                        authoritiesIterator);
10713                if (intentListCopy.size() == 0) {
10714                    // no more intents to match; we're not equivalent
10715                    if (DEBUG_FILTERS) {
10716                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10717                                + " package: " + applicationInfo.packageName
10718                                + " activity: " + intent.activity.className
10719                                + " origPrio: " + intent.getPriority());
10720                    }
10721                    intent.setPriority(0);
10722                    return;
10723                }
10724            }
10725
10726            // we found matching filter(s); app gets the max priority of all intents
10727            int cappedPriority = 0;
10728            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10729                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10730            }
10731            if (intent.getPriority() > cappedPriority) {
10732                if (DEBUG_FILTERS) {
10733                    Slog.i(TAG, "Found matching filter(s);"
10734                            + " cap priority to " + cappedPriority + ";"
10735                            + " package: " + applicationInfo.packageName
10736                            + " activity: " + intent.activity.className
10737                            + " origPrio: " + intent.getPriority());
10738                }
10739                intent.setPriority(cappedPriority);
10740                return;
10741            }
10742            // all this for nothing; the requested priority was <= what was on the system
10743        }
10744
10745        public final void addActivity(PackageParser.Activity a, String type) {
10746            mActivities.put(a.getComponentName(), a);
10747            if (DEBUG_SHOW_INFO)
10748                Log.v(
10749                TAG, "  " + type + " " +
10750                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10751            if (DEBUG_SHOW_INFO)
10752                Log.v(TAG, "    Class=" + a.info.name);
10753            final int NI = a.intents.size();
10754            for (int j=0; j<NI; j++) {
10755                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10756                if ("activity".equals(type)) {
10757                    final PackageSetting ps =
10758                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10759                    final List<PackageParser.Activity> systemActivities =
10760                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10761                    adjustPriority(systemActivities, intent);
10762                }
10763                if (DEBUG_SHOW_INFO) {
10764                    Log.v(TAG, "    IntentFilter:");
10765                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10766                }
10767                if (!intent.debugCheck()) {
10768                    Log.w(TAG, "==> For Activity " + a.info.name);
10769                }
10770                addFilter(intent);
10771            }
10772        }
10773
10774        public final void removeActivity(PackageParser.Activity a, String type) {
10775            mActivities.remove(a.getComponentName());
10776            if (DEBUG_SHOW_INFO) {
10777                Log.v(TAG, "  " + type + " "
10778                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10779                                : a.info.name) + ":");
10780                Log.v(TAG, "    Class=" + a.info.name);
10781            }
10782            final int NI = a.intents.size();
10783            for (int j=0; j<NI; j++) {
10784                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10785                if (DEBUG_SHOW_INFO) {
10786                    Log.v(TAG, "    IntentFilter:");
10787                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10788                }
10789                removeFilter(intent);
10790            }
10791        }
10792
10793        @Override
10794        protected boolean allowFilterResult(
10795                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10796            ActivityInfo filterAi = filter.activity.info;
10797            for (int i=dest.size()-1; i>=0; i--) {
10798                ActivityInfo destAi = dest.get(i).activityInfo;
10799                if (destAi.name == filterAi.name
10800                        && destAi.packageName == filterAi.packageName) {
10801                    return false;
10802                }
10803            }
10804            return true;
10805        }
10806
10807        @Override
10808        protected ActivityIntentInfo[] newArray(int size) {
10809            return new ActivityIntentInfo[size];
10810        }
10811
10812        @Override
10813        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10814            if (!sUserManager.exists(userId)) return true;
10815            PackageParser.Package p = filter.activity.owner;
10816            if (p != null) {
10817                PackageSetting ps = (PackageSetting)p.mExtras;
10818                if (ps != null) {
10819                    // System apps are never considered stopped for purposes of
10820                    // filtering, because there may be no way for the user to
10821                    // actually re-launch them.
10822                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10823                            && ps.getStopped(userId);
10824                }
10825            }
10826            return false;
10827        }
10828
10829        @Override
10830        protected boolean isPackageForFilter(String packageName,
10831                PackageParser.ActivityIntentInfo info) {
10832            return packageName.equals(info.activity.owner.packageName);
10833        }
10834
10835        @Override
10836        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10837                int match, int userId) {
10838            if (!sUserManager.exists(userId)) return null;
10839            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10840                return null;
10841            }
10842            final PackageParser.Activity activity = info.activity;
10843            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10844            if (ps == null) {
10845                return null;
10846            }
10847            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10848                    ps.readUserState(userId), userId);
10849            if (ai == null) {
10850                return null;
10851            }
10852            final ResolveInfo res = new ResolveInfo();
10853            res.activityInfo = ai;
10854            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10855                res.filter = info;
10856            }
10857            if (info != null) {
10858                res.handleAllWebDataURI = info.handleAllWebDataURI();
10859            }
10860            res.priority = info.getPriority();
10861            res.preferredOrder = activity.owner.mPreferredOrder;
10862            //System.out.println("Result: " + res.activityInfo.className +
10863            //                   " = " + res.priority);
10864            res.match = match;
10865            res.isDefault = info.hasDefault;
10866            res.labelRes = info.labelRes;
10867            res.nonLocalizedLabel = info.nonLocalizedLabel;
10868            if (userNeedsBadging(userId)) {
10869                res.noResourceId = true;
10870            } else {
10871                res.icon = info.icon;
10872            }
10873            res.iconResourceId = info.icon;
10874            res.system = res.activityInfo.applicationInfo.isSystemApp();
10875            return res;
10876        }
10877
10878        @Override
10879        protected void sortResults(List<ResolveInfo> results) {
10880            Collections.sort(results, mResolvePrioritySorter);
10881        }
10882
10883        @Override
10884        protected void dumpFilter(PrintWriter out, String prefix,
10885                PackageParser.ActivityIntentInfo filter) {
10886            out.print(prefix); out.print(
10887                    Integer.toHexString(System.identityHashCode(filter.activity)));
10888                    out.print(' ');
10889                    filter.activity.printComponentShortName(out);
10890                    out.print(" filter ");
10891                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10892        }
10893
10894        @Override
10895        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10896            return filter.activity;
10897        }
10898
10899        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10900            PackageParser.Activity activity = (PackageParser.Activity)label;
10901            out.print(prefix); out.print(
10902                    Integer.toHexString(System.identityHashCode(activity)));
10903                    out.print(' ');
10904                    activity.printComponentShortName(out);
10905            if (count > 1) {
10906                out.print(" ("); out.print(count); out.print(" filters)");
10907            }
10908            out.println();
10909        }
10910
10911        // Keys are String (activity class name), values are Activity.
10912        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10913                = new ArrayMap<ComponentName, PackageParser.Activity>();
10914        private int mFlags;
10915    }
10916
10917    private final class ServiceIntentResolver
10918            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10919        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10920                boolean defaultOnly, int userId) {
10921            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10922            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10923        }
10924
10925        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10926                int userId) {
10927            if (!sUserManager.exists(userId)) return null;
10928            mFlags = flags;
10929            return super.queryIntent(intent, resolvedType,
10930                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10931        }
10932
10933        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10934                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10935            if (!sUserManager.exists(userId)) return null;
10936            if (packageServices == null) {
10937                return null;
10938            }
10939            mFlags = flags;
10940            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10941            final int N = packageServices.size();
10942            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10943                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10944
10945            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10946            for (int i = 0; i < N; ++i) {
10947                intentFilters = packageServices.get(i).intents;
10948                if (intentFilters != null && intentFilters.size() > 0) {
10949                    PackageParser.ServiceIntentInfo[] array =
10950                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10951                    intentFilters.toArray(array);
10952                    listCut.add(array);
10953                }
10954            }
10955            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10956        }
10957
10958        public final void addService(PackageParser.Service s) {
10959            mServices.put(s.getComponentName(), s);
10960            if (DEBUG_SHOW_INFO) {
10961                Log.v(TAG, "  "
10962                        + (s.info.nonLocalizedLabel != null
10963                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10964                Log.v(TAG, "    Class=" + s.info.name);
10965            }
10966            final int NI = s.intents.size();
10967            int j;
10968            for (j=0; j<NI; j++) {
10969                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10970                if (DEBUG_SHOW_INFO) {
10971                    Log.v(TAG, "    IntentFilter:");
10972                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10973                }
10974                if (!intent.debugCheck()) {
10975                    Log.w(TAG, "==> For Service " + s.info.name);
10976                }
10977                addFilter(intent);
10978            }
10979        }
10980
10981        public final void removeService(PackageParser.Service s) {
10982            mServices.remove(s.getComponentName());
10983            if (DEBUG_SHOW_INFO) {
10984                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10985                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10986                Log.v(TAG, "    Class=" + s.info.name);
10987            }
10988            final int NI = s.intents.size();
10989            int j;
10990            for (j=0; j<NI; j++) {
10991                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10992                if (DEBUG_SHOW_INFO) {
10993                    Log.v(TAG, "    IntentFilter:");
10994                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10995                }
10996                removeFilter(intent);
10997            }
10998        }
10999
11000        @Override
11001        protected boolean allowFilterResult(
11002                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11003            ServiceInfo filterSi = filter.service.info;
11004            for (int i=dest.size()-1; i>=0; i--) {
11005                ServiceInfo destAi = dest.get(i).serviceInfo;
11006                if (destAi.name == filterSi.name
11007                        && destAi.packageName == filterSi.packageName) {
11008                    return false;
11009                }
11010            }
11011            return true;
11012        }
11013
11014        @Override
11015        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11016            return new PackageParser.ServiceIntentInfo[size];
11017        }
11018
11019        @Override
11020        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11021            if (!sUserManager.exists(userId)) return true;
11022            PackageParser.Package p = filter.service.owner;
11023            if (p != null) {
11024                PackageSetting ps = (PackageSetting)p.mExtras;
11025                if (ps != null) {
11026                    // System apps are never considered stopped for purposes of
11027                    // filtering, because there may be no way for the user to
11028                    // actually re-launch them.
11029                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11030                            && ps.getStopped(userId);
11031                }
11032            }
11033            return false;
11034        }
11035
11036        @Override
11037        protected boolean isPackageForFilter(String packageName,
11038                PackageParser.ServiceIntentInfo info) {
11039            return packageName.equals(info.service.owner.packageName);
11040        }
11041
11042        @Override
11043        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11044                int match, int userId) {
11045            if (!sUserManager.exists(userId)) return null;
11046            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11047            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11048                return null;
11049            }
11050            final PackageParser.Service service = info.service;
11051            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11052            if (ps == null) {
11053                return null;
11054            }
11055            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11056                    ps.readUserState(userId), userId);
11057            if (si == null) {
11058                return null;
11059            }
11060            final ResolveInfo res = new ResolveInfo();
11061            res.serviceInfo = si;
11062            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11063                res.filter = filter;
11064            }
11065            res.priority = info.getPriority();
11066            res.preferredOrder = service.owner.mPreferredOrder;
11067            res.match = match;
11068            res.isDefault = info.hasDefault;
11069            res.labelRes = info.labelRes;
11070            res.nonLocalizedLabel = info.nonLocalizedLabel;
11071            res.icon = info.icon;
11072            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11073            return res;
11074        }
11075
11076        @Override
11077        protected void sortResults(List<ResolveInfo> results) {
11078            Collections.sort(results, mResolvePrioritySorter);
11079        }
11080
11081        @Override
11082        protected void dumpFilter(PrintWriter out, String prefix,
11083                PackageParser.ServiceIntentInfo filter) {
11084            out.print(prefix); out.print(
11085                    Integer.toHexString(System.identityHashCode(filter.service)));
11086                    out.print(' ');
11087                    filter.service.printComponentShortName(out);
11088                    out.print(" filter ");
11089                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11090        }
11091
11092        @Override
11093        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11094            return filter.service;
11095        }
11096
11097        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11098            PackageParser.Service service = (PackageParser.Service)label;
11099            out.print(prefix); out.print(
11100                    Integer.toHexString(System.identityHashCode(service)));
11101                    out.print(' ');
11102                    service.printComponentShortName(out);
11103            if (count > 1) {
11104                out.print(" ("); out.print(count); out.print(" filters)");
11105            }
11106            out.println();
11107        }
11108
11109//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11110//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11111//            final List<ResolveInfo> retList = Lists.newArrayList();
11112//            while (i.hasNext()) {
11113//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11114//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11115//                    retList.add(resolveInfo);
11116//                }
11117//            }
11118//            return retList;
11119//        }
11120
11121        // Keys are String (activity class name), values are Activity.
11122        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11123                = new ArrayMap<ComponentName, PackageParser.Service>();
11124        private int mFlags;
11125    };
11126
11127    private final class ProviderIntentResolver
11128            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11129        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11130                boolean defaultOnly, int userId) {
11131            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11132            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11133        }
11134
11135        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11136                int userId) {
11137            if (!sUserManager.exists(userId))
11138                return null;
11139            mFlags = flags;
11140            return super.queryIntent(intent, resolvedType,
11141                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11142        }
11143
11144        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11145                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11146            if (!sUserManager.exists(userId))
11147                return null;
11148            if (packageProviders == null) {
11149                return null;
11150            }
11151            mFlags = flags;
11152            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11153            final int N = packageProviders.size();
11154            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11155                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11156
11157            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11158            for (int i = 0; i < N; ++i) {
11159                intentFilters = packageProviders.get(i).intents;
11160                if (intentFilters != null && intentFilters.size() > 0) {
11161                    PackageParser.ProviderIntentInfo[] array =
11162                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11163                    intentFilters.toArray(array);
11164                    listCut.add(array);
11165                }
11166            }
11167            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11168        }
11169
11170        public final void addProvider(PackageParser.Provider p) {
11171            if (mProviders.containsKey(p.getComponentName())) {
11172                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11173                return;
11174            }
11175
11176            mProviders.put(p.getComponentName(), p);
11177            if (DEBUG_SHOW_INFO) {
11178                Log.v(TAG, "  "
11179                        + (p.info.nonLocalizedLabel != null
11180                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11181                Log.v(TAG, "    Class=" + p.info.name);
11182            }
11183            final int NI = p.intents.size();
11184            int j;
11185            for (j = 0; j < NI; j++) {
11186                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11187                if (DEBUG_SHOW_INFO) {
11188                    Log.v(TAG, "    IntentFilter:");
11189                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11190                }
11191                if (!intent.debugCheck()) {
11192                    Log.w(TAG, "==> For Provider " + p.info.name);
11193                }
11194                addFilter(intent);
11195            }
11196        }
11197
11198        public final void removeProvider(PackageParser.Provider p) {
11199            mProviders.remove(p.getComponentName());
11200            if (DEBUG_SHOW_INFO) {
11201                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11202                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11203                Log.v(TAG, "    Class=" + p.info.name);
11204            }
11205            final int NI = p.intents.size();
11206            int j;
11207            for (j = 0; j < NI; j++) {
11208                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11209                if (DEBUG_SHOW_INFO) {
11210                    Log.v(TAG, "    IntentFilter:");
11211                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11212                }
11213                removeFilter(intent);
11214            }
11215        }
11216
11217        @Override
11218        protected boolean allowFilterResult(
11219                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11220            ProviderInfo filterPi = filter.provider.info;
11221            for (int i = dest.size() - 1; i >= 0; i--) {
11222                ProviderInfo destPi = dest.get(i).providerInfo;
11223                if (destPi.name == filterPi.name
11224                        && destPi.packageName == filterPi.packageName) {
11225                    return false;
11226                }
11227            }
11228            return true;
11229        }
11230
11231        @Override
11232        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11233            return new PackageParser.ProviderIntentInfo[size];
11234        }
11235
11236        @Override
11237        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11238            if (!sUserManager.exists(userId))
11239                return true;
11240            PackageParser.Package p = filter.provider.owner;
11241            if (p != null) {
11242                PackageSetting ps = (PackageSetting) p.mExtras;
11243                if (ps != null) {
11244                    // System apps are never considered stopped for purposes of
11245                    // filtering, because there may be no way for the user to
11246                    // actually re-launch them.
11247                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11248                            && ps.getStopped(userId);
11249                }
11250            }
11251            return false;
11252        }
11253
11254        @Override
11255        protected boolean isPackageForFilter(String packageName,
11256                PackageParser.ProviderIntentInfo info) {
11257            return packageName.equals(info.provider.owner.packageName);
11258        }
11259
11260        @Override
11261        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11262                int match, int userId) {
11263            if (!sUserManager.exists(userId))
11264                return null;
11265            final PackageParser.ProviderIntentInfo info = filter;
11266            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11267                return null;
11268            }
11269            final PackageParser.Provider provider = info.provider;
11270            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11271            if (ps == null) {
11272                return null;
11273            }
11274            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11275                    ps.readUserState(userId), userId);
11276            if (pi == null) {
11277                return null;
11278            }
11279            final ResolveInfo res = new ResolveInfo();
11280            res.providerInfo = pi;
11281            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11282                res.filter = filter;
11283            }
11284            res.priority = info.getPriority();
11285            res.preferredOrder = provider.owner.mPreferredOrder;
11286            res.match = match;
11287            res.isDefault = info.hasDefault;
11288            res.labelRes = info.labelRes;
11289            res.nonLocalizedLabel = info.nonLocalizedLabel;
11290            res.icon = info.icon;
11291            res.system = res.providerInfo.applicationInfo.isSystemApp();
11292            return res;
11293        }
11294
11295        @Override
11296        protected void sortResults(List<ResolveInfo> results) {
11297            Collections.sort(results, mResolvePrioritySorter);
11298        }
11299
11300        @Override
11301        protected void dumpFilter(PrintWriter out, String prefix,
11302                PackageParser.ProviderIntentInfo filter) {
11303            out.print(prefix);
11304            out.print(
11305                    Integer.toHexString(System.identityHashCode(filter.provider)));
11306            out.print(' ');
11307            filter.provider.printComponentShortName(out);
11308            out.print(" filter ");
11309            out.println(Integer.toHexString(System.identityHashCode(filter)));
11310        }
11311
11312        @Override
11313        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11314            return filter.provider;
11315        }
11316
11317        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11318            PackageParser.Provider provider = (PackageParser.Provider)label;
11319            out.print(prefix); out.print(
11320                    Integer.toHexString(System.identityHashCode(provider)));
11321                    out.print(' ');
11322                    provider.printComponentShortName(out);
11323            if (count > 1) {
11324                out.print(" ("); out.print(count); out.print(" filters)");
11325            }
11326            out.println();
11327        }
11328
11329        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11330                = new ArrayMap<ComponentName, PackageParser.Provider>();
11331        private int mFlags;
11332    }
11333
11334    private static final class EphemeralIntentResolver
11335            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11336        @Override
11337        protected EphemeralResolveIntentInfo[] newArray(int size) {
11338            return new EphemeralResolveIntentInfo[size];
11339        }
11340
11341        @Override
11342        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11343            return true;
11344        }
11345
11346        @Override
11347        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11348                int userId) {
11349            if (!sUserManager.exists(userId)) {
11350                return null;
11351            }
11352            return info.getEphemeralResolveInfo();
11353        }
11354    }
11355
11356    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11357            new Comparator<ResolveInfo>() {
11358        public int compare(ResolveInfo r1, ResolveInfo r2) {
11359            int v1 = r1.priority;
11360            int v2 = r2.priority;
11361            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11362            if (v1 != v2) {
11363                return (v1 > v2) ? -1 : 1;
11364            }
11365            v1 = r1.preferredOrder;
11366            v2 = r2.preferredOrder;
11367            if (v1 != v2) {
11368                return (v1 > v2) ? -1 : 1;
11369            }
11370            if (r1.isDefault != r2.isDefault) {
11371                return r1.isDefault ? -1 : 1;
11372            }
11373            v1 = r1.match;
11374            v2 = r2.match;
11375            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11376            if (v1 != v2) {
11377                return (v1 > v2) ? -1 : 1;
11378            }
11379            if (r1.system != r2.system) {
11380                return r1.system ? -1 : 1;
11381            }
11382            if (r1.activityInfo != null) {
11383                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11384            }
11385            if (r1.serviceInfo != null) {
11386                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11387            }
11388            if (r1.providerInfo != null) {
11389                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11390            }
11391            return 0;
11392        }
11393    };
11394
11395    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11396            new Comparator<ProviderInfo>() {
11397        public int compare(ProviderInfo p1, ProviderInfo p2) {
11398            final int v1 = p1.initOrder;
11399            final int v2 = p2.initOrder;
11400            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11401        }
11402    };
11403
11404    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11405            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11406            final int[] userIds) {
11407        mHandler.post(new Runnable() {
11408            @Override
11409            public void run() {
11410                try {
11411                    final IActivityManager am = ActivityManagerNative.getDefault();
11412                    if (am == null) return;
11413                    final int[] resolvedUserIds;
11414                    if (userIds == null) {
11415                        resolvedUserIds = am.getRunningUserIds();
11416                    } else {
11417                        resolvedUserIds = userIds;
11418                    }
11419                    for (int id : resolvedUserIds) {
11420                        final Intent intent = new Intent(action,
11421                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11422                        if (extras != null) {
11423                            intent.putExtras(extras);
11424                        }
11425                        if (targetPkg != null) {
11426                            intent.setPackage(targetPkg);
11427                        }
11428                        // Modify the UID when posting to other users
11429                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11430                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11431                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11432                            intent.putExtra(Intent.EXTRA_UID, uid);
11433                        }
11434                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11435                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11436                        if (DEBUG_BROADCASTS) {
11437                            RuntimeException here = new RuntimeException("here");
11438                            here.fillInStackTrace();
11439                            Slog.d(TAG, "Sending to user " + id + ": "
11440                                    + intent.toShortString(false, true, false, false)
11441                                    + " " + intent.getExtras(), here);
11442                        }
11443                        am.broadcastIntent(null, intent, null, finishedReceiver,
11444                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11445                                null, finishedReceiver != null, false, id);
11446                    }
11447                } catch (RemoteException ex) {
11448                }
11449            }
11450        });
11451    }
11452
11453    /**
11454     * Check if the external storage media is available. This is true if there
11455     * is a mounted external storage medium or if the external storage is
11456     * emulated.
11457     */
11458    private boolean isExternalMediaAvailable() {
11459        return mMediaMounted || Environment.isExternalStorageEmulated();
11460    }
11461
11462    @Override
11463    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11464        // writer
11465        synchronized (mPackages) {
11466            if (!isExternalMediaAvailable()) {
11467                // If the external storage is no longer mounted at this point,
11468                // the caller may not have been able to delete all of this
11469                // packages files and can not delete any more.  Bail.
11470                return null;
11471            }
11472            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11473            if (lastPackage != null) {
11474                pkgs.remove(lastPackage);
11475            }
11476            if (pkgs.size() > 0) {
11477                return pkgs.get(0);
11478            }
11479        }
11480        return null;
11481    }
11482
11483    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11484        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11485                userId, andCode ? 1 : 0, packageName);
11486        if (mSystemReady) {
11487            msg.sendToTarget();
11488        } else {
11489            if (mPostSystemReadyMessages == null) {
11490                mPostSystemReadyMessages = new ArrayList<>();
11491            }
11492            mPostSystemReadyMessages.add(msg);
11493        }
11494    }
11495
11496    void startCleaningPackages() {
11497        // reader
11498        if (!isExternalMediaAvailable()) {
11499            return;
11500        }
11501        synchronized (mPackages) {
11502            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11503                return;
11504            }
11505        }
11506        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11507        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11508        IActivityManager am = ActivityManagerNative.getDefault();
11509        if (am != null) {
11510            try {
11511                am.startService(null, intent, null, mContext.getOpPackageName(),
11512                        UserHandle.USER_SYSTEM);
11513            } catch (RemoteException e) {
11514            }
11515        }
11516    }
11517
11518    @Override
11519    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11520            int installFlags, String installerPackageName, int userId) {
11521        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11522
11523        final int callingUid = Binder.getCallingUid();
11524        enforceCrossUserPermission(callingUid, userId,
11525                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11526
11527        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11528            try {
11529                if (observer != null) {
11530                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11531                }
11532            } catch (RemoteException re) {
11533            }
11534            return;
11535        }
11536
11537        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11538            installFlags |= PackageManager.INSTALL_FROM_ADB;
11539
11540        } else {
11541            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11542            // about installerPackageName.
11543
11544            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11545            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11546        }
11547
11548        UserHandle user;
11549        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11550            user = UserHandle.ALL;
11551        } else {
11552            user = new UserHandle(userId);
11553        }
11554
11555        // Only system components can circumvent runtime permissions when installing.
11556        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11557                && mContext.checkCallingOrSelfPermission(Manifest.permission
11558                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11559            throw new SecurityException("You need the "
11560                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11561                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11562        }
11563
11564        final File originFile = new File(originPath);
11565        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11566
11567        final Message msg = mHandler.obtainMessage(INIT_COPY);
11568        final VerificationInfo verificationInfo = new VerificationInfo(
11569                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11570        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11571                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11572                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11573                null /*certificates*/);
11574        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11575        msg.obj = params;
11576
11577        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11578                System.identityHashCode(msg.obj));
11579        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11580                System.identityHashCode(msg.obj));
11581
11582        mHandler.sendMessage(msg);
11583    }
11584
11585    void installStage(String packageName, File stagedDir, String stagedCid,
11586            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11587            String installerPackageName, int installerUid, UserHandle user,
11588            Certificate[][] certificates) {
11589        if (DEBUG_EPHEMERAL) {
11590            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11591                Slog.d(TAG, "Ephemeral install of " + packageName);
11592            }
11593        }
11594        final VerificationInfo verificationInfo = new VerificationInfo(
11595                sessionParams.originatingUri, sessionParams.referrerUri,
11596                sessionParams.originatingUid, installerUid);
11597
11598        final OriginInfo origin;
11599        if (stagedDir != null) {
11600            origin = OriginInfo.fromStagedFile(stagedDir);
11601        } else {
11602            origin = OriginInfo.fromStagedContainer(stagedCid);
11603        }
11604
11605        final Message msg = mHandler.obtainMessage(INIT_COPY);
11606        final InstallParams params = new InstallParams(origin, null, observer,
11607                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11608                verificationInfo, user, sessionParams.abiOverride,
11609                sessionParams.grantedRuntimePermissions, certificates);
11610        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11611        msg.obj = params;
11612
11613        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11614                System.identityHashCode(msg.obj));
11615        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11616                System.identityHashCode(msg.obj));
11617
11618        mHandler.sendMessage(msg);
11619    }
11620
11621    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11622            int userId) {
11623        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11624        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11625    }
11626
11627    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11628            int appId, int userId) {
11629        Bundle extras = new Bundle(1);
11630        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11631
11632        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11633                packageName, extras, 0, null, null, new int[] {userId});
11634        try {
11635            IActivityManager am = ActivityManagerNative.getDefault();
11636            if (isSystem && am.isUserRunning(userId, 0)) {
11637                // The just-installed/enabled app is bundled on the system, so presumed
11638                // to be able to run automatically without needing an explicit launch.
11639                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11640                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11641                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11642                        .setPackage(packageName);
11643                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11644                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11645            }
11646        } catch (RemoteException e) {
11647            // shouldn't happen
11648            Slog.w(TAG, "Unable to bootstrap installed package", e);
11649        }
11650    }
11651
11652    @Override
11653    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11654            int userId) {
11655        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11656        PackageSetting pkgSetting;
11657        final int uid = Binder.getCallingUid();
11658        enforceCrossUserPermission(uid, userId,
11659                true /* requireFullPermission */, true /* checkShell */,
11660                "setApplicationHiddenSetting for user " + userId);
11661
11662        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11663            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11664            return false;
11665        }
11666
11667        long callingId = Binder.clearCallingIdentity();
11668        try {
11669            boolean sendAdded = false;
11670            boolean sendRemoved = false;
11671            // writer
11672            synchronized (mPackages) {
11673                pkgSetting = mSettings.mPackages.get(packageName);
11674                if (pkgSetting == null) {
11675                    return false;
11676                }
11677                // Do not allow "android" is being disabled
11678                if ("android".equals(packageName)) {
11679                    Slog.w(TAG, "Cannot hide package: android");
11680                    return false;
11681                }
11682                // Only allow protected packages to hide themselves.
11683                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11684                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11685                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11686                    return false;
11687                }
11688
11689                if (pkgSetting.getHidden(userId) != hidden) {
11690                    pkgSetting.setHidden(hidden, userId);
11691                    mSettings.writePackageRestrictionsLPr(userId);
11692                    if (hidden) {
11693                        sendRemoved = true;
11694                    } else {
11695                        sendAdded = true;
11696                    }
11697                }
11698            }
11699            if (sendAdded) {
11700                sendPackageAddedForUser(packageName, pkgSetting, userId);
11701                return true;
11702            }
11703            if (sendRemoved) {
11704                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11705                        "hiding pkg");
11706                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11707                return true;
11708            }
11709        } finally {
11710            Binder.restoreCallingIdentity(callingId);
11711        }
11712        return false;
11713    }
11714
11715    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11716            int userId) {
11717        final PackageRemovedInfo info = new PackageRemovedInfo();
11718        info.removedPackage = packageName;
11719        info.removedUsers = new int[] {userId};
11720        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11721        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11722    }
11723
11724    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11725        if (pkgList.length > 0) {
11726            Bundle extras = new Bundle(1);
11727            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11728
11729            sendPackageBroadcast(
11730                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11731                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11732                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11733                    new int[] {userId});
11734        }
11735    }
11736
11737    /**
11738     * Returns true if application is not found or there was an error. Otherwise it returns
11739     * the hidden state of the package for the given user.
11740     */
11741    @Override
11742    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11743        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11744        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11745                true /* requireFullPermission */, false /* checkShell */,
11746                "getApplicationHidden for user " + userId);
11747        PackageSetting pkgSetting;
11748        long callingId = Binder.clearCallingIdentity();
11749        try {
11750            // writer
11751            synchronized (mPackages) {
11752                pkgSetting = mSettings.mPackages.get(packageName);
11753                if (pkgSetting == null) {
11754                    return true;
11755                }
11756                return pkgSetting.getHidden(userId);
11757            }
11758        } finally {
11759            Binder.restoreCallingIdentity(callingId);
11760        }
11761    }
11762
11763    /**
11764     * @hide
11765     */
11766    @Override
11767    public int installExistingPackageAsUser(String packageName, int userId) {
11768        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11769                null);
11770        PackageSetting pkgSetting;
11771        final int uid = Binder.getCallingUid();
11772        enforceCrossUserPermission(uid, userId,
11773                true /* requireFullPermission */, true /* checkShell */,
11774                "installExistingPackage for user " + userId);
11775        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11776            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11777        }
11778
11779        long callingId = Binder.clearCallingIdentity();
11780        try {
11781            boolean installed = false;
11782
11783            // writer
11784            synchronized (mPackages) {
11785                pkgSetting = mSettings.mPackages.get(packageName);
11786                if (pkgSetting == null) {
11787                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11788                }
11789                if (!pkgSetting.getInstalled(userId)) {
11790                    pkgSetting.setInstalled(true, userId);
11791                    pkgSetting.setHidden(false, userId);
11792                    mSettings.writePackageRestrictionsLPr(userId);
11793                    installed = true;
11794                }
11795            }
11796
11797            if (installed) {
11798                if (pkgSetting.pkg != null) {
11799                    synchronized (mInstallLock) {
11800                        // We don't need to freeze for a brand new install
11801                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11802                    }
11803                }
11804                sendPackageAddedForUser(packageName, pkgSetting, userId);
11805            }
11806        } finally {
11807            Binder.restoreCallingIdentity(callingId);
11808        }
11809
11810        return PackageManager.INSTALL_SUCCEEDED;
11811    }
11812
11813    boolean isUserRestricted(int userId, String restrictionKey) {
11814        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11815        if (restrictions.getBoolean(restrictionKey, false)) {
11816            Log.w(TAG, "User is restricted: " + restrictionKey);
11817            return true;
11818        }
11819        return false;
11820    }
11821
11822    @Override
11823    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11824            int userId) {
11825        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11826        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11827                true /* requireFullPermission */, true /* checkShell */,
11828                "setPackagesSuspended for user " + userId);
11829
11830        if (ArrayUtils.isEmpty(packageNames)) {
11831            return packageNames;
11832        }
11833
11834        // List of package names for whom the suspended state has changed.
11835        List<String> changedPackages = new ArrayList<>(packageNames.length);
11836        // List of package names for whom the suspended state is not set as requested in this
11837        // method.
11838        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11839        long callingId = Binder.clearCallingIdentity();
11840        try {
11841            for (int i = 0; i < packageNames.length; i++) {
11842                String packageName = packageNames[i];
11843                boolean changed = false;
11844                final int appId;
11845                synchronized (mPackages) {
11846                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11847                    if (pkgSetting == null) {
11848                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11849                                + "\". Skipping suspending/un-suspending.");
11850                        unactionedPackages.add(packageName);
11851                        continue;
11852                    }
11853                    appId = pkgSetting.appId;
11854                    if (pkgSetting.getSuspended(userId) != suspended) {
11855                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11856                            unactionedPackages.add(packageName);
11857                            continue;
11858                        }
11859                        pkgSetting.setSuspended(suspended, userId);
11860                        mSettings.writePackageRestrictionsLPr(userId);
11861                        changed = true;
11862                        changedPackages.add(packageName);
11863                    }
11864                }
11865
11866                if (changed && suspended) {
11867                    killApplication(packageName, UserHandle.getUid(userId, appId),
11868                            "suspending package");
11869                }
11870            }
11871        } finally {
11872            Binder.restoreCallingIdentity(callingId);
11873        }
11874
11875        if (!changedPackages.isEmpty()) {
11876            sendPackagesSuspendedForUser(changedPackages.toArray(
11877                    new String[changedPackages.size()]), userId, suspended);
11878        }
11879
11880        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11881    }
11882
11883    @Override
11884    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11885        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11886                true /* requireFullPermission */, false /* checkShell */,
11887                "isPackageSuspendedForUser for user " + userId);
11888        synchronized (mPackages) {
11889            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11890            if (pkgSetting == null) {
11891                throw new IllegalArgumentException("Unknown target package: " + packageName);
11892            }
11893            return pkgSetting.getSuspended(userId);
11894        }
11895    }
11896
11897    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11898        if (isPackageDeviceAdmin(packageName, userId)) {
11899            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11900                    + "\": has an active device admin");
11901            return false;
11902        }
11903
11904        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11905        if (packageName.equals(activeLauncherPackageName)) {
11906            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11907                    + "\": contains the active launcher");
11908            return false;
11909        }
11910
11911        if (packageName.equals(mRequiredInstallerPackage)) {
11912            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11913                    + "\": required for package installation");
11914            return false;
11915        }
11916
11917        if (packageName.equals(mRequiredUninstallerPackage)) {
11918            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11919                    + "\": required for package uninstallation");
11920            return false;
11921        }
11922
11923        if (packageName.equals(mRequiredVerifierPackage)) {
11924            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11925                    + "\": required for package verification");
11926            return false;
11927        }
11928
11929        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11930            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11931                    + "\": is the default dialer");
11932            return false;
11933        }
11934
11935        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11936            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11937                    + "\": protected package");
11938            return false;
11939        }
11940
11941        return true;
11942    }
11943
11944    private String getActiveLauncherPackageName(int userId) {
11945        Intent intent = new Intent(Intent.ACTION_MAIN);
11946        intent.addCategory(Intent.CATEGORY_HOME);
11947        ResolveInfo resolveInfo = resolveIntent(
11948                intent,
11949                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11950                PackageManager.MATCH_DEFAULT_ONLY,
11951                userId);
11952
11953        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11954    }
11955
11956    private String getDefaultDialerPackageName(int userId) {
11957        synchronized (mPackages) {
11958            return mSettings.getDefaultDialerPackageNameLPw(userId);
11959        }
11960    }
11961
11962    @Override
11963    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11964        mContext.enforceCallingOrSelfPermission(
11965                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11966                "Only package verification agents can verify applications");
11967
11968        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11969        final PackageVerificationResponse response = new PackageVerificationResponse(
11970                verificationCode, Binder.getCallingUid());
11971        msg.arg1 = id;
11972        msg.obj = response;
11973        mHandler.sendMessage(msg);
11974    }
11975
11976    @Override
11977    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11978            long millisecondsToDelay) {
11979        mContext.enforceCallingOrSelfPermission(
11980                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11981                "Only package verification agents can extend verification timeouts");
11982
11983        final PackageVerificationState state = mPendingVerification.get(id);
11984        final PackageVerificationResponse response = new PackageVerificationResponse(
11985                verificationCodeAtTimeout, Binder.getCallingUid());
11986
11987        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11988            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11989        }
11990        if (millisecondsToDelay < 0) {
11991            millisecondsToDelay = 0;
11992        }
11993        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11994                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11995            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11996        }
11997
11998        if ((state != null) && !state.timeoutExtended()) {
11999            state.extendTimeout();
12000
12001            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12002            msg.arg1 = id;
12003            msg.obj = response;
12004            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12005        }
12006    }
12007
12008    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12009            int verificationCode, UserHandle user) {
12010        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12011        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12012        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12013        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12014        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12015
12016        mContext.sendBroadcastAsUser(intent, user,
12017                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12018    }
12019
12020    private ComponentName matchComponentForVerifier(String packageName,
12021            List<ResolveInfo> receivers) {
12022        ActivityInfo targetReceiver = null;
12023
12024        final int NR = receivers.size();
12025        for (int i = 0; i < NR; i++) {
12026            final ResolveInfo info = receivers.get(i);
12027            if (info.activityInfo == null) {
12028                continue;
12029            }
12030
12031            if (packageName.equals(info.activityInfo.packageName)) {
12032                targetReceiver = info.activityInfo;
12033                break;
12034            }
12035        }
12036
12037        if (targetReceiver == null) {
12038            return null;
12039        }
12040
12041        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12042    }
12043
12044    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12045            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12046        if (pkgInfo.verifiers.length == 0) {
12047            return null;
12048        }
12049
12050        final int N = pkgInfo.verifiers.length;
12051        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12052        for (int i = 0; i < N; i++) {
12053            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12054
12055            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12056                    receivers);
12057            if (comp == null) {
12058                continue;
12059            }
12060
12061            final int verifierUid = getUidForVerifier(verifierInfo);
12062            if (verifierUid == -1) {
12063                continue;
12064            }
12065
12066            if (DEBUG_VERIFY) {
12067                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12068                        + " with the correct signature");
12069            }
12070            sufficientVerifiers.add(comp);
12071            verificationState.addSufficientVerifier(verifierUid);
12072        }
12073
12074        return sufficientVerifiers;
12075    }
12076
12077    private int getUidForVerifier(VerifierInfo verifierInfo) {
12078        synchronized (mPackages) {
12079            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12080            if (pkg == null) {
12081                return -1;
12082            } else if (pkg.mSignatures.length != 1) {
12083                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12084                        + " has more than one signature; ignoring");
12085                return -1;
12086            }
12087
12088            /*
12089             * If the public key of the package's signature does not match
12090             * our expected public key, then this is a different package and
12091             * we should skip.
12092             */
12093
12094            final byte[] expectedPublicKey;
12095            try {
12096                final Signature verifierSig = pkg.mSignatures[0];
12097                final PublicKey publicKey = verifierSig.getPublicKey();
12098                expectedPublicKey = publicKey.getEncoded();
12099            } catch (CertificateException e) {
12100                return -1;
12101            }
12102
12103            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12104
12105            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12106                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12107                        + " does not have the expected public key; ignoring");
12108                return -1;
12109            }
12110
12111            return pkg.applicationInfo.uid;
12112        }
12113    }
12114
12115    @Override
12116    public void finishPackageInstall(int token, boolean didLaunch) {
12117        enforceSystemOrRoot("Only the system is allowed to finish installs");
12118
12119        if (DEBUG_INSTALL) {
12120            Slog.v(TAG, "BM finishing package install for " + token);
12121        }
12122        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12123
12124        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12125        mHandler.sendMessage(msg);
12126    }
12127
12128    /**
12129     * Get the verification agent timeout.
12130     *
12131     * @return verification timeout in milliseconds
12132     */
12133    private long getVerificationTimeout() {
12134        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12135                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12136                DEFAULT_VERIFICATION_TIMEOUT);
12137    }
12138
12139    /**
12140     * Get the default verification agent response code.
12141     *
12142     * @return default verification response code
12143     */
12144    private int getDefaultVerificationResponse() {
12145        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12146                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12147                DEFAULT_VERIFICATION_RESPONSE);
12148    }
12149
12150    /**
12151     * Check whether or not package verification has been enabled.
12152     *
12153     * @return true if verification should be performed
12154     */
12155    private boolean isVerificationEnabled(int userId, int installFlags) {
12156        if (!DEFAULT_VERIFY_ENABLE) {
12157            return false;
12158        }
12159        // Ephemeral apps don't get the full verification treatment
12160        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12161            if (DEBUG_EPHEMERAL) {
12162                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12163            }
12164            return false;
12165        }
12166
12167        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12168
12169        // Check if installing from ADB
12170        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12171            // Do not run verification in a test harness environment
12172            if (ActivityManager.isRunningInTestHarness()) {
12173                return false;
12174            }
12175            if (ensureVerifyAppsEnabled) {
12176                return true;
12177            }
12178            // Check if the developer does not want package verification for ADB installs
12179            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12180                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12181                return false;
12182            }
12183        }
12184
12185        if (ensureVerifyAppsEnabled) {
12186            return true;
12187        }
12188
12189        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12190                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12191    }
12192
12193    @Override
12194    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12195            throws RemoteException {
12196        mContext.enforceCallingOrSelfPermission(
12197                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12198                "Only intentfilter verification agents can verify applications");
12199
12200        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12201        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12202                Binder.getCallingUid(), verificationCode, failedDomains);
12203        msg.arg1 = id;
12204        msg.obj = response;
12205        mHandler.sendMessage(msg);
12206    }
12207
12208    @Override
12209    public int getIntentVerificationStatus(String packageName, int userId) {
12210        synchronized (mPackages) {
12211            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12212        }
12213    }
12214
12215    @Override
12216    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12217        mContext.enforceCallingOrSelfPermission(
12218                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12219
12220        boolean result = false;
12221        synchronized (mPackages) {
12222            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12223        }
12224        if (result) {
12225            scheduleWritePackageRestrictionsLocked(userId);
12226        }
12227        return result;
12228    }
12229
12230    @Override
12231    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12232            String packageName) {
12233        synchronized (mPackages) {
12234            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12235        }
12236    }
12237
12238    @Override
12239    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12240        if (TextUtils.isEmpty(packageName)) {
12241            return ParceledListSlice.emptyList();
12242        }
12243        synchronized (mPackages) {
12244            PackageParser.Package pkg = mPackages.get(packageName);
12245            if (pkg == null || pkg.activities == null) {
12246                return ParceledListSlice.emptyList();
12247            }
12248            final int count = pkg.activities.size();
12249            ArrayList<IntentFilter> result = new ArrayList<>();
12250            for (int n=0; n<count; n++) {
12251                PackageParser.Activity activity = pkg.activities.get(n);
12252                if (activity.intents != null && activity.intents.size() > 0) {
12253                    result.addAll(activity.intents);
12254                }
12255            }
12256            return new ParceledListSlice<>(result);
12257        }
12258    }
12259
12260    @Override
12261    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12262        mContext.enforceCallingOrSelfPermission(
12263                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12264
12265        synchronized (mPackages) {
12266            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12267            if (packageName != null) {
12268                result |= updateIntentVerificationStatus(packageName,
12269                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12270                        userId);
12271                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12272                        packageName, userId);
12273            }
12274            return result;
12275        }
12276    }
12277
12278    @Override
12279    public String getDefaultBrowserPackageName(int userId) {
12280        synchronized (mPackages) {
12281            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12282        }
12283    }
12284
12285    /**
12286     * Get the "allow unknown sources" setting.
12287     *
12288     * @return the current "allow unknown sources" setting
12289     */
12290    private int getUnknownSourcesSettings() {
12291        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12292                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12293                -1);
12294    }
12295
12296    @Override
12297    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12298        final int uid = Binder.getCallingUid();
12299        // writer
12300        synchronized (mPackages) {
12301            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12302            if (targetPackageSetting == null) {
12303                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12304            }
12305
12306            PackageSetting installerPackageSetting;
12307            if (installerPackageName != null) {
12308                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12309                if (installerPackageSetting == null) {
12310                    throw new IllegalArgumentException("Unknown installer package: "
12311                            + installerPackageName);
12312                }
12313            } else {
12314                installerPackageSetting = null;
12315            }
12316
12317            Signature[] callerSignature;
12318            Object obj = mSettings.getUserIdLPr(uid);
12319            if (obj != null) {
12320                if (obj instanceof SharedUserSetting) {
12321                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12322                } else if (obj instanceof PackageSetting) {
12323                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12324                } else {
12325                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12326                }
12327            } else {
12328                throw new SecurityException("Unknown calling UID: " + uid);
12329            }
12330
12331            // Verify: can't set installerPackageName to a package that is
12332            // not signed with the same cert as the caller.
12333            if (installerPackageSetting != null) {
12334                if (compareSignatures(callerSignature,
12335                        installerPackageSetting.signatures.mSignatures)
12336                        != PackageManager.SIGNATURE_MATCH) {
12337                    throw new SecurityException(
12338                            "Caller does not have same cert as new installer package "
12339                            + installerPackageName);
12340                }
12341            }
12342
12343            // Verify: if target already has an installer package, it must
12344            // be signed with the same cert as the caller.
12345            if (targetPackageSetting.installerPackageName != null) {
12346                PackageSetting setting = mSettings.mPackages.get(
12347                        targetPackageSetting.installerPackageName);
12348                // If the currently set package isn't valid, then it's always
12349                // okay to change it.
12350                if (setting != null) {
12351                    if (compareSignatures(callerSignature,
12352                            setting.signatures.mSignatures)
12353                            != PackageManager.SIGNATURE_MATCH) {
12354                        throw new SecurityException(
12355                                "Caller does not have same cert as old installer package "
12356                                + targetPackageSetting.installerPackageName);
12357                    }
12358                }
12359            }
12360
12361            // Okay!
12362            targetPackageSetting.installerPackageName = installerPackageName;
12363            if (installerPackageName != null) {
12364                mSettings.mInstallerPackages.add(installerPackageName);
12365            }
12366            scheduleWriteSettingsLocked();
12367        }
12368    }
12369
12370    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12371        // Queue up an async operation since the package installation may take a little while.
12372        mHandler.post(new Runnable() {
12373            public void run() {
12374                mHandler.removeCallbacks(this);
12375                 // Result object to be returned
12376                PackageInstalledInfo res = new PackageInstalledInfo();
12377                res.setReturnCode(currentStatus);
12378                res.uid = -1;
12379                res.pkg = null;
12380                res.removedInfo = null;
12381                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12382                    args.doPreInstall(res.returnCode);
12383                    synchronized (mInstallLock) {
12384                        installPackageTracedLI(args, res);
12385                    }
12386                    args.doPostInstall(res.returnCode, res.uid);
12387                }
12388
12389                // A restore should be performed at this point if (a) the install
12390                // succeeded, (b) the operation is not an update, and (c) the new
12391                // package has not opted out of backup participation.
12392                final boolean update = res.removedInfo != null
12393                        && res.removedInfo.removedPackage != null;
12394                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12395                boolean doRestore = !update
12396                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12397
12398                // Set up the post-install work request bookkeeping.  This will be used
12399                // and cleaned up by the post-install event handling regardless of whether
12400                // there's a restore pass performed.  Token values are >= 1.
12401                int token;
12402                if (mNextInstallToken < 0) mNextInstallToken = 1;
12403                token = mNextInstallToken++;
12404
12405                PostInstallData data = new PostInstallData(args, res);
12406                mRunningInstalls.put(token, data);
12407                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12408
12409                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12410                    // Pass responsibility to the Backup Manager.  It will perform a
12411                    // restore if appropriate, then pass responsibility back to the
12412                    // Package Manager to run the post-install observer callbacks
12413                    // and broadcasts.
12414                    IBackupManager bm = IBackupManager.Stub.asInterface(
12415                            ServiceManager.getService(Context.BACKUP_SERVICE));
12416                    if (bm != null) {
12417                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12418                                + " to BM for possible restore");
12419                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12420                        try {
12421                            // TODO: http://b/22388012
12422                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12423                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12424                            } else {
12425                                doRestore = false;
12426                            }
12427                        } catch (RemoteException e) {
12428                            // can't happen; the backup manager is local
12429                        } catch (Exception e) {
12430                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12431                            doRestore = false;
12432                        }
12433                    } else {
12434                        Slog.e(TAG, "Backup Manager not found!");
12435                        doRestore = false;
12436                    }
12437                }
12438
12439                if (!doRestore) {
12440                    // No restore possible, or the Backup Manager was mysteriously not
12441                    // available -- just fire the post-install work request directly.
12442                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12443
12444                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12445
12446                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12447                    mHandler.sendMessage(msg);
12448                }
12449            }
12450        });
12451    }
12452
12453    /**
12454     * Callback from PackageSettings whenever an app is first transitioned out of the
12455     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12456     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12457     * here whether the app is the target of an ongoing install, and only send the
12458     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12459     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12460     * handling.
12461     */
12462    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12463        // Serialize this with the rest of the install-process message chain.  In the
12464        // restore-at-install case, this Runnable will necessarily run before the
12465        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12466        // are coherent.  In the non-restore case, the app has already completed install
12467        // and been launched through some other means, so it is not in a problematic
12468        // state for observers to see the FIRST_LAUNCH signal.
12469        mHandler.post(new Runnable() {
12470            @Override
12471            public void run() {
12472                for (int i = 0; i < mRunningInstalls.size(); i++) {
12473                    final PostInstallData data = mRunningInstalls.valueAt(i);
12474                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12475                        continue;
12476                    }
12477                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12478                        // right package; but is it for the right user?
12479                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12480                            if (userId == data.res.newUsers[uIndex]) {
12481                                if (DEBUG_BACKUP) {
12482                                    Slog.i(TAG, "Package " + pkgName
12483                                            + " being restored so deferring FIRST_LAUNCH");
12484                                }
12485                                return;
12486                            }
12487                        }
12488                    }
12489                }
12490                // didn't find it, so not being restored
12491                if (DEBUG_BACKUP) {
12492                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12493                }
12494                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12495            }
12496        });
12497    }
12498
12499    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12500        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12501                installerPkg, null, userIds);
12502    }
12503
12504    private abstract class HandlerParams {
12505        private static final int MAX_RETRIES = 4;
12506
12507        /**
12508         * Number of times startCopy() has been attempted and had a non-fatal
12509         * error.
12510         */
12511        private int mRetries = 0;
12512
12513        /** User handle for the user requesting the information or installation. */
12514        private final UserHandle mUser;
12515        String traceMethod;
12516        int traceCookie;
12517
12518        HandlerParams(UserHandle user) {
12519            mUser = user;
12520        }
12521
12522        UserHandle getUser() {
12523            return mUser;
12524        }
12525
12526        HandlerParams setTraceMethod(String traceMethod) {
12527            this.traceMethod = traceMethod;
12528            return this;
12529        }
12530
12531        HandlerParams setTraceCookie(int traceCookie) {
12532            this.traceCookie = traceCookie;
12533            return this;
12534        }
12535
12536        final boolean startCopy() {
12537            boolean res;
12538            try {
12539                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12540
12541                if (++mRetries > MAX_RETRIES) {
12542                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12543                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12544                    handleServiceError();
12545                    return false;
12546                } else {
12547                    handleStartCopy();
12548                    res = true;
12549                }
12550            } catch (RemoteException e) {
12551                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12552                mHandler.sendEmptyMessage(MCS_RECONNECT);
12553                res = false;
12554            }
12555            handleReturnCode();
12556            return res;
12557        }
12558
12559        final void serviceError() {
12560            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12561            handleServiceError();
12562            handleReturnCode();
12563        }
12564
12565        abstract void handleStartCopy() throws RemoteException;
12566        abstract void handleServiceError();
12567        abstract void handleReturnCode();
12568    }
12569
12570    class MeasureParams extends HandlerParams {
12571        private final PackageStats mStats;
12572        private boolean mSuccess;
12573
12574        private final IPackageStatsObserver mObserver;
12575
12576        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12577            super(new UserHandle(stats.userHandle));
12578            mObserver = observer;
12579            mStats = stats;
12580        }
12581
12582        @Override
12583        public String toString() {
12584            return "MeasureParams{"
12585                + Integer.toHexString(System.identityHashCode(this))
12586                + " " + mStats.packageName + "}";
12587        }
12588
12589        @Override
12590        void handleStartCopy() throws RemoteException {
12591            synchronized (mInstallLock) {
12592                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12593            }
12594
12595            if (mSuccess) {
12596                boolean mounted = false;
12597                try {
12598                    final String status = Environment.getExternalStorageState();
12599                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12600                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12601                } catch (Exception e) {
12602                }
12603
12604                if (mounted) {
12605                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12606
12607                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12608                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12609
12610                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12611                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12612
12613                    // Always subtract cache size, since it's a subdirectory
12614                    mStats.externalDataSize -= mStats.externalCacheSize;
12615
12616                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12617                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12618
12619                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12620                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12621                }
12622            }
12623        }
12624
12625        @Override
12626        void handleReturnCode() {
12627            if (mObserver != null) {
12628                try {
12629                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12630                } catch (RemoteException e) {
12631                    Slog.i(TAG, "Observer no longer exists.");
12632                }
12633            }
12634        }
12635
12636        @Override
12637        void handleServiceError() {
12638            Slog.e(TAG, "Could not measure application " + mStats.packageName
12639                            + " external storage");
12640        }
12641    }
12642
12643    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12644            throws RemoteException {
12645        long result = 0;
12646        for (File path : paths) {
12647            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12648        }
12649        return result;
12650    }
12651
12652    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12653        for (File path : paths) {
12654            try {
12655                mcs.clearDirectory(path.getAbsolutePath());
12656            } catch (RemoteException e) {
12657            }
12658        }
12659    }
12660
12661    static class OriginInfo {
12662        /**
12663         * Location where install is coming from, before it has been
12664         * copied/renamed into place. This could be a single monolithic APK
12665         * file, or a cluster directory. This location may be untrusted.
12666         */
12667        final File file;
12668        final String cid;
12669
12670        /**
12671         * Flag indicating that {@link #file} or {@link #cid} has already been
12672         * staged, meaning downstream users don't need to defensively copy the
12673         * contents.
12674         */
12675        final boolean staged;
12676
12677        /**
12678         * Flag indicating that {@link #file} or {@link #cid} is an already
12679         * installed app that is being moved.
12680         */
12681        final boolean existing;
12682
12683        final String resolvedPath;
12684        final File resolvedFile;
12685
12686        static OriginInfo fromNothing() {
12687            return new OriginInfo(null, null, false, false);
12688        }
12689
12690        static OriginInfo fromUntrustedFile(File file) {
12691            return new OriginInfo(file, null, false, false);
12692        }
12693
12694        static OriginInfo fromExistingFile(File file) {
12695            return new OriginInfo(file, null, false, true);
12696        }
12697
12698        static OriginInfo fromStagedFile(File file) {
12699            return new OriginInfo(file, null, true, false);
12700        }
12701
12702        static OriginInfo fromStagedContainer(String cid) {
12703            return new OriginInfo(null, cid, true, false);
12704        }
12705
12706        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12707            this.file = file;
12708            this.cid = cid;
12709            this.staged = staged;
12710            this.existing = existing;
12711
12712            if (cid != null) {
12713                resolvedPath = PackageHelper.getSdDir(cid);
12714                resolvedFile = new File(resolvedPath);
12715            } else if (file != null) {
12716                resolvedPath = file.getAbsolutePath();
12717                resolvedFile = file;
12718            } else {
12719                resolvedPath = null;
12720                resolvedFile = null;
12721            }
12722        }
12723    }
12724
12725    static class MoveInfo {
12726        final int moveId;
12727        final String fromUuid;
12728        final String toUuid;
12729        final String packageName;
12730        final String dataAppName;
12731        final int appId;
12732        final String seinfo;
12733        final int targetSdkVersion;
12734
12735        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12736                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12737            this.moveId = moveId;
12738            this.fromUuid = fromUuid;
12739            this.toUuid = toUuid;
12740            this.packageName = packageName;
12741            this.dataAppName = dataAppName;
12742            this.appId = appId;
12743            this.seinfo = seinfo;
12744            this.targetSdkVersion = targetSdkVersion;
12745        }
12746    }
12747
12748    static class VerificationInfo {
12749        /** A constant used to indicate that a uid value is not present. */
12750        public static final int NO_UID = -1;
12751
12752        /** URI referencing where the package was downloaded from. */
12753        final Uri originatingUri;
12754
12755        /** HTTP referrer URI associated with the originatingURI. */
12756        final Uri referrer;
12757
12758        /** UID of the application that the install request originated from. */
12759        final int originatingUid;
12760
12761        /** UID of application requesting the install */
12762        final int installerUid;
12763
12764        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12765            this.originatingUri = originatingUri;
12766            this.referrer = referrer;
12767            this.originatingUid = originatingUid;
12768            this.installerUid = installerUid;
12769        }
12770    }
12771
12772    class InstallParams extends HandlerParams {
12773        final OriginInfo origin;
12774        final MoveInfo move;
12775        final IPackageInstallObserver2 observer;
12776        int installFlags;
12777        final String installerPackageName;
12778        final String volumeUuid;
12779        private InstallArgs mArgs;
12780        private int mRet;
12781        final String packageAbiOverride;
12782        final String[] grantedRuntimePermissions;
12783        final VerificationInfo verificationInfo;
12784        final Certificate[][] certificates;
12785
12786        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12787                int installFlags, String installerPackageName, String volumeUuid,
12788                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12789                String[] grantedPermissions, Certificate[][] certificates) {
12790            super(user);
12791            this.origin = origin;
12792            this.move = move;
12793            this.observer = observer;
12794            this.installFlags = installFlags;
12795            this.installerPackageName = installerPackageName;
12796            this.volumeUuid = volumeUuid;
12797            this.verificationInfo = verificationInfo;
12798            this.packageAbiOverride = packageAbiOverride;
12799            this.grantedRuntimePermissions = grantedPermissions;
12800            this.certificates = certificates;
12801        }
12802
12803        @Override
12804        public String toString() {
12805            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12806                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12807        }
12808
12809        private int installLocationPolicy(PackageInfoLite pkgLite) {
12810            String packageName = pkgLite.packageName;
12811            int installLocation = pkgLite.installLocation;
12812            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12813            // reader
12814            synchronized (mPackages) {
12815                // Currently installed package which the new package is attempting to replace or
12816                // null if no such package is installed.
12817                PackageParser.Package installedPkg = mPackages.get(packageName);
12818                // Package which currently owns the data which the new package will own if installed.
12819                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12820                // will be null whereas dataOwnerPkg will contain information about the package
12821                // which was uninstalled while keeping its data.
12822                PackageParser.Package dataOwnerPkg = installedPkg;
12823                if (dataOwnerPkg  == null) {
12824                    PackageSetting ps = mSettings.mPackages.get(packageName);
12825                    if (ps != null) {
12826                        dataOwnerPkg = ps.pkg;
12827                    }
12828                }
12829
12830                if (dataOwnerPkg != null) {
12831                    // If installed, the package will get access to data left on the device by its
12832                    // predecessor. As a security measure, this is permited only if this is not a
12833                    // version downgrade or if the predecessor package is marked as debuggable and
12834                    // a downgrade is explicitly requested.
12835                    //
12836                    // On debuggable platform builds, downgrades are permitted even for
12837                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12838                    // not offer security guarantees and thus it's OK to disable some security
12839                    // mechanisms to make debugging/testing easier on those builds. However, even on
12840                    // debuggable builds downgrades of packages are permitted only if requested via
12841                    // installFlags. This is because we aim to keep the behavior of debuggable
12842                    // platform builds as close as possible to the behavior of non-debuggable
12843                    // platform builds.
12844                    final boolean downgradeRequested =
12845                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12846                    final boolean packageDebuggable =
12847                                (dataOwnerPkg.applicationInfo.flags
12848                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12849                    final boolean downgradePermitted =
12850                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12851                    if (!downgradePermitted) {
12852                        try {
12853                            checkDowngrade(dataOwnerPkg, pkgLite);
12854                        } catch (PackageManagerException e) {
12855                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12856                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12857                        }
12858                    }
12859                }
12860
12861                if (installedPkg != null) {
12862                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12863                        // Check for updated system application.
12864                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12865                            if (onSd) {
12866                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12867                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12868                            }
12869                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12870                        } else {
12871                            if (onSd) {
12872                                // Install flag overrides everything.
12873                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12874                            }
12875                            // If current upgrade specifies particular preference
12876                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12877                                // Application explicitly specified internal.
12878                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12879                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12880                                // App explictly prefers external. Let policy decide
12881                            } else {
12882                                // Prefer previous location
12883                                if (isExternal(installedPkg)) {
12884                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12885                                }
12886                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12887                            }
12888                        }
12889                    } else {
12890                        // Invalid install. Return error code
12891                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12892                    }
12893                }
12894            }
12895            // All the special cases have been taken care of.
12896            // Return result based on recommended install location.
12897            if (onSd) {
12898                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12899            }
12900            return pkgLite.recommendedInstallLocation;
12901        }
12902
12903        /*
12904         * Invoke remote method to get package information and install
12905         * location values. Override install location based on default
12906         * policy if needed and then create install arguments based
12907         * on the install location.
12908         */
12909        public void handleStartCopy() throws RemoteException {
12910            int ret = PackageManager.INSTALL_SUCCEEDED;
12911
12912            // If we're already staged, we've firmly committed to an install location
12913            if (origin.staged) {
12914                if (origin.file != null) {
12915                    installFlags |= PackageManager.INSTALL_INTERNAL;
12916                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12917                } else if (origin.cid != null) {
12918                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12919                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12920                } else {
12921                    throw new IllegalStateException("Invalid stage location");
12922                }
12923            }
12924
12925            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12926            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12927            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12928            PackageInfoLite pkgLite = null;
12929
12930            if (onInt && onSd) {
12931                // Check if both bits are set.
12932                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12933                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12934            } else if (onSd && ephemeral) {
12935                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12936                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12937            } else {
12938                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12939                        packageAbiOverride);
12940
12941                if (DEBUG_EPHEMERAL && ephemeral) {
12942                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12943                }
12944
12945                /*
12946                 * If we have too little free space, try to free cache
12947                 * before giving up.
12948                 */
12949                if (!origin.staged && pkgLite.recommendedInstallLocation
12950                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12951                    // TODO: focus freeing disk space on the target device
12952                    final StorageManager storage = StorageManager.from(mContext);
12953                    final long lowThreshold = storage.getStorageLowBytes(
12954                            Environment.getDataDirectory());
12955
12956                    final long sizeBytes = mContainerService.calculateInstalledSize(
12957                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12958
12959                    try {
12960                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12961                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12962                                installFlags, packageAbiOverride);
12963                    } catch (InstallerException e) {
12964                        Slog.w(TAG, "Failed to free cache", e);
12965                    }
12966
12967                    /*
12968                     * The cache free must have deleted the file we
12969                     * downloaded to install.
12970                     *
12971                     * TODO: fix the "freeCache" call to not delete
12972                     *       the file we care about.
12973                     */
12974                    if (pkgLite.recommendedInstallLocation
12975                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12976                        pkgLite.recommendedInstallLocation
12977                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12978                    }
12979                }
12980            }
12981
12982            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12983                int loc = pkgLite.recommendedInstallLocation;
12984                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12985                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12986                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12987                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12988                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12989                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12990                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12991                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12992                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12993                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12994                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12995                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12996                } else {
12997                    // Override with defaults if needed.
12998                    loc = installLocationPolicy(pkgLite);
12999                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13000                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13001                    } else if (!onSd && !onInt) {
13002                        // Override install location with flags
13003                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13004                            // Set the flag to install on external media.
13005                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13006                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13007                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13008                            if (DEBUG_EPHEMERAL) {
13009                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13010                            }
13011                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13012                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13013                                    |PackageManager.INSTALL_INTERNAL);
13014                        } else {
13015                            // Make sure the flag for installing on external
13016                            // media is unset
13017                            installFlags |= PackageManager.INSTALL_INTERNAL;
13018                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13019                        }
13020                    }
13021                }
13022            }
13023
13024            final InstallArgs args = createInstallArgs(this);
13025            mArgs = args;
13026
13027            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13028                // TODO: http://b/22976637
13029                // Apps installed for "all" users use the device owner to verify the app
13030                UserHandle verifierUser = getUser();
13031                if (verifierUser == UserHandle.ALL) {
13032                    verifierUser = UserHandle.SYSTEM;
13033                }
13034
13035                /*
13036                 * Determine if we have any installed package verifiers. If we
13037                 * do, then we'll defer to them to verify the packages.
13038                 */
13039                final int requiredUid = mRequiredVerifierPackage == null ? -1
13040                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13041                                verifierUser.getIdentifier());
13042                if (!origin.existing && requiredUid != -1
13043                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13044                    final Intent verification = new Intent(
13045                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13046                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13047                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13048                            PACKAGE_MIME_TYPE);
13049                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13050
13051                    // Query all live verifiers based on current user state
13052                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13053                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13054
13055                    if (DEBUG_VERIFY) {
13056                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13057                                + verification.toString() + " with " + pkgLite.verifiers.length
13058                                + " optional verifiers");
13059                    }
13060
13061                    final int verificationId = mPendingVerificationToken++;
13062
13063                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13064
13065                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13066                            installerPackageName);
13067
13068                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13069                            installFlags);
13070
13071                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13072                            pkgLite.packageName);
13073
13074                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13075                            pkgLite.versionCode);
13076
13077                    if (verificationInfo != null) {
13078                        if (verificationInfo.originatingUri != null) {
13079                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13080                                    verificationInfo.originatingUri);
13081                        }
13082                        if (verificationInfo.referrer != null) {
13083                            verification.putExtra(Intent.EXTRA_REFERRER,
13084                                    verificationInfo.referrer);
13085                        }
13086                        if (verificationInfo.originatingUid >= 0) {
13087                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13088                                    verificationInfo.originatingUid);
13089                        }
13090                        if (verificationInfo.installerUid >= 0) {
13091                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13092                                    verificationInfo.installerUid);
13093                        }
13094                    }
13095
13096                    final PackageVerificationState verificationState = new PackageVerificationState(
13097                            requiredUid, args);
13098
13099                    mPendingVerification.append(verificationId, verificationState);
13100
13101                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13102                            receivers, verificationState);
13103
13104                    /*
13105                     * If any sufficient verifiers were listed in the package
13106                     * manifest, attempt to ask them.
13107                     */
13108                    if (sufficientVerifiers != null) {
13109                        final int N = sufficientVerifiers.size();
13110                        if (N == 0) {
13111                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13112                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13113                        } else {
13114                            for (int i = 0; i < N; i++) {
13115                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13116
13117                                final Intent sufficientIntent = new Intent(verification);
13118                                sufficientIntent.setComponent(verifierComponent);
13119                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13120                            }
13121                        }
13122                    }
13123
13124                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13125                            mRequiredVerifierPackage, receivers);
13126                    if (ret == PackageManager.INSTALL_SUCCEEDED
13127                            && mRequiredVerifierPackage != null) {
13128                        Trace.asyncTraceBegin(
13129                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13130                        /*
13131                         * Send the intent to the required verification agent,
13132                         * but only start the verification timeout after the
13133                         * target BroadcastReceivers have run.
13134                         */
13135                        verification.setComponent(requiredVerifierComponent);
13136                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13137                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13138                                new BroadcastReceiver() {
13139                                    @Override
13140                                    public void onReceive(Context context, Intent intent) {
13141                                        final Message msg = mHandler
13142                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13143                                        msg.arg1 = verificationId;
13144                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13145                                    }
13146                                }, null, 0, null, null);
13147
13148                        /*
13149                         * We don't want the copy to proceed until verification
13150                         * succeeds, so null out this field.
13151                         */
13152                        mArgs = null;
13153                    }
13154                } else {
13155                    /*
13156                     * No package verification is enabled, so immediately start
13157                     * the remote call to initiate copy using temporary file.
13158                     */
13159                    ret = args.copyApk(mContainerService, true);
13160                }
13161            }
13162
13163            mRet = ret;
13164        }
13165
13166        @Override
13167        void handleReturnCode() {
13168            // If mArgs is null, then MCS couldn't be reached. When it
13169            // reconnects, it will try again to install. At that point, this
13170            // will succeed.
13171            if (mArgs != null) {
13172                processPendingInstall(mArgs, mRet);
13173            }
13174        }
13175
13176        @Override
13177        void handleServiceError() {
13178            mArgs = createInstallArgs(this);
13179            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13180        }
13181
13182        public boolean isForwardLocked() {
13183            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13184        }
13185    }
13186
13187    /**
13188     * Used during creation of InstallArgs
13189     *
13190     * @param installFlags package installation flags
13191     * @return true if should be installed on external storage
13192     */
13193    private static boolean installOnExternalAsec(int installFlags) {
13194        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13195            return false;
13196        }
13197        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13198            return true;
13199        }
13200        return false;
13201    }
13202
13203    /**
13204     * Used during creation of InstallArgs
13205     *
13206     * @param installFlags package installation flags
13207     * @return true if should be installed as forward locked
13208     */
13209    private static boolean installForwardLocked(int installFlags) {
13210        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13211    }
13212
13213    private InstallArgs createInstallArgs(InstallParams params) {
13214        if (params.move != null) {
13215            return new MoveInstallArgs(params);
13216        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13217            return new AsecInstallArgs(params);
13218        } else {
13219            return new FileInstallArgs(params);
13220        }
13221    }
13222
13223    /**
13224     * Create args that describe an existing installed package. Typically used
13225     * when cleaning up old installs, or used as a move source.
13226     */
13227    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13228            String resourcePath, String[] instructionSets) {
13229        final boolean isInAsec;
13230        if (installOnExternalAsec(installFlags)) {
13231            /* Apps on SD card are always in ASEC containers. */
13232            isInAsec = true;
13233        } else if (installForwardLocked(installFlags)
13234                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13235            /*
13236             * Forward-locked apps are only in ASEC containers if they're the
13237             * new style
13238             */
13239            isInAsec = true;
13240        } else {
13241            isInAsec = false;
13242        }
13243
13244        if (isInAsec) {
13245            return new AsecInstallArgs(codePath, instructionSets,
13246                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13247        } else {
13248            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13249        }
13250    }
13251
13252    static abstract class InstallArgs {
13253        /** @see InstallParams#origin */
13254        final OriginInfo origin;
13255        /** @see InstallParams#move */
13256        final MoveInfo move;
13257
13258        final IPackageInstallObserver2 observer;
13259        // Always refers to PackageManager flags only
13260        final int installFlags;
13261        final String installerPackageName;
13262        final String volumeUuid;
13263        final UserHandle user;
13264        final String abiOverride;
13265        final String[] installGrantPermissions;
13266        /** If non-null, drop an async trace when the install completes */
13267        final String traceMethod;
13268        final int traceCookie;
13269        final Certificate[][] certificates;
13270
13271        // The list of instruction sets supported by this app. This is currently
13272        // only used during the rmdex() phase to clean up resources. We can get rid of this
13273        // if we move dex files under the common app path.
13274        /* nullable */ String[] instructionSets;
13275
13276        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13277                int installFlags, String installerPackageName, String volumeUuid,
13278                UserHandle user, String[] instructionSets,
13279                String abiOverride, String[] installGrantPermissions,
13280                String traceMethod, int traceCookie, Certificate[][] certificates) {
13281            this.origin = origin;
13282            this.move = move;
13283            this.installFlags = installFlags;
13284            this.observer = observer;
13285            this.installerPackageName = installerPackageName;
13286            this.volumeUuid = volumeUuid;
13287            this.user = user;
13288            this.instructionSets = instructionSets;
13289            this.abiOverride = abiOverride;
13290            this.installGrantPermissions = installGrantPermissions;
13291            this.traceMethod = traceMethod;
13292            this.traceCookie = traceCookie;
13293            this.certificates = certificates;
13294        }
13295
13296        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13297        abstract int doPreInstall(int status);
13298
13299        /**
13300         * Rename package into final resting place. All paths on the given
13301         * scanned package should be updated to reflect the rename.
13302         */
13303        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13304        abstract int doPostInstall(int status, int uid);
13305
13306        /** @see PackageSettingBase#codePathString */
13307        abstract String getCodePath();
13308        /** @see PackageSettingBase#resourcePathString */
13309        abstract String getResourcePath();
13310
13311        // Need installer lock especially for dex file removal.
13312        abstract void cleanUpResourcesLI();
13313        abstract boolean doPostDeleteLI(boolean delete);
13314
13315        /**
13316         * Called before the source arguments are copied. This is used mostly
13317         * for MoveParams when it needs to read the source file to put it in the
13318         * destination.
13319         */
13320        int doPreCopy() {
13321            return PackageManager.INSTALL_SUCCEEDED;
13322        }
13323
13324        /**
13325         * Called after the source arguments are copied. This is used mostly for
13326         * MoveParams when it needs to read the source file to put it in the
13327         * destination.
13328         */
13329        int doPostCopy(int uid) {
13330            return PackageManager.INSTALL_SUCCEEDED;
13331        }
13332
13333        protected boolean isFwdLocked() {
13334            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13335        }
13336
13337        protected boolean isExternalAsec() {
13338            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13339        }
13340
13341        protected boolean isEphemeral() {
13342            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13343        }
13344
13345        UserHandle getUser() {
13346            return user;
13347        }
13348    }
13349
13350    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13351        if (!allCodePaths.isEmpty()) {
13352            if (instructionSets == null) {
13353                throw new IllegalStateException("instructionSet == null");
13354            }
13355            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13356            for (String codePath : allCodePaths) {
13357                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13358                    try {
13359                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13360                    } catch (InstallerException ignored) {
13361                    }
13362                }
13363            }
13364        }
13365    }
13366
13367    /**
13368     * Logic to handle installation of non-ASEC applications, including copying
13369     * and renaming logic.
13370     */
13371    class FileInstallArgs extends InstallArgs {
13372        private File codeFile;
13373        private File resourceFile;
13374
13375        // Example topology:
13376        // /data/app/com.example/base.apk
13377        // /data/app/com.example/split_foo.apk
13378        // /data/app/com.example/lib/arm/libfoo.so
13379        // /data/app/com.example/lib/arm64/libfoo.so
13380        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13381
13382        /** New install */
13383        FileInstallArgs(InstallParams params) {
13384            super(params.origin, params.move, params.observer, params.installFlags,
13385                    params.installerPackageName, params.volumeUuid,
13386                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13387                    params.grantedRuntimePermissions,
13388                    params.traceMethod, params.traceCookie, params.certificates);
13389            if (isFwdLocked()) {
13390                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13391            }
13392        }
13393
13394        /** Existing install */
13395        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13396            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13397                    null, null, null, 0, null /*certificates*/);
13398            this.codeFile = (codePath != null) ? new File(codePath) : null;
13399            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13400        }
13401
13402        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13403            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13404            try {
13405                return doCopyApk(imcs, temp);
13406            } finally {
13407                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13408            }
13409        }
13410
13411        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13412            if (origin.staged) {
13413                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13414                codeFile = origin.file;
13415                resourceFile = origin.file;
13416                return PackageManager.INSTALL_SUCCEEDED;
13417            }
13418
13419            try {
13420                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13421                final File tempDir =
13422                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13423                codeFile = tempDir;
13424                resourceFile = tempDir;
13425            } catch (IOException e) {
13426                Slog.w(TAG, "Failed to create copy file: " + e);
13427                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13428            }
13429
13430            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13431                @Override
13432                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13433                    if (!FileUtils.isValidExtFilename(name)) {
13434                        throw new IllegalArgumentException("Invalid filename: " + name);
13435                    }
13436                    try {
13437                        final File file = new File(codeFile, name);
13438                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13439                                O_RDWR | O_CREAT, 0644);
13440                        Os.chmod(file.getAbsolutePath(), 0644);
13441                        return new ParcelFileDescriptor(fd);
13442                    } catch (ErrnoException e) {
13443                        throw new RemoteException("Failed to open: " + e.getMessage());
13444                    }
13445                }
13446            };
13447
13448            int ret = PackageManager.INSTALL_SUCCEEDED;
13449            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13450            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13451                Slog.e(TAG, "Failed to copy package");
13452                return ret;
13453            }
13454
13455            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13456            NativeLibraryHelper.Handle handle = null;
13457            try {
13458                handle = NativeLibraryHelper.Handle.create(codeFile);
13459                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13460                        abiOverride);
13461            } catch (IOException e) {
13462                Slog.e(TAG, "Copying native libraries failed", e);
13463                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13464            } finally {
13465                IoUtils.closeQuietly(handle);
13466            }
13467
13468            return ret;
13469        }
13470
13471        int doPreInstall(int status) {
13472            if (status != PackageManager.INSTALL_SUCCEEDED) {
13473                cleanUp();
13474            }
13475            return status;
13476        }
13477
13478        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13479            if (status != PackageManager.INSTALL_SUCCEEDED) {
13480                cleanUp();
13481                return false;
13482            }
13483
13484            final File targetDir = codeFile.getParentFile();
13485            final File beforeCodeFile = codeFile;
13486            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13487
13488            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13489            try {
13490                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13491            } catch (ErrnoException e) {
13492                Slog.w(TAG, "Failed to rename", e);
13493                return false;
13494            }
13495
13496            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13497                Slog.w(TAG, "Failed to restorecon");
13498                return false;
13499            }
13500
13501            // Reflect the rename internally
13502            codeFile = afterCodeFile;
13503            resourceFile = afterCodeFile;
13504
13505            // Reflect the rename in scanned details
13506            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13507            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13508                    afterCodeFile, pkg.baseCodePath));
13509            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13510                    afterCodeFile, pkg.splitCodePaths));
13511
13512            // Reflect the rename in app info
13513            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13514            pkg.setApplicationInfoCodePath(pkg.codePath);
13515            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13516            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13517            pkg.setApplicationInfoResourcePath(pkg.codePath);
13518            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13519            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13520
13521            return true;
13522        }
13523
13524        int doPostInstall(int status, int uid) {
13525            if (status != PackageManager.INSTALL_SUCCEEDED) {
13526                cleanUp();
13527            }
13528            return status;
13529        }
13530
13531        @Override
13532        String getCodePath() {
13533            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13534        }
13535
13536        @Override
13537        String getResourcePath() {
13538            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13539        }
13540
13541        private boolean cleanUp() {
13542            if (codeFile == null || !codeFile.exists()) {
13543                return false;
13544            }
13545
13546            removeCodePathLI(codeFile);
13547
13548            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13549                resourceFile.delete();
13550            }
13551
13552            return true;
13553        }
13554
13555        void cleanUpResourcesLI() {
13556            // Try enumerating all code paths before deleting
13557            List<String> allCodePaths = Collections.EMPTY_LIST;
13558            if (codeFile != null && codeFile.exists()) {
13559                try {
13560                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13561                    allCodePaths = pkg.getAllCodePaths();
13562                } catch (PackageParserException e) {
13563                    // Ignored; we tried our best
13564                }
13565            }
13566
13567            cleanUp();
13568            removeDexFiles(allCodePaths, instructionSets);
13569        }
13570
13571        boolean doPostDeleteLI(boolean delete) {
13572            // XXX err, shouldn't we respect the delete flag?
13573            cleanUpResourcesLI();
13574            return true;
13575        }
13576    }
13577
13578    private boolean isAsecExternal(String cid) {
13579        final String asecPath = PackageHelper.getSdFilesystem(cid);
13580        return !asecPath.startsWith(mAsecInternalPath);
13581    }
13582
13583    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13584            PackageManagerException {
13585        if (copyRet < 0) {
13586            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13587                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13588                throw new PackageManagerException(copyRet, message);
13589            }
13590        }
13591    }
13592
13593    /**
13594     * Extract the MountService "container ID" from the full code path of an
13595     * .apk.
13596     */
13597    static String cidFromCodePath(String fullCodePath) {
13598        int eidx = fullCodePath.lastIndexOf("/");
13599        String subStr1 = fullCodePath.substring(0, eidx);
13600        int sidx = subStr1.lastIndexOf("/");
13601        return subStr1.substring(sidx+1, eidx);
13602    }
13603
13604    /**
13605     * Logic to handle installation of ASEC applications, including copying and
13606     * renaming logic.
13607     */
13608    class AsecInstallArgs extends InstallArgs {
13609        static final String RES_FILE_NAME = "pkg.apk";
13610        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13611
13612        String cid;
13613        String packagePath;
13614        String resourcePath;
13615
13616        /** New install */
13617        AsecInstallArgs(InstallParams params) {
13618            super(params.origin, params.move, params.observer, params.installFlags,
13619                    params.installerPackageName, params.volumeUuid,
13620                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13621                    params.grantedRuntimePermissions,
13622                    params.traceMethod, params.traceCookie, params.certificates);
13623        }
13624
13625        /** Existing install */
13626        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13627                        boolean isExternal, boolean isForwardLocked) {
13628            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13629              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13630                    instructionSets, null, null, null, 0, null /*certificates*/);
13631            // Hackily pretend we're still looking at a full code path
13632            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13633                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13634            }
13635
13636            // Extract cid from fullCodePath
13637            int eidx = fullCodePath.lastIndexOf("/");
13638            String subStr1 = fullCodePath.substring(0, eidx);
13639            int sidx = subStr1.lastIndexOf("/");
13640            cid = subStr1.substring(sidx+1, eidx);
13641            setMountPath(subStr1);
13642        }
13643
13644        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13645            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13646              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13647                    instructionSets, null, null, null, 0, null /*certificates*/);
13648            this.cid = cid;
13649            setMountPath(PackageHelper.getSdDir(cid));
13650        }
13651
13652        void createCopyFile() {
13653            cid = mInstallerService.allocateExternalStageCidLegacy();
13654        }
13655
13656        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13657            if (origin.staged && origin.cid != null) {
13658                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13659                cid = origin.cid;
13660                setMountPath(PackageHelper.getSdDir(cid));
13661                return PackageManager.INSTALL_SUCCEEDED;
13662            }
13663
13664            if (temp) {
13665                createCopyFile();
13666            } else {
13667                /*
13668                 * Pre-emptively destroy the container since it's destroyed if
13669                 * copying fails due to it existing anyway.
13670                 */
13671                PackageHelper.destroySdDir(cid);
13672            }
13673
13674            final String newMountPath = imcs.copyPackageToContainer(
13675                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13676                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13677
13678            if (newMountPath != null) {
13679                setMountPath(newMountPath);
13680                return PackageManager.INSTALL_SUCCEEDED;
13681            } else {
13682                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13683            }
13684        }
13685
13686        @Override
13687        String getCodePath() {
13688            return packagePath;
13689        }
13690
13691        @Override
13692        String getResourcePath() {
13693            return resourcePath;
13694        }
13695
13696        int doPreInstall(int status) {
13697            if (status != PackageManager.INSTALL_SUCCEEDED) {
13698                // Destroy container
13699                PackageHelper.destroySdDir(cid);
13700            } else {
13701                boolean mounted = PackageHelper.isContainerMounted(cid);
13702                if (!mounted) {
13703                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13704                            Process.SYSTEM_UID);
13705                    if (newMountPath != null) {
13706                        setMountPath(newMountPath);
13707                    } else {
13708                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13709                    }
13710                }
13711            }
13712            return status;
13713        }
13714
13715        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13716            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13717            String newMountPath = null;
13718            if (PackageHelper.isContainerMounted(cid)) {
13719                // Unmount the container
13720                if (!PackageHelper.unMountSdDir(cid)) {
13721                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13722                    return false;
13723                }
13724            }
13725            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13726                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13727                        " which might be stale. Will try to clean up.");
13728                // Clean up the stale container and proceed to recreate.
13729                if (!PackageHelper.destroySdDir(newCacheId)) {
13730                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13731                    return false;
13732                }
13733                // Successfully cleaned up stale container. Try to rename again.
13734                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13735                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13736                            + " inspite of cleaning it up.");
13737                    return false;
13738                }
13739            }
13740            if (!PackageHelper.isContainerMounted(newCacheId)) {
13741                Slog.w(TAG, "Mounting container " + newCacheId);
13742                newMountPath = PackageHelper.mountSdDir(newCacheId,
13743                        getEncryptKey(), Process.SYSTEM_UID);
13744            } else {
13745                newMountPath = PackageHelper.getSdDir(newCacheId);
13746            }
13747            if (newMountPath == null) {
13748                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13749                return false;
13750            }
13751            Log.i(TAG, "Succesfully renamed " + cid +
13752                    " to " + newCacheId +
13753                    " at new path: " + newMountPath);
13754            cid = newCacheId;
13755
13756            final File beforeCodeFile = new File(packagePath);
13757            setMountPath(newMountPath);
13758            final File afterCodeFile = new File(packagePath);
13759
13760            // Reflect the rename in scanned details
13761            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13762            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13763                    afterCodeFile, pkg.baseCodePath));
13764            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13765                    afterCodeFile, pkg.splitCodePaths));
13766
13767            // Reflect the rename in app info
13768            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13769            pkg.setApplicationInfoCodePath(pkg.codePath);
13770            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13771            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13772            pkg.setApplicationInfoResourcePath(pkg.codePath);
13773            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13774            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13775
13776            return true;
13777        }
13778
13779        private void setMountPath(String mountPath) {
13780            final File mountFile = new File(mountPath);
13781
13782            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13783            if (monolithicFile.exists()) {
13784                packagePath = monolithicFile.getAbsolutePath();
13785                if (isFwdLocked()) {
13786                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13787                } else {
13788                    resourcePath = packagePath;
13789                }
13790            } else {
13791                packagePath = mountFile.getAbsolutePath();
13792                resourcePath = packagePath;
13793            }
13794        }
13795
13796        int doPostInstall(int status, int uid) {
13797            if (status != PackageManager.INSTALL_SUCCEEDED) {
13798                cleanUp();
13799            } else {
13800                final int groupOwner;
13801                final String protectedFile;
13802                if (isFwdLocked()) {
13803                    groupOwner = UserHandle.getSharedAppGid(uid);
13804                    protectedFile = RES_FILE_NAME;
13805                } else {
13806                    groupOwner = -1;
13807                    protectedFile = null;
13808                }
13809
13810                if (uid < Process.FIRST_APPLICATION_UID
13811                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13812                    Slog.e(TAG, "Failed to finalize " + cid);
13813                    PackageHelper.destroySdDir(cid);
13814                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13815                }
13816
13817                boolean mounted = PackageHelper.isContainerMounted(cid);
13818                if (!mounted) {
13819                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13820                }
13821            }
13822            return status;
13823        }
13824
13825        private void cleanUp() {
13826            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13827
13828            // Destroy secure container
13829            PackageHelper.destroySdDir(cid);
13830        }
13831
13832        private List<String> getAllCodePaths() {
13833            final File codeFile = new File(getCodePath());
13834            if (codeFile != null && codeFile.exists()) {
13835                try {
13836                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13837                    return pkg.getAllCodePaths();
13838                } catch (PackageParserException e) {
13839                    // Ignored; we tried our best
13840                }
13841            }
13842            return Collections.EMPTY_LIST;
13843        }
13844
13845        void cleanUpResourcesLI() {
13846            // Enumerate all code paths before deleting
13847            cleanUpResourcesLI(getAllCodePaths());
13848        }
13849
13850        private void cleanUpResourcesLI(List<String> allCodePaths) {
13851            cleanUp();
13852            removeDexFiles(allCodePaths, instructionSets);
13853        }
13854
13855        String getPackageName() {
13856            return getAsecPackageName(cid);
13857        }
13858
13859        boolean doPostDeleteLI(boolean delete) {
13860            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13861            final List<String> allCodePaths = getAllCodePaths();
13862            boolean mounted = PackageHelper.isContainerMounted(cid);
13863            if (mounted) {
13864                // Unmount first
13865                if (PackageHelper.unMountSdDir(cid)) {
13866                    mounted = false;
13867                }
13868            }
13869            if (!mounted && delete) {
13870                cleanUpResourcesLI(allCodePaths);
13871            }
13872            return !mounted;
13873        }
13874
13875        @Override
13876        int doPreCopy() {
13877            if (isFwdLocked()) {
13878                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13879                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13880                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13881                }
13882            }
13883
13884            return PackageManager.INSTALL_SUCCEEDED;
13885        }
13886
13887        @Override
13888        int doPostCopy(int uid) {
13889            if (isFwdLocked()) {
13890                if (uid < Process.FIRST_APPLICATION_UID
13891                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13892                                RES_FILE_NAME)) {
13893                    Slog.e(TAG, "Failed to finalize " + cid);
13894                    PackageHelper.destroySdDir(cid);
13895                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13896                }
13897            }
13898
13899            return PackageManager.INSTALL_SUCCEEDED;
13900        }
13901    }
13902
13903    /**
13904     * Logic to handle movement of existing installed applications.
13905     */
13906    class MoveInstallArgs extends InstallArgs {
13907        private File codeFile;
13908        private File resourceFile;
13909
13910        /** New install */
13911        MoveInstallArgs(InstallParams params) {
13912            super(params.origin, params.move, params.observer, params.installFlags,
13913                    params.installerPackageName, params.volumeUuid,
13914                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13915                    params.grantedRuntimePermissions,
13916                    params.traceMethod, params.traceCookie, params.certificates);
13917        }
13918
13919        int copyApk(IMediaContainerService imcs, boolean temp) {
13920            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13921                    + move.fromUuid + " to " + move.toUuid);
13922            synchronized (mInstaller) {
13923                try {
13924                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13925                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13926                } catch (InstallerException e) {
13927                    Slog.w(TAG, "Failed to move app", e);
13928                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13929                }
13930            }
13931
13932            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13933            resourceFile = codeFile;
13934            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13935
13936            return PackageManager.INSTALL_SUCCEEDED;
13937        }
13938
13939        int doPreInstall(int status) {
13940            if (status != PackageManager.INSTALL_SUCCEEDED) {
13941                cleanUp(move.toUuid);
13942            }
13943            return status;
13944        }
13945
13946        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13947            if (status != PackageManager.INSTALL_SUCCEEDED) {
13948                cleanUp(move.toUuid);
13949                return false;
13950            }
13951
13952            // Reflect the move in app info
13953            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13954            pkg.setApplicationInfoCodePath(pkg.codePath);
13955            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13956            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13957            pkg.setApplicationInfoResourcePath(pkg.codePath);
13958            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13959            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13960
13961            return true;
13962        }
13963
13964        int doPostInstall(int status, int uid) {
13965            if (status == PackageManager.INSTALL_SUCCEEDED) {
13966                cleanUp(move.fromUuid);
13967            } else {
13968                cleanUp(move.toUuid);
13969            }
13970            return status;
13971        }
13972
13973        @Override
13974        String getCodePath() {
13975            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13976        }
13977
13978        @Override
13979        String getResourcePath() {
13980            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13981        }
13982
13983        private boolean cleanUp(String volumeUuid) {
13984            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13985                    move.dataAppName);
13986            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13987            final int[] userIds = sUserManager.getUserIds();
13988            synchronized (mInstallLock) {
13989                // Clean up both app data and code
13990                // All package moves are frozen until finished
13991                for (int userId : userIds) {
13992                    try {
13993                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13994                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13995                    } catch (InstallerException e) {
13996                        Slog.w(TAG, String.valueOf(e));
13997                    }
13998                }
13999                removeCodePathLI(codeFile);
14000            }
14001            return true;
14002        }
14003
14004        void cleanUpResourcesLI() {
14005            throw new UnsupportedOperationException();
14006        }
14007
14008        boolean doPostDeleteLI(boolean delete) {
14009            throw new UnsupportedOperationException();
14010        }
14011    }
14012
14013    static String getAsecPackageName(String packageCid) {
14014        int idx = packageCid.lastIndexOf("-");
14015        if (idx == -1) {
14016            return packageCid;
14017        }
14018        return packageCid.substring(0, idx);
14019    }
14020
14021    // Utility method used to create code paths based on package name and available index.
14022    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14023        String idxStr = "";
14024        int idx = 1;
14025        // Fall back to default value of idx=1 if prefix is not
14026        // part of oldCodePath
14027        if (oldCodePath != null) {
14028            String subStr = oldCodePath;
14029            // Drop the suffix right away
14030            if (suffix != null && subStr.endsWith(suffix)) {
14031                subStr = subStr.substring(0, subStr.length() - suffix.length());
14032            }
14033            // If oldCodePath already contains prefix find out the
14034            // ending index to either increment or decrement.
14035            int sidx = subStr.lastIndexOf(prefix);
14036            if (sidx != -1) {
14037                subStr = subStr.substring(sidx + prefix.length());
14038                if (subStr != null) {
14039                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14040                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14041                    }
14042                    try {
14043                        idx = Integer.parseInt(subStr);
14044                        if (idx <= 1) {
14045                            idx++;
14046                        } else {
14047                            idx--;
14048                        }
14049                    } catch(NumberFormatException e) {
14050                    }
14051                }
14052            }
14053        }
14054        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14055        return prefix + idxStr;
14056    }
14057
14058    private File getNextCodePath(File targetDir, String packageName) {
14059        int suffix = 1;
14060        File result;
14061        do {
14062            result = new File(targetDir, packageName + "-" + suffix);
14063            suffix++;
14064        } while (result.exists());
14065        return result;
14066    }
14067
14068    // Utility method that returns the relative package path with respect
14069    // to the installation directory. Like say for /data/data/com.test-1.apk
14070    // string com.test-1 is returned.
14071    static String deriveCodePathName(String codePath) {
14072        if (codePath == null) {
14073            return null;
14074        }
14075        final File codeFile = new File(codePath);
14076        final String name = codeFile.getName();
14077        if (codeFile.isDirectory()) {
14078            return name;
14079        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14080            final int lastDot = name.lastIndexOf('.');
14081            return name.substring(0, lastDot);
14082        } else {
14083            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14084            return null;
14085        }
14086    }
14087
14088    static class PackageInstalledInfo {
14089        String name;
14090        int uid;
14091        // The set of users that originally had this package installed.
14092        int[] origUsers;
14093        // The set of users that now have this package installed.
14094        int[] newUsers;
14095        PackageParser.Package pkg;
14096        int returnCode;
14097        String returnMsg;
14098        PackageRemovedInfo removedInfo;
14099        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14100
14101        public void setError(int code, String msg) {
14102            setReturnCode(code);
14103            setReturnMessage(msg);
14104            Slog.w(TAG, msg);
14105        }
14106
14107        public void setError(String msg, PackageParserException e) {
14108            setReturnCode(e.error);
14109            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14110            Slog.w(TAG, msg, e);
14111        }
14112
14113        public void setError(String msg, PackageManagerException e) {
14114            returnCode = e.error;
14115            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14116            Slog.w(TAG, msg, e);
14117        }
14118
14119        public void setReturnCode(int returnCode) {
14120            this.returnCode = returnCode;
14121            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14122            for (int i = 0; i < childCount; i++) {
14123                addedChildPackages.valueAt(i).returnCode = returnCode;
14124            }
14125        }
14126
14127        private void setReturnMessage(String returnMsg) {
14128            this.returnMsg = returnMsg;
14129            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14130            for (int i = 0; i < childCount; i++) {
14131                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14132            }
14133        }
14134
14135        // In some error cases we want to convey more info back to the observer
14136        String origPackage;
14137        String origPermission;
14138    }
14139
14140    /*
14141     * Install a non-existing package.
14142     */
14143    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14144            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14145            PackageInstalledInfo res) {
14146        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14147
14148        // Remember this for later, in case we need to rollback this install
14149        String pkgName = pkg.packageName;
14150
14151        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14152
14153        synchronized(mPackages) {
14154            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
14155            if (renamedPackage != null) {
14156                // A package with the same name is already installed, though
14157                // it has been renamed to an older name.  The package we
14158                // are trying to install should be installed as an update to
14159                // the existing one, but that has not been requested, so bail.
14160                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14161                        + " without first uninstalling package running as "
14162                        + renamedPackage);
14163                return;
14164            }
14165            if (mPackages.containsKey(pkgName)) {
14166                // Don't allow installation over an existing package with the same name.
14167                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14168                        + " without first uninstalling.");
14169                return;
14170            }
14171        }
14172
14173        try {
14174            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14175                    System.currentTimeMillis(), user);
14176
14177            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14178
14179            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14180                prepareAppDataAfterInstallLIF(newPackage);
14181
14182            } else {
14183                // Remove package from internal structures, but keep around any
14184                // data that might have already existed
14185                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14186                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14187            }
14188        } catch (PackageManagerException e) {
14189            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14190        }
14191
14192        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14193    }
14194
14195    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14196        // Can't rotate keys during boot or if sharedUser.
14197        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14198                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14199            return false;
14200        }
14201        // app is using upgradeKeySets; make sure all are valid
14202        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14203        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14204        for (int i = 0; i < upgradeKeySets.length; i++) {
14205            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14206                Slog.wtf(TAG, "Package "
14207                         + (oldPs.name != null ? oldPs.name : "<null>")
14208                         + " contains upgrade-key-set reference to unknown key-set: "
14209                         + upgradeKeySets[i]
14210                         + " reverting to signatures check.");
14211                return false;
14212            }
14213        }
14214        return true;
14215    }
14216
14217    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14218        // Upgrade keysets are being used.  Determine if new package has a superset of the
14219        // required keys.
14220        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14221        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14222        for (int i = 0; i < upgradeKeySets.length; i++) {
14223            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14224            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14225                return true;
14226            }
14227        }
14228        return false;
14229    }
14230
14231    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14232        try (DigestInputStream digestStream =
14233                new DigestInputStream(new FileInputStream(file), digest)) {
14234            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14235        }
14236    }
14237
14238    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14239            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14240        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14241
14242        final PackageParser.Package oldPackage;
14243        final String pkgName = pkg.packageName;
14244        final int[] allUsers;
14245        final int[] installedUsers;
14246
14247        synchronized(mPackages) {
14248            oldPackage = mPackages.get(pkgName);
14249            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14250
14251            // don't allow upgrade to target a release SDK from a pre-release SDK
14252            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14253                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14254            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14255                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14256            if (oldTargetsPreRelease
14257                    && !newTargetsPreRelease
14258                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14259                Slog.w(TAG, "Can't install package targeting released sdk");
14260                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14261                return;
14262            }
14263
14264            // don't allow an upgrade from full to ephemeral
14265            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14266            if (isEphemeral && !oldIsEphemeral) {
14267                // can't downgrade from full to ephemeral
14268                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14269                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14270                return;
14271            }
14272
14273            // verify signatures are valid
14274            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14275            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14276                if (!checkUpgradeKeySetLP(ps, pkg)) {
14277                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14278                            "New package not signed by keys specified by upgrade-keysets: "
14279                                    + pkgName);
14280                    return;
14281                }
14282            } else {
14283                // default to original signature matching
14284                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14285                        != PackageManager.SIGNATURE_MATCH) {
14286                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14287                            "New package has a different signature: " + pkgName);
14288                    return;
14289                }
14290            }
14291
14292            // don't allow a system upgrade unless the upgrade hash matches
14293            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14294                byte[] digestBytes = null;
14295                try {
14296                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14297                    updateDigest(digest, new File(pkg.baseCodePath));
14298                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14299                        for (String path : pkg.splitCodePaths) {
14300                            updateDigest(digest, new File(path));
14301                        }
14302                    }
14303                    digestBytes = digest.digest();
14304                } catch (NoSuchAlgorithmException | IOException e) {
14305                    res.setError(INSTALL_FAILED_INVALID_APK,
14306                            "Could not compute hash: " + pkgName);
14307                    return;
14308                }
14309                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14310                    res.setError(INSTALL_FAILED_INVALID_APK,
14311                            "New package fails restrict-update check: " + pkgName);
14312                    return;
14313                }
14314                // retain upgrade restriction
14315                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14316            }
14317
14318            // Check for shared user id changes
14319            String invalidPackageName =
14320                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14321            if (invalidPackageName != null) {
14322                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14323                        "Package " + invalidPackageName + " tried to change user "
14324                                + oldPackage.mSharedUserId);
14325                return;
14326            }
14327
14328            // In case of rollback, remember per-user/profile install state
14329            allUsers = sUserManager.getUserIds();
14330            installedUsers = ps.queryInstalledUsers(allUsers, true);
14331        }
14332
14333        // Update what is removed
14334        res.removedInfo = new PackageRemovedInfo();
14335        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14336        res.removedInfo.removedPackage = oldPackage.packageName;
14337        res.removedInfo.isUpdate = true;
14338        res.removedInfo.origUsers = installedUsers;
14339        final int childCount = (oldPackage.childPackages != null)
14340                ? oldPackage.childPackages.size() : 0;
14341        for (int i = 0; i < childCount; i++) {
14342            boolean childPackageUpdated = false;
14343            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14344            if (res.addedChildPackages != null) {
14345                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14346                if (childRes != null) {
14347                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14348                    childRes.removedInfo.removedPackage = childPkg.packageName;
14349                    childRes.removedInfo.isUpdate = true;
14350                    childPackageUpdated = true;
14351                }
14352            }
14353            if (!childPackageUpdated) {
14354                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14355                childRemovedRes.removedPackage = childPkg.packageName;
14356                childRemovedRes.isUpdate = false;
14357                childRemovedRes.dataRemoved = true;
14358                synchronized (mPackages) {
14359                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14360                    if (childPs != null) {
14361                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14362                    }
14363                }
14364                if (res.removedInfo.removedChildPackages == null) {
14365                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14366                }
14367                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14368            }
14369        }
14370
14371        boolean sysPkg = (isSystemApp(oldPackage));
14372        if (sysPkg) {
14373            // Set the system/privileged flags as needed
14374            final boolean privileged =
14375                    (oldPackage.applicationInfo.privateFlags
14376                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14377            final int systemPolicyFlags = policyFlags
14378                    | PackageParser.PARSE_IS_SYSTEM
14379                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14380
14381            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14382                    user, allUsers, installerPackageName, res);
14383        } else {
14384            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14385                    user, allUsers, installerPackageName, res);
14386        }
14387    }
14388
14389    public List<String> getPreviousCodePaths(String packageName) {
14390        final PackageSetting ps = mSettings.mPackages.get(packageName);
14391        final List<String> result = new ArrayList<String>();
14392        if (ps != null && ps.oldCodePaths != null) {
14393            result.addAll(ps.oldCodePaths);
14394        }
14395        return result;
14396    }
14397
14398    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14399            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14400            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14401        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14402                + deletedPackage);
14403
14404        String pkgName = deletedPackage.packageName;
14405        boolean deletedPkg = true;
14406        boolean addedPkg = false;
14407        boolean updatedSettings = false;
14408        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14409        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14410                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14411
14412        final long origUpdateTime = (pkg.mExtras != null)
14413                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14414
14415        // First delete the existing package while retaining the data directory
14416        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14417                res.removedInfo, true, pkg)) {
14418            // If the existing package wasn't successfully deleted
14419            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14420            deletedPkg = false;
14421        } else {
14422            // Successfully deleted the old package; proceed with replace.
14423
14424            // If deleted package lived in a container, give users a chance to
14425            // relinquish resources before killing.
14426            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14427                if (DEBUG_INSTALL) {
14428                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14429                }
14430                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14431                final ArrayList<String> pkgList = new ArrayList<String>(1);
14432                pkgList.add(deletedPackage.applicationInfo.packageName);
14433                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14434            }
14435
14436            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14437                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14438            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14439
14440            try {
14441                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14442                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14443                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14444
14445                // Update the in-memory copy of the previous code paths.
14446                PackageSetting ps = mSettings.mPackages.get(pkgName);
14447                if (!killApp) {
14448                    if (ps.oldCodePaths == null) {
14449                        ps.oldCodePaths = new ArraySet<>();
14450                    }
14451                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14452                    if (deletedPackage.splitCodePaths != null) {
14453                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14454                    }
14455                } else {
14456                    ps.oldCodePaths = null;
14457                }
14458                if (ps.childPackageNames != null) {
14459                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14460                        final String childPkgName = ps.childPackageNames.get(i);
14461                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14462                        childPs.oldCodePaths = ps.oldCodePaths;
14463                    }
14464                }
14465                prepareAppDataAfterInstallLIF(newPackage);
14466                addedPkg = true;
14467            } catch (PackageManagerException e) {
14468                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14469            }
14470        }
14471
14472        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14473            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14474
14475            // Revert all internal state mutations and added folders for the failed install
14476            if (addedPkg) {
14477                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14478                        res.removedInfo, true, null);
14479            }
14480
14481            // Restore the old package
14482            if (deletedPkg) {
14483                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14484                File restoreFile = new File(deletedPackage.codePath);
14485                // Parse old package
14486                boolean oldExternal = isExternal(deletedPackage);
14487                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14488                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14489                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14490                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14491                try {
14492                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14493                            null);
14494                } catch (PackageManagerException e) {
14495                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14496                            + e.getMessage());
14497                    return;
14498                }
14499
14500                synchronized (mPackages) {
14501                    // Ensure the installer package name up to date
14502                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14503
14504                    // Update permissions for restored package
14505                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14506
14507                    mSettings.writeLPr();
14508                }
14509
14510                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14511            }
14512        } else {
14513            synchronized (mPackages) {
14514                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14515                if (ps != null) {
14516                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14517                    if (res.removedInfo.removedChildPackages != null) {
14518                        final int childCount = res.removedInfo.removedChildPackages.size();
14519                        // Iterate in reverse as we may modify the collection
14520                        for (int i = childCount - 1; i >= 0; i--) {
14521                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14522                            if (res.addedChildPackages.containsKey(childPackageName)) {
14523                                res.removedInfo.removedChildPackages.removeAt(i);
14524                            } else {
14525                                PackageRemovedInfo childInfo = res.removedInfo
14526                                        .removedChildPackages.valueAt(i);
14527                                childInfo.removedForAllUsers = mPackages.get(
14528                                        childInfo.removedPackage) == null;
14529                            }
14530                        }
14531                    }
14532                }
14533            }
14534        }
14535    }
14536
14537    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14538            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14539            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14540        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14541                + ", old=" + deletedPackage);
14542
14543        final boolean disabledSystem;
14544
14545        // Remove existing system package
14546        removePackageLI(deletedPackage, true);
14547
14548        synchronized (mPackages) {
14549            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14550        }
14551        if (!disabledSystem) {
14552            // We didn't need to disable the .apk as a current system package,
14553            // which means we are replacing another update that is already
14554            // installed.  We need to make sure to delete the older one's .apk.
14555            res.removedInfo.args = createInstallArgsForExisting(0,
14556                    deletedPackage.applicationInfo.getCodePath(),
14557                    deletedPackage.applicationInfo.getResourcePath(),
14558                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14559        } else {
14560            res.removedInfo.args = null;
14561        }
14562
14563        // Successfully disabled the old package. Now proceed with re-installation
14564        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14565                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14566        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14567
14568        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14569        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14570                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14571
14572        PackageParser.Package newPackage = null;
14573        try {
14574            // Add the package to the internal data structures
14575            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14576
14577            // Set the update and install times
14578            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14579            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14580                    System.currentTimeMillis());
14581
14582            // Update the package dynamic state if succeeded
14583            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14584                // Now that the install succeeded make sure we remove data
14585                // directories for any child package the update removed.
14586                final int deletedChildCount = (deletedPackage.childPackages != null)
14587                        ? deletedPackage.childPackages.size() : 0;
14588                final int newChildCount = (newPackage.childPackages != null)
14589                        ? newPackage.childPackages.size() : 0;
14590                for (int i = 0; i < deletedChildCount; i++) {
14591                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14592                    boolean childPackageDeleted = true;
14593                    for (int j = 0; j < newChildCount; j++) {
14594                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14595                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14596                            childPackageDeleted = false;
14597                            break;
14598                        }
14599                    }
14600                    if (childPackageDeleted) {
14601                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14602                                deletedChildPkg.packageName);
14603                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14604                            PackageRemovedInfo removedChildRes = res.removedInfo
14605                                    .removedChildPackages.get(deletedChildPkg.packageName);
14606                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14607                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14608                        }
14609                    }
14610                }
14611
14612                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14613                prepareAppDataAfterInstallLIF(newPackage);
14614            }
14615        } catch (PackageManagerException e) {
14616            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14617            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14618        }
14619
14620        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14621            // Re installation failed. Restore old information
14622            // Remove new pkg information
14623            if (newPackage != null) {
14624                removeInstalledPackageLI(newPackage, true);
14625            }
14626            // Add back the old system package
14627            try {
14628                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14629            } catch (PackageManagerException e) {
14630                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14631            }
14632
14633            synchronized (mPackages) {
14634                if (disabledSystem) {
14635                    enableSystemPackageLPw(deletedPackage);
14636                }
14637
14638                // Ensure the installer package name up to date
14639                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14640
14641                // Update permissions for restored package
14642                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14643
14644                mSettings.writeLPr();
14645            }
14646
14647            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14648                    + " after failed upgrade");
14649        }
14650    }
14651
14652    /**
14653     * Checks whether the parent or any of the child packages have a change shared
14654     * user. For a package to be a valid update the shred users of the parent and
14655     * the children should match. We may later support changing child shared users.
14656     * @param oldPkg The updated package.
14657     * @param newPkg The update package.
14658     * @return The shared user that change between the versions.
14659     */
14660    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14661            PackageParser.Package newPkg) {
14662        // Check parent shared user
14663        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14664            return newPkg.packageName;
14665        }
14666        // Check child shared users
14667        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14668        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14669        for (int i = 0; i < newChildCount; i++) {
14670            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14671            // If this child was present, did it have the same shared user?
14672            for (int j = 0; j < oldChildCount; j++) {
14673                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14674                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14675                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14676                    return newChildPkg.packageName;
14677                }
14678            }
14679        }
14680        return null;
14681    }
14682
14683    private void removeNativeBinariesLI(PackageSetting ps) {
14684        // Remove the lib path for the parent package
14685        if (ps != null) {
14686            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14687            // Remove the lib path for the child packages
14688            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14689            for (int i = 0; i < childCount; i++) {
14690                PackageSetting childPs = null;
14691                synchronized (mPackages) {
14692                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14693                }
14694                if (childPs != null) {
14695                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14696                            .legacyNativeLibraryPathString);
14697                }
14698            }
14699        }
14700    }
14701
14702    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14703        // Enable the parent package
14704        mSettings.enableSystemPackageLPw(pkg.packageName);
14705        // Enable the child packages
14706        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14707        for (int i = 0; i < childCount; i++) {
14708            PackageParser.Package childPkg = pkg.childPackages.get(i);
14709            mSettings.enableSystemPackageLPw(childPkg.packageName);
14710        }
14711    }
14712
14713    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14714            PackageParser.Package newPkg) {
14715        // Disable the parent package (parent always replaced)
14716        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14717        // Disable the child packages
14718        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14719        for (int i = 0; i < childCount; i++) {
14720            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14721            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14722            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14723        }
14724        return disabled;
14725    }
14726
14727    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14728            String installerPackageName) {
14729        // Enable the parent package
14730        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14731        // Enable the child packages
14732        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14733        for (int i = 0; i < childCount; i++) {
14734            PackageParser.Package childPkg = pkg.childPackages.get(i);
14735            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14736        }
14737    }
14738
14739    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14740        // Collect all used permissions in the UID
14741        ArraySet<String> usedPermissions = new ArraySet<>();
14742        final int packageCount = su.packages.size();
14743        for (int i = 0; i < packageCount; i++) {
14744            PackageSetting ps = su.packages.valueAt(i);
14745            if (ps.pkg == null) {
14746                continue;
14747            }
14748            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14749            for (int j = 0; j < requestedPermCount; j++) {
14750                String permission = ps.pkg.requestedPermissions.get(j);
14751                BasePermission bp = mSettings.mPermissions.get(permission);
14752                if (bp != null) {
14753                    usedPermissions.add(permission);
14754                }
14755            }
14756        }
14757
14758        PermissionsState permissionsState = su.getPermissionsState();
14759        // Prune install permissions
14760        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14761        final int installPermCount = installPermStates.size();
14762        for (int i = installPermCount - 1; i >= 0;  i--) {
14763            PermissionState permissionState = installPermStates.get(i);
14764            if (!usedPermissions.contains(permissionState.getName())) {
14765                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14766                if (bp != null) {
14767                    permissionsState.revokeInstallPermission(bp);
14768                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14769                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14770                }
14771            }
14772        }
14773
14774        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14775
14776        // Prune runtime permissions
14777        for (int userId : allUserIds) {
14778            List<PermissionState> runtimePermStates = permissionsState
14779                    .getRuntimePermissionStates(userId);
14780            final int runtimePermCount = runtimePermStates.size();
14781            for (int i = runtimePermCount - 1; i >= 0; i--) {
14782                PermissionState permissionState = runtimePermStates.get(i);
14783                if (!usedPermissions.contains(permissionState.getName())) {
14784                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14785                    if (bp != null) {
14786                        permissionsState.revokeRuntimePermission(bp, userId);
14787                        permissionsState.updatePermissionFlags(bp, userId,
14788                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14789                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14790                                runtimePermissionChangedUserIds, userId);
14791                    }
14792                }
14793            }
14794        }
14795
14796        return runtimePermissionChangedUserIds;
14797    }
14798
14799    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14800            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14801        // Update the parent package setting
14802        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14803                res, user);
14804        // Update the child packages setting
14805        final int childCount = (newPackage.childPackages != null)
14806                ? newPackage.childPackages.size() : 0;
14807        for (int i = 0; i < childCount; i++) {
14808            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14809            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14810            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14811                    childRes.origUsers, childRes, user);
14812        }
14813    }
14814
14815    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14816            String installerPackageName, int[] allUsers, int[] installedForUsers,
14817            PackageInstalledInfo res, UserHandle user) {
14818        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14819
14820        String pkgName = newPackage.packageName;
14821        synchronized (mPackages) {
14822            //write settings. the installStatus will be incomplete at this stage.
14823            //note that the new package setting would have already been
14824            //added to mPackages. It hasn't been persisted yet.
14825            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14826            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14827            mSettings.writeLPr();
14828            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14829        }
14830
14831        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14832        synchronized (mPackages) {
14833            updatePermissionsLPw(newPackage.packageName, newPackage,
14834                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14835                            ? UPDATE_PERMISSIONS_ALL : 0));
14836            // For system-bundled packages, we assume that installing an upgraded version
14837            // of the package implies that the user actually wants to run that new code,
14838            // so we enable the package.
14839            PackageSetting ps = mSettings.mPackages.get(pkgName);
14840            final int userId = user.getIdentifier();
14841            if (ps != null) {
14842                if (isSystemApp(newPackage)) {
14843                    if (DEBUG_INSTALL) {
14844                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14845                    }
14846                    // Enable system package for requested users
14847                    if (res.origUsers != null) {
14848                        for (int origUserId : res.origUsers) {
14849                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14850                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14851                                        origUserId, installerPackageName);
14852                            }
14853                        }
14854                    }
14855                    // Also convey the prior install/uninstall state
14856                    if (allUsers != null && installedForUsers != null) {
14857                        for (int currentUserId : allUsers) {
14858                            final boolean installed = ArrayUtils.contains(
14859                                    installedForUsers, currentUserId);
14860                            if (DEBUG_INSTALL) {
14861                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14862                            }
14863                            ps.setInstalled(installed, currentUserId);
14864                        }
14865                        // these install state changes will be persisted in the
14866                        // upcoming call to mSettings.writeLPr().
14867                    }
14868                }
14869                // It's implied that when a user requests installation, they want the app to be
14870                // installed and enabled.
14871                if (userId != UserHandle.USER_ALL) {
14872                    ps.setInstalled(true, userId);
14873                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14874                }
14875            }
14876            res.name = pkgName;
14877            res.uid = newPackage.applicationInfo.uid;
14878            res.pkg = newPackage;
14879            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14880            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14881            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14882            //to update install status
14883            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14884            mSettings.writeLPr();
14885            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14886        }
14887
14888        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14889    }
14890
14891    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14892        try {
14893            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14894            installPackageLI(args, res);
14895        } finally {
14896            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14897        }
14898    }
14899
14900    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14901        final int installFlags = args.installFlags;
14902        final String installerPackageName = args.installerPackageName;
14903        final String volumeUuid = args.volumeUuid;
14904        final File tmpPackageFile = new File(args.getCodePath());
14905        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14906        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14907                || (args.volumeUuid != null));
14908        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14909        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14910        boolean replace = false;
14911        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14912        if (args.move != null) {
14913            // moving a complete application; perform an initial scan on the new install location
14914            scanFlags |= SCAN_INITIAL;
14915        }
14916        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14917            scanFlags |= SCAN_DONT_KILL_APP;
14918        }
14919
14920        // Result object to be returned
14921        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14922
14923        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14924
14925        // Sanity check
14926        if (ephemeral && (forwardLocked || onExternal)) {
14927            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14928                    + " external=" + onExternal);
14929            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14930            return;
14931        }
14932
14933        // Retrieve PackageSettings and parse package
14934        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14935                | PackageParser.PARSE_ENFORCE_CODE
14936                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14937                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14938                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14939                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14940        PackageParser pp = new PackageParser();
14941        pp.setSeparateProcesses(mSeparateProcesses);
14942        pp.setDisplayMetrics(mMetrics);
14943
14944        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14945        final PackageParser.Package pkg;
14946        try {
14947            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14948        } catch (PackageParserException e) {
14949            res.setError("Failed parse during installPackageLI", e);
14950            return;
14951        } finally {
14952            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14953        }
14954
14955        // If we are installing a clustered package add results for the children
14956        if (pkg.childPackages != null) {
14957            synchronized (mPackages) {
14958                final int childCount = pkg.childPackages.size();
14959                for (int i = 0; i < childCount; i++) {
14960                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14961                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14962                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14963                    childRes.pkg = childPkg;
14964                    childRes.name = childPkg.packageName;
14965                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14966                    if (childPs != null) {
14967                        childRes.origUsers = childPs.queryInstalledUsers(
14968                                sUserManager.getUserIds(), true);
14969                    }
14970                    if ((mPackages.containsKey(childPkg.packageName))) {
14971                        childRes.removedInfo = new PackageRemovedInfo();
14972                        childRes.removedInfo.removedPackage = childPkg.packageName;
14973                    }
14974                    if (res.addedChildPackages == null) {
14975                        res.addedChildPackages = new ArrayMap<>();
14976                    }
14977                    res.addedChildPackages.put(childPkg.packageName, childRes);
14978                }
14979            }
14980        }
14981
14982        // If package doesn't declare API override, mark that we have an install
14983        // time CPU ABI override.
14984        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14985            pkg.cpuAbiOverride = args.abiOverride;
14986        }
14987
14988        String pkgName = res.name = pkg.packageName;
14989        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14990            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14991                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14992                return;
14993            }
14994        }
14995
14996        try {
14997            // either use what we've been given or parse directly from the APK
14998            if (args.certificates != null) {
14999                try {
15000                    PackageParser.populateCertificates(pkg, args.certificates);
15001                } catch (PackageParserException e) {
15002                    // there was something wrong with the certificates we were given;
15003                    // try to pull them from the APK
15004                    PackageParser.collectCertificates(pkg, parseFlags);
15005                }
15006            } else {
15007                PackageParser.collectCertificates(pkg, parseFlags);
15008            }
15009        } catch (PackageParserException e) {
15010            res.setError("Failed collect during installPackageLI", e);
15011            return;
15012        }
15013
15014        // Get rid of all references to package scan path via parser.
15015        pp = null;
15016        String oldCodePath = null;
15017        boolean systemApp = false;
15018        synchronized (mPackages) {
15019            // Check if installing already existing package
15020            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15021                String oldName = mSettings.getRenamedPackageLPr(pkgName);
15022                if (pkg.mOriginalPackages != null
15023                        && pkg.mOriginalPackages.contains(oldName)
15024                        && mPackages.containsKey(oldName)) {
15025                    // This package is derived from an original package,
15026                    // and this device has been updating from that original
15027                    // name.  We must continue using the original name, so
15028                    // rename the new package here.
15029                    pkg.setPackageName(oldName);
15030                    pkgName = pkg.packageName;
15031                    replace = true;
15032                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15033                            + oldName + " pkgName=" + pkgName);
15034                } else if (mPackages.containsKey(pkgName)) {
15035                    // This package, under its official name, already exists
15036                    // on the device; we should replace it.
15037                    replace = true;
15038                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15039                }
15040
15041                // Child packages are installed through the parent package
15042                if (pkg.parentPackage != null) {
15043                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15044                            "Package " + pkg.packageName + " is child of package "
15045                                    + pkg.parentPackage.parentPackage + ". Child packages "
15046                                    + "can be updated only through the parent package.");
15047                    return;
15048                }
15049
15050                if (replace) {
15051                    // Prevent apps opting out from runtime permissions
15052                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15053                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15054                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15055                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15056                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15057                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15058                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15059                                        + " doesn't support runtime permissions but the old"
15060                                        + " target SDK " + oldTargetSdk + " does.");
15061                        return;
15062                    }
15063
15064                    // Prevent installing of child packages
15065                    if (oldPackage.parentPackage != null) {
15066                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15067                                "Package " + pkg.packageName + " is child of package "
15068                                        + oldPackage.parentPackage + ". Child packages "
15069                                        + "can be updated only through the parent package.");
15070                        return;
15071                    }
15072                }
15073            }
15074
15075            PackageSetting ps = mSettings.mPackages.get(pkgName);
15076            if (ps != null) {
15077                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15078
15079                // Quick sanity check that we're signed correctly if updating;
15080                // we'll check this again later when scanning, but we want to
15081                // bail early here before tripping over redefined permissions.
15082                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15083                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15084                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15085                                + pkg.packageName + " upgrade keys do not match the "
15086                                + "previously installed version");
15087                        return;
15088                    }
15089                } else {
15090                    try {
15091                        verifySignaturesLP(ps, pkg);
15092                    } catch (PackageManagerException e) {
15093                        res.setError(e.error, e.getMessage());
15094                        return;
15095                    }
15096                }
15097
15098                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15099                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15100                    systemApp = (ps.pkg.applicationInfo.flags &
15101                            ApplicationInfo.FLAG_SYSTEM) != 0;
15102                }
15103                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15104            }
15105
15106            // Check whether the newly-scanned package wants to define an already-defined perm
15107            int N = pkg.permissions.size();
15108            for (int i = N-1; i >= 0; i--) {
15109                PackageParser.Permission perm = pkg.permissions.get(i);
15110                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15111                if (bp != null) {
15112                    // If the defining package is signed with our cert, it's okay.  This
15113                    // also includes the "updating the same package" case, of course.
15114                    // "updating same package" could also involve key-rotation.
15115                    final boolean sigsOk;
15116                    if (bp.sourcePackage.equals(pkg.packageName)
15117                            && (bp.packageSetting instanceof PackageSetting)
15118                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15119                                    scanFlags))) {
15120                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15121                    } else {
15122                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15123                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15124                    }
15125                    if (!sigsOk) {
15126                        // If the owning package is the system itself, we log but allow
15127                        // install to proceed; we fail the install on all other permission
15128                        // redefinitions.
15129                        if (!bp.sourcePackage.equals("android")) {
15130                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15131                                    + pkg.packageName + " attempting to redeclare permission "
15132                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15133                            res.origPermission = perm.info.name;
15134                            res.origPackage = bp.sourcePackage;
15135                            return;
15136                        } else {
15137                            Slog.w(TAG, "Package " + pkg.packageName
15138                                    + " attempting to redeclare system permission "
15139                                    + perm.info.name + "; ignoring new declaration");
15140                            pkg.permissions.remove(i);
15141                        }
15142                    }
15143                }
15144            }
15145        }
15146
15147        if (systemApp) {
15148            if (onExternal) {
15149                // Abort update; system app can't be replaced with app on sdcard
15150                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15151                        "Cannot install updates to system apps on sdcard");
15152                return;
15153            } else if (ephemeral) {
15154                // Abort update; system app can't be replaced with an ephemeral app
15155                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15156                        "Cannot update a system app with an ephemeral app");
15157                return;
15158            }
15159        }
15160
15161        if (args.move != null) {
15162            // We did an in-place move, so dex is ready to roll
15163            scanFlags |= SCAN_NO_DEX;
15164            scanFlags |= SCAN_MOVE;
15165
15166            synchronized (mPackages) {
15167                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15168                if (ps == null) {
15169                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15170                            "Missing settings for moved package " + pkgName);
15171                }
15172
15173                // We moved the entire application as-is, so bring over the
15174                // previously derived ABI information.
15175                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15176                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15177            }
15178
15179        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15180            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15181            scanFlags |= SCAN_NO_DEX;
15182
15183            try {
15184                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15185                    args.abiOverride : pkg.cpuAbiOverride);
15186                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15187                        true /* extract libs */);
15188            } catch (PackageManagerException pme) {
15189                Slog.e(TAG, "Error deriving application ABI", pme);
15190                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15191                return;
15192            }
15193
15194            // Shared libraries for the package need to be updated.
15195            synchronized (mPackages) {
15196                try {
15197                    updateSharedLibrariesLPw(pkg, null);
15198                } catch (PackageManagerException e) {
15199                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15200                }
15201            }
15202            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15203            // Do not run PackageDexOptimizer through the local performDexOpt
15204            // method because `pkg` may not be in `mPackages` yet.
15205            //
15206            // Also, don't fail application installs if the dexopt step fails.
15207            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15208                    null /* instructionSets */, false /* checkProfiles */,
15209                    getCompilerFilterForReason(REASON_INSTALL),
15210                    getOrCreateCompilerPackageStats(pkg));
15211            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15212
15213            // Notify BackgroundDexOptService that the package has been changed.
15214            // If this is an update of a package which used to fail to compile,
15215            // BDOS will remove it from its blacklist.
15216            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15217        }
15218
15219        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15220            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15221            return;
15222        }
15223
15224        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15225
15226        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15227                "installPackageLI")) {
15228            if (replace) {
15229                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15230                        installerPackageName, res);
15231            } else {
15232                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15233                        args.user, installerPackageName, volumeUuid, res);
15234            }
15235        }
15236        synchronized (mPackages) {
15237            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15238            if (ps != null) {
15239                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15240            }
15241
15242            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15243            for (int i = 0; i < childCount; i++) {
15244                PackageParser.Package childPkg = pkg.childPackages.get(i);
15245                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15246                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15247                if (childPs != null) {
15248                    childRes.newUsers = childPs.queryInstalledUsers(
15249                            sUserManager.getUserIds(), true);
15250                }
15251            }
15252        }
15253    }
15254
15255    private void startIntentFilterVerifications(int userId, boolean replacing,
15256            PackageParser.Package pkg) {
15257        if (mIntentFilterVerifierComponent == null) {
15258            Slog.w(TAG, "No IntentFilter verification will not be done as "
15259                    + "there is no IntentFilterVerifier available!");
15260            return;
15261        }
15262
15263        final int verifierUid = getPackageUid(
15264                mIntentFilterVerifierComponent.getPackageName(),
15265                MATCH_DEBUG_TRIAGED_MISSING,
15266                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15267
15268        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15269        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15270        mHandler.sendMessage(msg);
15271
15272        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15273        for (int i = 0; i < childCount; i++) {
15274            PackageParser.Package childPkg = pkg.childPackages.get(i);
15275            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15276            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15277            mHandler.sendMessage(msg);
15278        }
15279    }
15280
15281    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15282            PackageParser.Package pkg) {
15283        int size = pkg.activities.size();
15284        if (size == 0) {
15285            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15286                    "No activity, so no need to verify any IntentFilter!");
15287            return;
15288        }
15289
15290        final boolean hasDomainURLs = hasDomainURLs(pkg);
15291        if (!hasDomainURLs) {
15292            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15293                    "No domain URLs, so no need to verify any IntentFilter!");
15294            return;
15295        }
15296
15297        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15298                + " if any IntentFilter from the " + size
15299                + " Activities needs verification ...");
15300
15301        int count = 0;
15302        final String packageName = pkg.packageName;
15303
15304        synchronized (mPackages) {
15305            // If this is a new install and we see that we've already run verification for this
15306            // package, we have nothing to do: it means the state was restored from backup.
15307            if (!replacing) {
15308                IntentFilterVerificationInfo ivi =
15309                        mSettings.getIntentFilterVerificationLPr(packageName);
15310                if (ivi != null) {
15311                    if (DEBUG_DOMAIN_VERIFICATION) {
15312                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15313                                + ivi.getStatusString());
15314                    }
15315                    return;
15316                }
15317            }
15318
15319            // If any filters need to be verified, then all need to be.
15320            boolean needToVerify = false;
15321            for (PackageParser.Activity a : pkg.activities) {
15322                for (ActivityIntentInfo filter : a.intents) {
15323                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15324                        if (DEBUG_DOMAIN_VERIFICATION) {
15325                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15326                        }
15327                        needToVerify = true;
15328                        break;
15329                    }
15330                }
15331            }
15332
15333            if (needToVerify) {
15334                final int verificationId = mIntentFilterVerificationToken++;
15335                for (PackageParser.Activity a : pkg.activities) {
15336                    for (ActivityIntentInfo filter : a.intents) {
15337                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15338                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15339                                    "Verification needed for IntentFilter:" + filter.toString());
15340                            mIntentFilterVerifier.addOneIntentFilterVerification(
15341                                    verifierUid, userId, verificationId, filter, packageName);
15342                            count++;
15343                        }
15344                    }
15345                }
15346            }
15347        }
15348
15349        if (count > 0) {
15350            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15351                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15352                    +  " for userId:" + userId);
15353            mIntentFilterVerifier.startVerifications(userId);
15354        } else {
15355            if (DEBUG_DOMAIN_VERIFICATION) {
15356                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15357            }
15358        }
15359    }
15360
15361    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15362        final ComponentName cn  = filter.activity.getComponentName();
15363        final String packageName = cn.getPackageName();
15364
15365        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15366                packageName);
15367        if (ivi == null) {
15368            return true;
15369        }
15370        int status = ivi.getStatus();
15371        switch (status) {
15372            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15373            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15374                return true;
15375
15376            default:
15377                // Nothing to do
15378                return false;
15379        }
15380    }
15381
15382    private static boolean isMultiArch(ApplicationInfo info) {
15383        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15384    }
15385
15386    private static boolean isExternal(PackageParser.Package pkg) {
15387        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15388    }
15389
15390    private static boolean isExternal(PackageSetting ps) {
15391        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15392    }
15393
15394    private static boolean isEphemeral(PackageParser.Package pkg) {
15395        return pkg.applicationInfo.isEphemeralApp();
15396    }
15397
15398    private static boolean isEphemeral(PackageSetting ps) {
15399        return ps.pkg != null && isEphemeral(ps.pkg);
15400    }
15401
15402    private static boolean isSystemApp(PackageParser.Package pkg) {
15403        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15404    }
15405
15406    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15407        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15408    }
15409
15410    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15411        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15412    }
15413
15414    private static boolean isSystemApp(PackageSetting ps) {
15415        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15416    }
15417
15418    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15419        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15420    }
15421
15422    private int packageFlagsToInstallFlags(PackageSetting ps) {
15423        int installFlags = 0;
15424        if (isEphemeral(ps)) {
15425            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15426        }
15427        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15428            // This existing package was an external ASEC install when we have
15429            // the external flag without a UUID
15430            installFlags |= PackageManager.INSTALL_EXTERNAL;
15431        }
15432        if (ps.isForwardLocked()) {
15433            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15434        }
15435        return installFlags;
15436    }
15437
15438    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15439        if (isExternal(pkg)) {
15440            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15441                return StorageManager.UUID_PRIMARY_PHYSICAL;
15442            } else {
15443                return pkg.volumeUuid;
15444            }
15445        } else {
15446            return StorageManager.UUID_PRIVATE_INTERNAL;
15447        }
15448    }
15449
15450    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15451        if (isExternal(pkg)) {
15452            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15453                return mSettings.getExternalVersion();
15454            } else {
15455                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15456            }
15457        } else {
15458            return mSettings.getInternalVersion();
15459        }
15460    }
15461
15462    private void deleteTempPackageFiles() {
15463        final FilenameFilter filter = new FilenameFilter() {
15464            public boolean accept(File dir, String name) {
15465                return name.startsWith("vmdl") && name.endsWith(".tmp");
15466            }
15467        };
15468        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15469            file.delete();
15470        }
15471    }
15472
15473    @Override
15474    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15475            int flags) {
15476        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15477                flags);
15478    }
15479
15480    @Override
15481    public void deletePackage(final String packageName,
15482            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15483        mContext.enforceCallingOrSelfPermission(
15484                android.Manifest.permission.DELETE_PACKAGES, null);
15485        Preconditions.checkNotNull(packageName);
15486        Preconditions.checkNotNull(observer);
15487        final int uid = Binder.getCallingUid();
15488        if (!isOrphaned(packageName)
15489                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15490            try {
15491                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15492                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15493                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15494                observer.onUserActionRequired(intent);
15495            } catch (RemoteException re) {
15496            }
15497            return;
15498        }
15499        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15500        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15501        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15502            mContext.enforceCallingOrSelfPermission(
15503                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15504                    "deletePackage for user " + userId);
15505        }
15506
15507        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15508            try {
15509                observer.onPackageDeleted(packageName,
15510                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15511            } catch (RemoteException re) {
15512            }
15513            return;
15514        }
15515
15516        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15517            try {
15518                observer.onPackageDeleted(packageName,
15519                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15520            } catch (RemoteException re) {
15521            }
15522            return;
15523        }
15524
15525        if (DEBUG_REMOVE) {
15526            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15527                    + " deleteAllUsers: " + deleteAllUsers );
15528        }
15529        // Queue up an async operation since the package deletion may take a little while.
15530        mHandler.post(new Runnable() {
15531            public void run() {
15532                mHandler.removeCallbacks(this);
15533                int returnCode;
15534                if (!deleteAllUsers) {
15535                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15536                } else {
15537                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15538                    // If nobody is blocking uninstall, proceed with delete for all users
15539                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15540                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15541                    } else {
15542                        // Otherwise uninstall individually for users with blockUninstalls=false
15543                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15544                        for (int userId : users) {
15545                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15546                                returnCode = deletePackageX(packageName, userId, userFlags);
15547                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15548                                    Slog.w(TAG, "Package delete failed for user " + userId
15549                                            + ", returnCode " + returnCode);
15550                                }
15551                            }
15552                        }
15553                        // The app has only been marked uninstalled for certain users.
15554                        // We still need to report that delete was blocked
15555                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15556                    }
15557                }
15558                try {
15559                    observer.onPackageDeleted(packageName, returnCode, null);
15560                } catch (RemoteException e) {
15561                    Log.i(TAG, "Observer no longer exists.");
15562                } //end catch
15563            } //end run
15564        });
15565    }
15566
15567    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15568        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15569              || callingUid == Process.SYSTEM_UID) {
15570            return true;
15571        }
15572        final int callingUserId = UserHandle.getUserId(callingUid);
15573        // If the caller installed the pkgName, then allow it to silently uninstall.
15574        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15575            return true;
15576        }
15577
15578        // Allow package verifier to silently uninstall.
15579        if (mRequiredVerifierPackage != null &&
15580                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15581            return true;
15582        }
15583
15584        // Allow package uninstaller to silently uninstall.
15585        if (mRequiredUninstallerPackage != null &&
15586                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15587            return true;
15588        }
15589
15590        // Allow storage manager to silently uninstall.
15591        if (mStorageManagerPackage != null &&
15592                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
15593            return true;
15594        }
15595        return false;
15596    }
15597
15598    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15599        int[] result = EMPTY_INT_ARRAY;
15600        for (int userId : userIds) {
15601            if (getBlockUninstallForUser(packageName, userId)) {
15602                result = ArrayUtils.appendInt(result, userId);
15603            }
15604        }
15605        return result;
15606    }
15607
15608    @Override
15609    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15610        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15611    }
15612
15613    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15614        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15615                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15616        try {
15617            if (dpm != null) {
15618                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15619                        /* callingUserOnly =*/ false);
15620                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15621                        : deviceOwnerComponentName.getPackageName();
15622                // Does the package contains the device owner?
15623                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15624                // this check is probably not needed, since DO should be registered as a device
15625                // admin on some user too. (Original bug for this: b/17657954)
15626                if (packageName.equals(deviceOwnerPackageName)) {
15627                    return true;
15628                }
15629                // Does it contain a device admin for any user?
15630                int[] users;
15631                if (userId == UserHandle.USER_ALL) {
15632                    users = sUserManager.getUserIds();
15633                } else {
15634                    users = new int[]{userId};
15635                }
15636                for (int i = 0; i < users.length; ++i) {
15637                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15638                        return true;
15639                    }
15640                }
15641            }
15642        } catch (RemoteException e) {
15643        }
15644        return false;
15645    }
15646
15647    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15648        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15649    }
15650
15651    /**
15652     *  This method is an internal method that could be get invoked either
15653     *  to delete an installed package or to clean up a failed installation.
15654     *  After deleting an installed package, a broadcast is sent to notify any
15655     *  listeners that the package has been removed. For cleaning up a failed
15656     *  installation, the broadcast is not necessary since the package's
15657     *  installation wouldn't have sent the initial broadcast either
15658     *  The key steps in deleting a package are
15659     *  deleting the package information in internal structures like mPackages,
15660     *  deleting the packages base directories through installd
15661     *  updating mSettings to reflect current status
15662     *  persisting settings for later use
15663     *  sending a broadcast if necessary
15664     */
15665    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15666        final PackageRemovedInfo info = new PackageRemovedInfo();
15667        final boolean res;
15668
15669        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15670                ? UserHandle.USER_ALL : userId;
15671
15672        if (isPackageDeviceAdmin(packageName, removeUser)) {
15673            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15674            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15675        }
15676
15677        PackageSetting uninstalledPs = null;
15678
15679        // for the uninstall-updates case and restricted profiles, remember the per-
15680        // user handle installed state
15681        int[] allUsers;
15682        synchronized (mPackages) {
15683            uninstalledPs = mSettings.mPackages.get(packageName);
15684            if (uninstalledPs == null) {
15685                Slog.w(TAG, "Not removing non-existent package " + packageName);
15686                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15687            }
15688            allUsers = sUserManager.getUserIds();
15689            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15690        }
15691
15692        final int freezeUser;
15693        if (isUpdatedSystemApp(uninstalledPs)
15694                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15695            // We're downgrading a system app, which will apply to all users, so
15696            // freeze them all during the downgrade
15697            freezeUser = UserHandle.USER_ALL;
15698        } else {
15699            freezeUser = removeUser;
15700        }
15701
15702        synchronized (mInstallLock) {
15703            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15704            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15705                    deleteFlags, "deletePackageX")) {
15706                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15707                        deleteFlags | REMOVE_CHATTY, info, true, null);
15708            }
15709            synchronized (mPackages) {
15710                if (res) {
15711                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15712                }
15713            }
15714        }
15715
15716        if (res) {
15717            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15718            info.sendPackageRemovedBroadcasts(killApp);
15719            info.sendSystemPackageUpdatedBroadcasts();
15720            info.sendSystemPackageAppearedBroadcasts();
15721        }
15722        // Force a gc here.
15723        Runtime.getRuntime().gc();
15724        // Delete the resources here after sending the broadcast to let
15725        // other processes clean up before deleting resources.
15726        if (info.args != null) {
15727            synchronized (mInstallLock) {
15728                info.args.doPostDeleteLI(true);
15729            }
15730        }
15731
15732        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15733    }
15734
15735    class PackageRemovedInfo {
15736        String removedPackage;
15737        int uid = -1;
15738        int removedAppId = -1;
15739        int[] origUsers;
15740        int[] removedUsers = null;
15741        boolean isRemovedPackageSystemUpdate = false;
15742        boolean isUpdate;
15743        boolean dataRemoved;
15744        boolean removedForAllUsers;
15745        // Clean up resources deleted packages.
15746        InstallArgs args = null;
15747        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15748        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15749
15750        void sendPackageRemovedBroadcasts(boolean killApp) {
15751            sendPackageRemovedBroadcastInternal(killApp);
15752            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15753            for (int i = 0; i < childCount; i++) {
15754                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15755                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15756            }
15757        }
15758
15759        void sendSystemPackageUpdatedBroadcasts() {
15760            if (isRemovedPackageSystemUpdate) {
15761                sendSystemPackageUpdatedBroadcastsInternal();
15762                final int childCount = (removedChildPackages != null)
15763                        ? removedChildPackages.size() : 0;
15764                for (int i = 0; i < childCount; i++) {
15765                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15766                    if (childInfo.isRemovedPackageSystemUpdate) {
15767                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15768                    }
15769                }
15770            }
15771        }
15772
15773        void sendSystemPackageAppearedBroadcasts() {
15774            final int packageCount = (appearedChildPackages != null)
15775                    ? appearedChildPackages.size() : 0;
15776            for (int i = 0; i < packageCount; i++) {
15777                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15778                for (int userId : installedInfo.newUsers) {
15779                    sendPackageAddedForUser(installedInfo.name, true,
15780                            UserHandle.getAppId(installedInfo.uid), userId);
15781                }
15782            }
15783        }
15784
15785        private void sendSystemPackageUpdatedBroadcastsInternal() {
15786            Bundle extras = new Bundle(2);
15787            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15788            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15789            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15790                    extras, 0, null, null, null);
15791            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15792                    extras, 0, null, null, null);
15793            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15794                    null, 0, removedPackage, null, null);
15795        }
15796
15797        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15798            Bundle extras = new Bundle(2);
15799            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15800            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15801            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15802            if (isUpdate || isRemovedPackageSystemUpdate) {
15803                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15804            }
15805            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15806            if (removedPackage != null) {
15807                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15808                        extras, 0, null, null, removedUsers);
15809                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15810                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15811                            removedPackage, extras, 0, null, null, removedUsers);
15812                }
15813            }
15814            if (removedAppId >= 0) {
15815                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15816                        removedUsers);
15817            }
15818        }
15819    }
15820
15821    /*
15822     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15823     * flag is not set, the data directory is removed as well.
15824     * make sure this flag is set for partially installed apps. If not its meaningless to
15825     * delete a partially installed application.
15826     */
15827    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15828            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15829        String packageName = ps.name;
15830        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15831        // Retrieve object to delete permissions for shared user later on
15832        final PackageParser.Package deletedPkg;
15833        final PackageSetting deletedPs;
15834        // reader
15835        synchronized (mPackages) {
15836            deletedPkg = mPackages.get(packageName);
15837            deletedPs = mSettings.mPackages.get(packageName);
15838            if (outInfo != null) {
15839                outInfo.removedPackage = packageName;
15840                outInfo.removedUsers = deletedPs != null
15841                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15842                        : null;
15843            }
15844        }
15845
15846        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15847
15848        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15849            final PackageParser.Package resolvedPkg;
15850            if (deletedPkg != null) {
15851                resolvedPkg = deletedPkg;
15852            } else {
15853                // We don't have a parsed package when it lives on an ejected
15854                // adopted storage device, so fake something together
15855                resolvedPkg = new PackageParser.Package(ps.name);
15856                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15857            }
15858            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15859                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15860            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15861            if (outInfo != null) {
15862                outInfo.dataRemoved = true;
15863            }
15864            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15865        }
15866
15867        // writer
15868        synchronized (mPackages) {
15869            if (deletedPs != null) {
15870                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15871                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15872                    clearDefaultBrowserIfNeeded(packageName);
15873                    if (outInfo != null) {
15874                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15875                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15876                    }
15877                    updatePermissionsLPw(deletedPs.name, null, 0);
15878                    if (deletedPs.sharedUser != null) {
15879                        // Remove permissions associated with package. Since runtime
15880                        // permissions are per user we have to kill the removed package
15881                        // or packages running under the shared user of the removed
15882                        // package if revoking the permissions requested only by the removed
15883                        // package is successful and this causes a change in gids.
15884                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15885                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15886                                    userId);
15887                            if (userIdToKill == UserHandle.USER_ALL
15888                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15889                                // If gids changed for this user, kill all affected packages.
15890                                mHandler.post(new Runnable() {
15891                                    @Override
15892                                    public void run() {
15893                                        // This has to happen with no lock held.
15894                                        killApplication(deletedPs.name, deletedPs.appId,
15895                                                KILL_APP_REASON_GIDS_CHANGED);
15896                                    }
15897                                });
15898                                break;
15899                            }
15900                        }
15901                    }
15902                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15903                }
15904                // make sure to preserve per-user disabled state if this removal was just
15905                // a downgrade of a system app to the factory package
15906                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15907                    if (DEBUG_REMOVE) {
15908                        Slog.d(TAG, "Propagating install state across downgrade");
15909                    }
15910                    for (int userId : allUserHandles) {
15911                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15912                        if (DEBUG_REMOVE) {
15913                            Slog.d(TAG, "    user " + userId + " => " + installed);
15914                        }
15915                        ps.setInstalled(installed, userId);
15916                    }
15917                }
15918            }
15919            // can downgrade to reader
15920            if (writeSettings) {
15921                // Save settings now
15922                mSettings.writeLPr();
15923            }
15924        }
15925        if (outInfo != null) {
15926            // A user ID was deleted here. Go through all users and remove it
15927            // from KeyStore.
15928            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15929        }
15930    }
15931
15932    static boolean locationIsPrivileged(File path) {
15933        try {
15934            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15935                    .getCanonicalPath();
15936            return path.getCanonicalPath().startsWith(privilegedAppDir);
15937        } catch (IOException e) {
15938            Slog.e(TAG, "Unable to access code path " + path);
15939        }
15940        return false;
15941    }
15942
15943    /*
15944     * Tries to delete system package.
15945     */
15946    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15947            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15948            boolean writeSettings) {
15949        if (deletedPs.parentPackageName != null) {
15950            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15951            return false;
15952        }
15953
15954        final boolean applyUserRestrictions
15955                = (allUserHandles != null) && (outInfo.origUsers != null);
15956        final PackageSetting disabledPs;
15957        // Confirm if the system package has been updated
15958        // An updated system app can be deleted. This will also have to restore
15959        // the system pkg from system partition
15960        // reader
15961        synchronized (mPackages) {
15962            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15963        }
15964
15965        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15966                + " disabledPs=" + disabledPs);
15967
15968        if (disabledPs == null) {
15969            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15970            return false;
15971        } else if (DEBUG_REMOVE) {
15972            Slog.d(TAG, "Deleting system pkg from data partition");
15973        }
15974
15975        if (DEBUG_REMOVE) {
15976            if (applyUserRestrictions) {
15977                Slog.d(TAG, "Remembering install states:");
15978                for (int userId : allUserHandles) {
15979                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15980                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15981                }
15982            }
15983        }
15984
15985        // Delete the updated package
15986        outInfo.isRemovedPackageSystemUpdate = true;
15987        if (outInfo.removedChildPackages != null) {
15988            final int childCount = (deletedPs.childPackageNames != null)
15989                    ? deletedPs.childPackageNames.size() : 0;
15990            for (int i = 0; i < childCount; i++) {
15991                String childPackageName = deletedPs.childPackageNames.get(i);
15992                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15993                        .contains(childPackageName)) {
15994                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15995                            childPackageName);
15996                    if (childInfo != null) {
15997                        childInfo.isRemovedPackageSystemUpdate = true;
15998                    }
15999                }
16000            }
16001        }
16002
16003        if (disabledPs.versionCode < deletedPs.versionCode) {
16004            // Delete data for downgrades
16005            flags &= ~PackageManager.DELETE_KEEP_DATA;
16006        } else {
16007            // Preserve data by setting flag
16008            flags |= PackageManager.DELETE_KEEP_DATA;
16009        }
16010
16011        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16012                outInfo, writeSettings, disabledPs.pkg);
16013        if (!ret) {
16014            return false;
16015        }
16016
16017        // writer
16018        synchronized (mPackages) {
16019            // Reinstate the old system package
16020            enableSystemPackageLPw(disabledPs.pkg);
16021            // Remove any native libraries from the upgraded package.
16022            removeNativeBinariesLI(deletedPs);
16023        }
16024
16025        // Install the system package
16026        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16027        int parseFlags = mDefParseFlags
16028                | PackageParser.PARSE_MUST_BE_APK
16029                | PackageParser.PARSE_IS_SYSTEM
16030                | PackageParser.PARSE_IS_SYSTEM_DIR;
16031        if (locationIsPrivileged(disabledPs.codePath)) {
16032            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16033        }
16034
16035        final PackageParser.Package newPkg;
16036        try {
16037            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16038        } catch (PackageManagerException e) {
16039            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16040                    + e.getMessage());
16041            return false;
16042        }
16043        try {
16044            // update shared libraries for the newly re-installed system package
16045            updateSharedLibrariesLPw(newPkg, null);
16046        } catch (PackageManagerException e) {
16047            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16048        }
16049
16050        prepareAppDataAfterInstallLIF(newPkg);
16051
16052        // writer
16053        synchronized (mPackages) {
16054            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16055
16056            // Propagate the permissions state as we do not want to drop on the floor
16057            // runtime permissions. The update permissions method below will take
16058            // care of removing obsolete permissions and grant install permissions.
16059            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16060            updatePermissionsLPw(newPkg.packageName, newPkg,
16061                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16062
16063            if (applyUserRestrictions) {
16064                if (DEBUG_REMOVE) {
16065                    Slog.d(TAG, "Propagating install state across reinstall");
16066                }
16067                for (int userId : allUserHandles) {
16068                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16069                    if (DEBUG_REMOVE) {
16070                        Slog.d(TAG, "    user " + userId + " => " + installed);
16071                    }
16072                    ps.setInstalled(installed, userId);
16073
16074                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16075                }
16076                // Regardless of writeSettings we need to ensure that this restriction
16077                // state propagation is persisted
16078                mSettings.writeAllUsersPackageRestrictionsLPr();
16079            }
16080            // can downgrade to reader here
16081            if (writeSettings) {
16082                mSettings.writeLPr();
16083            }
16084        }
16085        return true;
16086    }
16087
16088    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16089            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16090            PackageRemovedInfo outInfo, boolean writeSettings,
16091            PackageParser.Package replacingPackage) {
16092        synchronized (mPackages) {
16093            if (outInfo != null) {
16094                outInfo.uid = ps.appId;
16095            }
16096
16097            if (outInfo != null && outInfo.removedChildPackages != null) {
16098                final int childCount = (ps.childPackageNames != null)
16099                        ? ps.childPackageNames.size() : 0;
16100                for (int i = 0; i < childCount; i++) {
16101                    String childPackageName = ps.childPackageNames.get(i);
16102                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16103                    if (childPs == null) {
16104                        return false;
16105                    }
16106                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16107                            childPackageName);
16108                    if (childInfo != null) {
16109                        childInfo.uid = childPs.appId;
16110                    }
16111                }
16112            }
16113        }
16114
16115        // Delete package data from internal structures and also remove data if flag is set
16116        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16117
16118        // Delete the child packages data
16119        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16120        for (int i = 0; i < childCount; i++) {
16121            PackageSetting childPs;
16122            synchronized (mPackages) {
16123                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16124            }
16125            if (childPs != null) {
16126                PackageRemovedInfo childOutInfo = (outInfo != null
16127                        && outInfo.removedChildPackages != null)
16128                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16129                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16130                        && (replacingPackage != null
16131                        && !replacingPackage.hasChildPackage(childPs.name))
16132                        ? flags & ~DELETE_KEEP_DATA : flags;
16133                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16134                        deleteFlags, writeSettings);
16135            }
16136        }
16137
16138        // Delete application code and resources only for parent packages
16139        if (ps.parentPackageName == null) {
16140            if (deleteCodeAndResources && (outInfo != null)) {
16141                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16142                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16143                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16144            }
16145        }
16146
16147        return true;
16148    }
16149
16150    @Override
16151    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16152            int userId) {
16153        mContext.enforceCallingOrSelfPermission(
16154                android.Manifest.permission.DELETE_PACKAGES, null);
16155        synchronized (mPackages) {
16156            PackageSetting ps = mSettings.mPackages.get(packageName);
16157            if (ps == null) {
16158                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16159                return false;
16160            }
16161            if (!ps.getInstalled(userId)) {
16162                // Can't block uninstall for an app that is not installed or enabled.
16163                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16164                return false;
16165            }
16166            ps.setBlockUninstall(blockUninstall, userId);
16167            mSettings.writePackageRestrictionsLPr(userId);
16168        }
16169        return true;
16170    }
16171
16172    @Override
16173    public boolean getBlockUninstallForUser(String packageName, int userId) {
16174        synchronized (mPackages) {
16175            PackageSetting ps = mSettings.mPackages.get(packageName);
16176            if (ps == null) {
16177                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16178                return false;
16179            }
16180            return ps.getBlockUninstall(userId);
16181        }
16182    }
16183
16184    @Override
16185    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16186        int callingUid = Binder.getCallingUid();
16187        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16188            throw new SecurityException(
16189                    "setRequiredForSystemUser can only be run by the system or root");
16190        }
16191        synchronized (mPackages) {
16192            PackageSetting ps = mSettings.mPackages.get(packageName);
16193            if (ps == null) {
16194                Log.w(TAG, "Package doesn't exist: " + packageName);
16195                return false;
16196            }
16197            if (systemUserApp) {
16198                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16199            } else {
16200                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16201            }
16202            mSettings.writeLPr();
16203        }
16204        return true;
16205    }
16206
16207    /*
16208     * This method handles package deletion in general
16209     */
16210    private boolean deletePackageLIF(String packageName, UserHandle user,
16211            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16212            PackageRemovedInfo outInfo, boolean writeSettings,
16213            PackageParser.Package replacingPackage) {
16214        if (packageName == null) {
16215            Slog.w(TAG, "Attempt to delete null packageName.");
16216            return false;
16217        }
16218
16219        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16220
16221        PackageSetting ps;
16222
16223        synchronized (mPackages) {
16224            ps = mSettings.mPackages.get(packageName);
16225            if (ps == null) {
16226                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16227                return false;
16228            }
16229
16230            if (ps.parentPackageName != null && (!isSystemApp(ps)
16231                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16232                if (DEBUG_REMOVE) {
16233                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16234                            + ((user == null) ? UserHandle.USER_ALL : user));
16235                }
16236                final int removedUserId = (user != null) ? user.getIdentifier()
16237                        : UserHandle.USER_ALL;
16238                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16239                    return false;
16240                }
16241                markPackageUninstalledForUserLPw(ps, user);
16242                scheduleWritePackageRestrictionsLocked(user);
16243                return true;
16244            }
16245        }
16246
16247        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16248                && user.getIdentifier() != UserHandle.USER_ALL)) {
16249            // The caller is asking that the package only be deleted for a single
16250            // user.  To do this, we just mark its uninstalled state and delete
16251            // its data. If this is a system app, we only allow this to happen if
16252            // they have set the special DELETE_SYSTEM_APP which requests different
16253            // semantics than normal for uninstalling system apps.
16254            markPackageUninstalledForUserLPw(ps, user);
16255
16256            if (!isSystemApp(ps)) {
16257                // Do not uninstall the APK if an app should be cached
16258                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16259                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16260                    // Other user still have this package installed, so all
16261                    // we need to do is clear this user's data and save that
16262                    // it is uninstalled.
16263                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16264                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16265                        return false;
16266                    }
16267                    scheduleWritePackageRestrictionsLocked(user);
16268                    return true;
16269                } else {
16270                    // We need to set it back to 'installed' so the uninstall
16271                    // broadcasts will be sent correctly.
16272                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16273                    ps.setInstalled(true, user.getIdentifier());
16274                }
16275            } else {
16276                // This is a system app, so we assume that the
16277                // other users still have this package installed, so all
16278                // we need to do is clear this user's data and save that
16279                // it is uninstalled.
16280                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16281                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16282                    return false;
16283                }
16284                scheduleWritePackageRestrictionsLocked(user);
16285                return true;
16286            }
16287        }
16288
16289        // If we are deleting a composite package for all users, keep track
16290        // of result for each child.
16291        if (ps.childPackageNames != null && outInfo != null) {
16292            synchronized (mPackages) {
16293                final int childCount = ps.childPackageNames.size();
16294                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16295                for (int i = 0; i < childCount; i++) {
16296                    String childPackageName = ps.childPackageNames.get(i);
16297                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16298                    childInfo.removedPackage = childPackageName;
16299                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16300                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16301                    if (childPs != null) {
16302                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16303                    }
16304                }
16305            }
16306        }
16307
16308        boolean ret = false;
16309        if (isSystemApp(ps)) {
16310            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16311            // When an updated system application is deleted we delete the existing resources
16312            // as well and fall back to existing code in system partition
16313            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16314        } else {
16315            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16316            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16317                    outInfo, writeSettings, replacingPackage);
16318        }
16319
16320        // Take a note whether we deleted the package for all users
16321        if (outInfo != null) {
16322            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16323            if (outInfo.removedChildPackages != null) {
16324                synchronized (mPackages) {
16325                    final int childCount = outInfo.removedChildPackages.size();
16326                    for (int i = 0; i < childCount; i++) {
16327                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16328                        if (childInfo != null) {
16329                            childInfo.removedForAllUsers = mPackages.get(
16330                                    childInfo.removedPackage) == null;
16331                        }
16332                    }
16333                }
16334            }
16335            // If we uninstalled an update to a system app there may be some
16336            // child packages that appeared as they are declared in the system
16337            // app but were not declared in the update.
16338            if (isSystemApp(ps)) {
16339                synchronized (mPackages) {
16340                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16341                    final int childCount = (updatedPs.childPackageNames != null)
16342                            ? updatedPs.childPackageNames.size() : 0;
16343                    for (int i = 0; i < childCount; i++) {
16344                        String childPackageName = updatedPs.childPackageNames.get(i);
16345                        if (outInfo.removedChildPackages == null
16346                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16347                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16348                            if (childPs == null) {
16349                                continue;
16350                            }
16351                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16352                            installRes.name = childPackageName;
16353                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16354                            installRes.pkg = mPackages.get(childPackageName);
16355                            installRes.uid = childPs.pkg.applicationInfo.uid;
16356                            if (outInfo.appearedChildPackages == null) {
16357                                outInfo.appearedChildPackages = new ArrayMap<>();
16358                            }
16359                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16360                        }
16361                    }
16362                }
16363            }
16364        }
16365
16366        return ret;
16367    }
16368
16369    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16370        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16371                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16372        for (int nextUserId : userIds) {
16373            if (DEBUG_REMOVE) {
16374                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16375            }
16376            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16377                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16378                    false /*hidden*/, false /*suspended*/, null, null, null,
16379                    false /*blockUninstall*/,
16380                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16381        }
16382    }
16383
16384    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16385            PackageRemovedInfo outInfo) {
16386        final PackageParser.Package pkg;
16387        synchronized (mPackages) {
16388            pkg = mPackages.get(ps.name);
16389        }
16390
16391        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16392                : new int[] {userId};
16393        for (int nextUserId : userIds) {
16394            if (DEBUG_REMOVE) {
16395                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16396                        + nextUserId);
16397            }
16398
16399            destroyAppDataLIF(pkg, userId,
16400                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16401            destroyAppProfilesLIF(pkg, userId);
16402            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16403            schedulePackageCleaning(ps.name, nextUserId, false);
16404            synchronized (mPackages) {
16405                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16406                    scheduleWritePackageRestrictionsLocked(nextUserId);
16407                }
16408                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16409            }
16410        }
16411
16412        if (outInfo != null) {
16413            outInfo.removedPackage = ps.name;
16414            outInfo.removedAppId = ps.appId;
16415            outInfo.removedUsers = userIds;
16416        }
16417
16418        return true;
16419    }
16420
16421    private final class ClearStorageConnection implements ServiceConnection {
16422        IMediaContainerService mContainerService;
16423
16424        @Override
16425        public void onServiceConnected(ComponentName name, IBinder service) {
16426            synchronized (this) {
16427                mContainerService = IMediaContainerService.Stub.asInterface(service);
16428                notifyAll();
16429            }
16430        }
16431
16432        @Override
16433        public void onServiceDisconnected(ComponentName name) {
16434        }
16435    }
16436
16437    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16438        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16439
16440        final boolean mounted;
16441        if (Environment.isExternalStorageEmulated()) {
16442            mounted = true;
16443        } else {
16444            final String status = Environment.getExternalStorageState();
16445
16446            mounted = status.equals(Environment.MEDIA_MOUNTED)
16447                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16448        }
16449
16450        if (!mounted) {
16451            return;
16452        }
16453
16454        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16455        int[] users;
16456        if (userId == UserHandle.USER_ALL) {
16457            users = sUserManager.getUserIds();
16458        } else {
16459            users = new int[] { userId };
16460        }
16461        final ClearStorageConnection conn = new ClearStorageConnection();
16462        if (mContext.bindServiceAsUser(
16463                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16464            try {
16465                for (int curUser : users) {
16466                    long timeout = SystemClock.uptimeMillis() + 5000;
16467                    synchronized (conn) {
16468                        long now;
16469                        while (conn.mContainerService == null &&
16470                                (now = SystemClock.uptimeMillis()) < timeout) {
16471                            try {
16472                                conn.wait(timeout - now);
16473                            } catch (InterruptedException e) {
16474                            }
16475                        }
16476                    }
16477                    if (conn.mContainerService == null) {
16478                        return;
16479                    }
16480
16481                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16482                    clearDirectory(conn.mContainerService,
16483                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16484                    if (allData) {
16485                        clearDirectory(conn.mContainerService,
16486                                userEnv.buildExternalStorageAppDataDirs(packageName));
16487                        clearDirectory(conn.mContainerService,
16488                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16489                    }
16490                }
16491            } finally {
16492                mContext.unbindService(conn);
16493            }
16494        }
16495    }
16496
16497    @Override
16498    public void clearApplicationProfileData(String packageName) {
16499        enforceSystemOrRoot("Only the system can clear all profile data");
16500
16501        final PackageParser.Package pkg;
16502        synchronized (mPackages) {
16503            pkg = mPackages.get(packageName);
16504        }
16505
16506        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16507            synchronized (mInstallLock) {
16508                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16509                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16510                        true /* removeBaseMarker */);
16511            }
16512        }
16513    }
16514
16515    @Override
16516    public void clearApplicationUserData(final String packageName,
16517            final IPackageDataObserver observer, final int userId) {
16518        mContext.enforceCallingOrSelfPermission(
16519                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16520
16521        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16522                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16523
16524        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16525            throw new SecurityException("Cannot clear data for a protected package: "
16526                    + packageName);
16527        }
16528        // Queue up an async operation since the package deletion may take a little while.
16529        mHandler.post(new Runnable() {
16530            public void run() {
16531                mHandler.removeCallbacks(this);
16532                final boolean succeeded;
16533                try (PackageFreezer freezer = freezePackage(packageName,
16534                        "clearApplicationUserData")) {
16535                    synchronized (mInstallLock) {
16536                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16537                    }
16538                    clearExternalStorageDataSync(packageName, userId, true);
16539                }
16540                if (succeeded) {
16541                    // invoke DeviceStorageMonitor's update method to clear any notifications
16542                    DeviceStorageMonitorInternal dsm = LocalServices
16543                            .getService(DeviceStorageMonitorInternal.class);
16544                    if (dsm != null) {
16545                        dsm.checkMemory();
16546                    }
16547                }
16548                if(observer != null) {
16549                    try {
16550                        observer.onRemoveCompleted(packageName, succeeded);
16551                    } catch (RemoteException e) {
16552                        Log.i(TAG, "Observer no longer exists.");
16553                    }
16554                } //end if observer
16555            } //end run
16556        });
16557    }
16558
16559    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16560        if (packageName == null) {
16561            Slog.w(TAG, "Attempt to delete null packageName.");
16562            return false;
16563        }
16564
16565        // Try finding details about the requested package
16566        PackageParser.Package pkg;
16567        synchronized (mPackages) {
16568            pkg = mPackages.get(packageName);
16569            if (pkg == null) {
16570                final PackageSetting ps = mSettings.mPackages.get(packageName);
16571                if (ps != null) {
16572                    pkg = ps.pkg;
16573                }
16574            }
16575
16576            if (pkg == null) {
16577                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16578                return false;
16579            }
16580
16581            PackageSetting ps = (PackageSetting) pkg.mExtras;
16582            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16583        }
16584
16585        clearAppDataLIF(pkg, userId,
16586                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16587
16588        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16589        removeKeystoreDataIfNeeded(userId, appId);
16590
16591        UserManagerInternal umInternal = getUserManagerInternal();
16592        final int flags;
16593        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16594            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16595        } else if (umInternal.isUserRunning(userId)) {
16596            flags = StorageManager.FLAG_STORAGE_DE;
16597        } else {
16598            flags = 0;
16599        }
16600        prepareAppDataContentsLIF(pkg, userId, flags);
16601
16602        return true;
16603    }
16604
16605    /**
16606     * Reverts user permission state changes (permissions and flags) in
16607     * all packages for a given user.
16608     *
16609     * @param userId The device user for which to do a reset.
16610     */
16611    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16612        final int packageCount = mPackages.size();
16613        for (int i = 0; i < packageCount; i++) {
16614            PackageParser.Package pkg = mPackages.valueAt(i);
16615            PackageSetting ps = (PackageSetting) pkg.mExtras;
16616            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16617        }
16618    }
16619
16620    private void resetNetworkPolicies(int userId) {
16621        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16622    }
16623
16624    /**
16625     * Reverts user permission state changes (permissions and flags).
16626     *
16627     * @param ps The package for which to reset.
16628     * @param userId The device user for which to do a reset.
16629     */
16630    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16631            final PackageSetting ps, final int userId) {
16632        if (ps.pkg == null) {
16633            return;
16634        }
16635
16636        // These are flags that can change base on user actions.
16637        final int userSettableMask = FLAG_PERMISSION_USER_SET
16638                | FLAG_PERMISSION_USER_FIXED
16639                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16640                | FLAG_PERMISSION_REVIEW_REQUIRED;
16641
16642        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16643                | FLAG_PERMISSION_POLICY_FIXED;
16644
16645        boolean writeInstallPermissions = false;
16646        boolean writeRuntimePermissions = false;
16647
16648        final int permissionCount = ps.pkg.requestedPermissions.size();
16649        for (int i = 0; i < permissionCount; i++) {
16650            String permission = ps.pkg.requestedPermissions.get(i);
16651
16652            BasePermission bp = mSettings.mPermissions.get(permission);
16653            if (bp == null) {
16654                continue;
16655            }
16656
16657            // If shared user we just reset the state to which only this app contributed.
16658            if (ps.sharedUser != null) {
16659                boolean used = false;
16660                final int packageCount = ps.sharedUser.packages.size();
16661                for (int j = 0; j < packageCount; j++) {
16662                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16663                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16664                            && pkg.pkg.requestedPermissions.contains(permission)) {
16665                        used = true;
16666                        break;
16667                    }
16668                }
16669                if (used) {
16670                    continue;
16671                }
16672            }
16673
16674            PermissionsState permissionsState = ps.getPermissionsState();
16675
16676            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16677
16678            // Always clear the user settable flags.
16679            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16680                    bp.name) != null;
16681            // If permission review is enabled and this is a legacy app, mark the
16682            // permission as requiring a review as this is the initial state.
16683            int flags = 0;
16684            if (mPermissionReviewRequired
16685                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16686                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16687            }
16688            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16689                if (hasInstallState) {
16690                    writeInstallPermissions = true;
16691                } else {
16692                    writeRuntimePermissions = true;
16693                }
16694            }
16695
16696            // Below is only runtime permission handling.
16697            if (!bp.isRuntime()) {
16698                continue;
16699            }
16700
16701            // Never clobber system or policy.
16702            if ((oldFlags & policyOrSystemFlags) != 0) {
16703                continue;
16704            }
16705
16706            // If this permission was granted by default, make sure it is.
16707            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16708                if (permissionsState.grantRuntimePermission(bp, userId)
16709                        != PERMISSION_OPERATION_FAILURE) {
16710                    writeRuntimePermissions = true;
16711                }
16712            // If permission review is enabled the permissions for a legacy apps
16713            // are represented as constantly granted runtime ones, so don't revoke.
16714            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16715                // Otherwise, reset the permission.
16716                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16717                switch (revokeResult) {
16718                    case PERMISSION_OPERATION_SUCCESS:
16719                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16720                        writeRuntimePermissions = true;
16721                        final int appId = ps.appId;
16722                        mHandler.post(new Runnable() {
16723                            @Override
16724                            public void run() {
16725                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16726                            }
16727                        });
16728                    } break;
16729                }
16730            }
16731        }
16732
16733        // Synchronously write as we are taking permissions away.
16734        if (writeRuntimePermissions) {
16735            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16736        }
16737
16738        // Synchronously write as we are taking permissions away.
16739        if (writeInstallPermissions) {
16740            mSettings.writeLPr();
16741        }
16742    }
16743
16744    /**
16745     * Remove entries from the keystore daemon. Will only remove it if the
16746     * {@code appId} is valid.
16747     */
16748    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16749        if (appId < 0) {
16750            return;
16751        }
16752
16753        final KeyStore keyStore = KeyStore.getInstance();
16754        if (keyStore != null) {
16755            if (userId == UserHandle.USER_ALL) {
16756                for (final int individual : sUserManager.getUserIds()) {
16757                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16758                }
16759            } else {
16760                keyStore.clearUid(UserHandle.getUid(userId, appId));
16761            }
16762        } else {
16763            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16764        }
16765    }
16766
16767    @Override
16768    public void deleteApplicationCacheFiles(final String packageName,
16769            final IPackageDataObserver observer) {
16770        final int userId = UserHandle.getCallingUserId();
16771        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16772    }
16773
16774    @Override
16775    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16776            final IPackageDataObserver observer) {
16777        mContext.enforceCallingOrSelfPermission(
16778                android.Manifest.permission.DELETE_CACHE_FILES, null);
16779        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16780                /* requireFullPermission= */ true, /* checkShell= */ false,
16781                "delete application cache files");
16782
16783        final PackageParser.Package pkg;
16784        synchronized (mPackages) {
16785            pkg = mPackages.get(packageName);
16786        }
16787
16788        // Queue up an async operation since the package deletion may take a little while.
16789        mHandler.post(new Runnable() {
16790            public void run() {
16791                synchronized (mInstallLock) {
16792                    final int flags = StorageManager.FLAG_STORAGE_DE
16793                            | StorageManager.FLAG_STORAGE_CE;
16794                    // We're only clearing cache files, so we don't care if the
16795                    // app is unfrozen and still able to run
16796                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16797                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16798                }
16799                clearExternalStorageDataSync(packageName, userId, false);
16800                if (observer != null) {
16801                    try {
16802                        observer.onRemoveCompleted(packageName, true);
16803                    } catch (RemoteException e) {
16804                        Log.i(TAG, "Observer no longer exists.");
16805                    }
16806                }
16807            }
16808        });
16809    }
16810
16811    @Override
16812    public void getPackageSizeInfo(final String packageName, int userHandle,
16813            final IPackageStatsObserver observer) {
16814        mContext.enforceCallingOrSelfPermission(
16815                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16816        if (packageName == null) {
16817            throw new IllegalArgumentException("Attempt to get size of null packageName");
16818        }
16819
16820        PackageStats stats = new PackageStats(packageName, userHandle);
16821
16822        /*
16823         * Queue up an async operation since the package measurement may take a
16824         * little while.
16825         */
16826        Message msg = mHandler.obtainMessage(INIT_COPY);
16827        msg.obj = new MeasureParams(stats, observer);
16828        mHandler.sendMessage(msg);
16829    }
16830
16831    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16832        final PackageSetting ps;
16833        synchronized (mPackages) {
16834            ps = mSettings.mPackages.get(packageName);
16835            if (ps == null) {
16836                Slog.w(TAG, "Failed to find settings for " + packageName);
16837                return false;
16838            }
16839        }
16840        try {
16841            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16842                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16843                    ps.getCeDataInode(userId), ps.codePathString, stats);
16844        } catch (InstallerException e) {
16845            Slog.w(TAG, String.valueOf(e));
16846            return false;
16847        }
16848
16849        // For now, ignore code size of packages on system partition
16850        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16851            stats.codeSize = 0;
16852        }
16853
16854        return true;
16855    }
16856
16857    private int getUidTargetSdkVersionLockedLPr(int uid) {
16858        Object obj = mSettings.getUserIdLPr(uid);
16859        if (obj instanceof SharedUserSetting) {
16860            final SharedUserSetting sus = (SharedUserSetting) obj;
16861            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16862            final Iterator<PackageSetting> it = sus.packages.iterator();
16863            while (it.hasNext()) {
16864                final PackageSetting ps = it.next();
16865                if (ps.pkg != null) {
16866                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16867                    if (v < vers) vers = v;
16868                }
16869            }
16870            return vers;
16871        } else if (obj instanceof PackageSetting) {
16872            final PackageSetting ps = (PackageSetting) obj;
16873            if (ps.pkg != null) {
16874                return ps.pkg.applicationInfo.targetSdkVersion;
16875            }
16876        }
16877        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16878    }
16879
16880    @Override
16881    public void addPreferredActivity(IntentFilter filter, int match,
16882            ComponentName[] set, ComponentName activity, int userId) {
16883        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16884                "Adding preferred");
16885    }
16886
16887    private void addPreferredActivityInternal(IntentFilter filter, int match,
16888            ComponentName[] set, ComponentName activity, boolean always, int userId,
16889            String opname) {
16890        // writer
16891        int callingUid = Binder.getCallingUid();
16892        enforceCrossUserPermission(callingUid, userId,
16893                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16894        if (filter.countActions() == 0) {
16895            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16896            return;
16897        }
16898        synchronized (mPackages) {
16899            if (mContext.checkCallingOrSelfPermission(
16900                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16901                    != PackageManager.PERMISSION_GRANTED) {
16902                if (getUidTargetSdkVersionLockedLPr(callingUid)
16903                        < Build.VERSION_CODES.FROYO) {
16904                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16905                            + callingUid);
16906                    return;
16907                }
16908                mContext.enforceCallingOrSelfPermission(
16909                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16910            }
16911
16912            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16913            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16914                    + userId + ":");
16915            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16916            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16917            scheduleWritePackageRestrictionsLocked(userId);
16918            postPreferredActivityChangedBroadcast(userId);
16919        }
16920    }
16921
16922    private void postPreferredActivityChangedBroadcast(int userId) {
16923        mHandler.post(() -> {
16924            final IActivityManager am = ActivityManagerNative.getDefault();
16925            if (am == null) {
16926                return;
16927            }
16928
16929            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
16930            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
16931            try {
16932                am.broadcastIntent(null, intent, null, null,
16933                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
16934                        null, false, false, userId);
16935            } catch (RemoteException e) {
16936            }
16937        });
16938    }
16939
16940    @Override
16941    public void replacePreferredActivity(IntentFilter filter, int match,
16942            ComponentName[] set, ComponentName activity, int userId) {
16943        if (filter.countActions() != 1) {
16944            throw new IllegalArgumentException(
16945                    "replacePreferredActivity expects filter to have only 1 action.");
16946        }
16947        if (filter.countDataAuthorities() != 0
16948                || filter.countDataPaths() != 0
16949                || filter.countDataSchemes() > 1
16950                || filter.countDataTypes() != 0) {
16951            throw new IllegalArgumentException(
16952                    "replacePreferredActivity expects filter to have no data authorities, " +
16953                    "paths, or types; and at most one scheme.");
16954        }
16955
16956        final int callingUid = Binder.getCallingUid();
16957        enforceCrossUserPermission(callingUid, userId,
16958                true /* requireFullPermission */, false /* checkShell */,
16959                "replace preferred activity");
16960        synchronized (mPackages) {
16961            if (mContext.checkCallingOrSelfPermission(
16962                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16963                    != PackageManager.PERMISSION_GRANTED) {
16964                if (getUidTargetSdkVersionLockedLPr(callingUid)
16965                        < Build.VERSION_CODES.FROYO) {
16966                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16967                            + Binder.getCallingUid());
16968                    return;
16969                }
16970                mContext.enforceCallingOrSelfPermission(
16971                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16972            }
16973
16974            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16975            if (pir != null) {
16976                // Get all of the existing entries that exactly match this filter.
16977                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16978                if (existing != null && existing.size() == 1) {
16979                    PreferredActivity cur = existing.get(0);
16980                    if (DEBUG_PREFERRED) {
16981                        Slog.i(TAG, "Checking replace of preferred:");
16982                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16983                        if (!cur.mPref.mAlways) {
16984                            Slog.i(TAG, "  -- CUR; not mAlways!");
16985                        } else {
16986                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16987                            Slog.i(TAG, "  -- CUR: mSet="
16988                                    + Arrays.toString(cur.mPref.mSetComponents));
16989                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16990                            Slog.i(TAG, "  -- NEW: mMatch="
16991                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16992                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16993                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16994                        }
16995                    }
16996                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16997                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16998                            && cur.mPref.sameSet(set)) {
16999                        // Setting the preferred activity to what it happens to be already
17000                        if (DEBUG_PREFERRED) {
17001                            Slog.i(TAG, "Replacing with same preferred activity "
17002                                    + cur.mPref.mShortComponent + " for user "
17003                                    + userId + ":");
17004                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17005                        }
17006                        return;
17007                    }
17008                }
17009
17010                if (existing != null) {
17011                    if (DEBUG_PREFERRED) {
17012                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17013                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17014                    }
17015                    for (int i = 0; i < existing.size(); i++) {
17016                        PreferredActivity pa = existing.get(i);
17017                        if (DEBUG_PREFERRED) {
17018                            Slog.i(TAG, "Removing existing preferred activity "
17019                                    + pa.mPref.mComponent + ":");
17020                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17021                        }
17022                        pir.removeFilter(pa);
17023                    }
17024                }
17025            }
17026            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17027                    "Replacing preferred");
17028        }
17029    }
17030
17031    @Override
17032    public void clearPackagePreferredActivities(String packageName) {
17033        final int uid = Binder.getCallingUid();
17034        // writer
17035        synchronized (mPackages) {
17036            PackageParser.Package pkg = mPackages.get(packageName);
17037            if (pkg == null || pkg.applicationInfo.uid != uid) {
17038                if (mContext.checkCallingOrSelfPermission(
17039                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17040                        != PackageManager.PERMISSION_GRANTED) {
17041                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17042                            < Build.VERSION_CODES.FROYO) {
17043                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17044                                + Binder.getCallingUid());
17045                        return;
17046                    }
17047                    mContext.enforceCallingOrSelfPermission(
17048                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17049                }
17050            }
17051
17052            int user = UserHandle.getCallingUserId();
17053            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17054                scheduleWritePackageRestrictionsLocked(user);
17055            }
17056        }
17057    }
17058
17059    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17060    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17061        ArrayList<PreferredActivity> removed = null;
17062        boolean changed = false;
17063        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17064            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17065            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17066            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17067                continue;
17068            }
17069            Iterator<PreferredActivity> it = pir.filterIterator();
17070            while (it.hasNext()) {
17071                PreferredActivity pa = it.next();
17072                // Mark entry for removal only if it matches the package name
17073                // and the entry is of type "always".
17074                if (packageName == null ||
17075                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17076                                && pa.mPref.mAlways)) {
17077                    if (removed == null) {
17078                        removed = new ArrayList<PreferredActivity>();
17079                    }
17080                    removed.add(pa);
17081                }
17082            }
17083            if (removed != null) {
17084                for (int j=0; j<removed.size(); j++) {
17085                    PreferredActivity pa = removed.get(j);
17086                    pir.removeFilter(pa);
17087                }
17088                changed = true;
17089            }
17090        }
17091        if (changed) {
17092            postPreferredActivityChangedBroadcast(userId);
17093        }
17094        return changed;
17095    }
17096
17097    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17098    private void clearIntentFilterVerificationsLPw(int userId) {
17099        final int packageCount = mPackages.size();
17100        for (int i = 0; i < packageCount; i++) {
17101            PackageParser.Package pkg = mPackages.valueAt(i);
17102            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17103        }
17104    }
17105
17106    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17107    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17108        if (userId == UserHandle.USER_ALL) {
17109            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17110                    sUserManager.getUserIds())) {
17111                for (int oneUserId : sUserManager.getUserIds()) {
17112                    scheduleWritePackageRestrictionsLocked(oneUserId);
17113                }
17114            }
17115        } else {
17116            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17117                scheduleWritePackageRestrictionsLocked(userId);
17118            }
17119        }
17120    }
17121
17122    void clearDefaultBrowserIfNeeded(String packageName) {
17123        for (int oneUserId : sUserManager.getUserIds()) {
17124            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17125            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17126            if (packageName.equals(defaultBrowserPackageName)) {
17127                setDefaultBrowserPackageName(null, oneUserId);
17128            }
17129        }
17130    }
17131
17132    @Override
17133    public void resetApplicationPreferences(int userId) {
17134        mContext.enforceCallingOrSelfPermission(
17135                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17136        final long identity = Binder.clearCallingIdentity();
17137        // writer
17138        try {
17139            synchronized (mPackages) {
17140                clearPackagePreferredActivitiesLPw(null, userId);
17141                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17142                // TODO: We have to reset the default SMS and Phone. This requires
17143                // significant refactoring to keep all default apps in the package
17144                // manager (cleaner but more work) or have the services provide
17145                // callbacks to the package manager to request a default app reset.
17146                applyFactoryDefaultBrowserLPw(userId);
17147                clearIntentFilterVerificationsLPw(userId);
17148                primeDomainVerificationsLPw(userId);
17149                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17150                scheduleWritePackageRestrictionsLocked(userId);
17151            }
17152            resetNetworkPolicies(userId);
17153        } finally {
17154            Binder.restoreCallingIdentity(identity);
17155        }
17156    }
17157
17158    @Override
17159    public int getPreferredActivities(List<IntentFilter> outFilters,
17160            List<ComponentName> outActivities, String packageName) {
17161
17162        int num = 0;
17163        final int userId = UserHandle.getCallingUserId();
17164        // reader
17165        synchronized (mPackages) {
17166            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17167            if (pir != null) {
17168                final Iterator<PreferredActivity> it = pir.filterIterator();
17169                while (it.hasNext()) {
17170                    final PreferredActivity pa = it.next();
17171                    if (packageName == null
17172                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17173                                    && pa.mPref.mAlways)) {
17174                        if (outFilters != null) {
17175                            outFilters.add(new IntentFilter(pa));
17176                        }
17177                        if (outActivities != null) {
17178                            outActivities.add(pa.mPref.mComponent);
17179                        }
17180                    }
17181                }
17182            }
17183        }
17184
17185        return num;
17186    }
17187
17188    @Override
17189    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17190            int userId) {
17191        int callingUid = Binder.getCallingUid();
17192        if (callingUid != Process.SYSTEM_UID) {
17193            throw new SecurityException(
17194                    "addPersistentPreferredActivity can only be run by the system");
17195        }
17196        if (filter.countActions() == 0) {
17197            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17198            return;
17199        }
17200        synchronized (mPackages) {
17201            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17202                    ":");
17203            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17204            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17205                    new PersistentPreferredActivity(filter, activity));
17206            scheduleWritePackageRestrictionsLocked(userId);
17207            postPreferredActivityChangedBroadcast(userId);
17208        }
17209    }
17210
17211    @Override
17212    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17213        int callingUid = Binder.getCallingUid();
17214        if (callingUid != Process.SYSTEM_UID) {
17215            throw new SecurityException(
17216                    "clearPackagePersistentPreferredActivities can only be run by the system");
17217        }
17218        ArrayList<PersistentPreferredActivity> removed = null;
17219        boolean changed = false;
17220        synchronized (mPackages) {
17221            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17222                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17223                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17224                        .valueAt(i);
17225                if (userId != thisUserId) {
17226                    continue;
17227                }
17228                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17229                while (it.hasNext()) {
17230                    PersistentPreferredActivity ppa = it.next();
17231                    // Mark entry for removal only if it matches the package name.
17232                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17233                        if (removed == null) {
17234                            removed = new ArrayList<PersistentPreferredActivity>();
17235                        }
17236                        removed.add(ppa);
17237                    }
17238                }
17239                if (removed != null) {
17240                    for (int j=0; j<removed.size(); j++) {
17241                        PersistentPreferredActivity ppa = removed.get(j);
17242                        ppir.removeFilter(ppa);
17243                    }
17244                    changed = true;
17245                }
17246            }
17247
17248            if (changed) {
17249                scheduleWritePackageRestrictionsLocked(userId);
17250                postPreferredActivityChangedBroadcast(userId);
17251            }
17252        }
17253    }
17254
17255    /**
17256     * Common machinery for picking apart a restored XML blob and passing
17257     * it to a caller-supplied functor to be applied to the running system.
17258     */
17259    private void restoreFromXml(XmlPullParser parser, int userId,
17260            String expectedStartTag, BlobXmlRestorer functor)
17261            throws IOException, XmlPullParserException {
17262        int type;
17263        while ((type = parser.next()) != XmlPullParser.START_TAG
17264                && type != XmlPullParser.END_DOCUMENT) {
17265        }
17266        if (type != XmlPullParser.START_TAG) {
17267            // oops didn't find a start tag?!
17268            if (DEBUG_BACKUP) {
17269                Slog.e(TAG, "Didn't find start tag during restore");
17270            }
17271            return;
17272        }
17273Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17274        // this is supposed to be TAG_PREFERRED_BACKUP
17275        if (!expectedStartTag.equals(parser.getName())) {
17276            if (DEBUG_BACKUP) {
17277                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17278            }
17279            return;
17280        }
17281
17282        // skip interfering stuff, then we're aligned with the backing implementation
17283        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17284Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17285        functor.apply(parser, userId);
17286    }
17287
17288    private interface BlobXmlRestorer {
17289        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17290    }
17291
17292    /**
17293     * Non-Binder method, support for the backup/restore mechanism: write the
17294     * full set of preferred activities in its canonical XML format.  Returns the
17295     * XML output as a byte array, or null if there is none.
17296     */
17297    @Override
17298    public byte[] getPreferredActivityBackup(int userId) {
17299        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17300            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17301        }
17302
17303        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17304        try {
17305            final XmlSerializer serializer = new FastXmlSerializer();
17306            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17307            serializer.startDocument(null, true);
17308            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17309
17310            synchronized (mPackages) {
17311                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17312            }
17313
17314            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17315            serializer.endDocument();
17316            serializer.flush();
17317        } catch (Exception e) {
17318            if (DEBUG_BACKUP) {
17319                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17320            }
17321            return null;
17322        }
17323
17324        return dataStream.toByteArray();
17325    }
17326
17327    @Override
17328    public void restorePreferredActivities(byte[] backup, int userId) {
17329        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17330            throw new SecurityException("Only the system may call restorePreferredActivities()");
17331        }
17332
17333        try {
17334            final XmlPullParser parser = Xml.newPullParser();
17335            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17336            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17337                    new BlobXmlRestorer() {
17338                        @Override
17339                        public void apply(XmlPullParser parser, int userId)
17340                                throws XmlPullParserException, IOException {
17341                            synchronized (mPackages) {
17342                                mSettings.readPreferredActivitiesLPw(parser, userId);
17343                            }
17344                        }
17345                    } );
17346        } catch (Exception e) {
17347            if (DEBUG_BACKUP) {
17348                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17349            }
17350        }
17351    }
17352
17353    /**
17354     * Non-Binder method, support for the backup/restore mechanism: write the
17355     * default browser (etc) settings in its canonical XML format.  Returns the default
17356     * browser XML representation as a byte array, or null if there is none.
17357     */
17358    @Override
17359    public byte[] getDefaultAppsBackup(int userId) {
17360        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17361            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17362        }
17363
17364        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17365        try {
17366            final XmlSerializer serializer = new FastXmlSerializer();
17367            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17368            serializer.startDocument(null, true);
17369            serializer.startTag(null, TAG_DEFAULT_APPS);
17370
17371            synchronized (mPackages) {
17372                mSettings.writeDefaultAppsLPr(serializer, userId);
17373            }
17374
17375            serializer.endTag(null, TAG_DEFAULT_APPS);
17376            serializer.endDocument();
17377            serializer.flush();
17378        } catch (Exception e) {
17379            if (DEBUG_BACKUP) {
17380                Slog.e(TAG, "Unable to write default apps for backup", e);
17381            }
17382            return null;
17383        }
17384
17385        return dataStream.toByteArray();
17386    }
17387
17388    @Override
17389    public void restoreDefaultApps(byte[] backup, int userId) {
17390        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17391            throw new SecurityException("Only the system may call restoreDefaultApps()");
17392        }
17393
17394        try {
17395            final XmlPullParser parser = Xml.newPullParser();
17396            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17397            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17398                    new BlobXmlRestorer() {
17399                        @Override
17400                        public void apply(XmlPullParser parser, int userId)
17401                                throws XmlPullParserException, IOException {
17402                            synchronized (mPackages) {
17403                                mSettings.readDefaultAppsLPw(parser, userId);
17404                            }
17405                        }
17406                    } );
17407        } catch (Exception e) {
17408            if (DEBUG_BACKUP) {
17409                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17410            }
17411        }
17412    }
17413
17414    @Override
17415    public byte[] getIntentFilterVerificationBackup(int userId) {
17416        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17417            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17418        }
17419
17420        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17421        try {
17422            final XmlSerializer serializer = new FastXmlSerializer();
17423            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17424            serializer.startDocument(null, true);
17425            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17426
17427            synchronized (mPackages) {
17428                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17429            }
17430
17431            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17432            serializer.endDocument();
17433            serializer.flush();
17434        } catch (Exception e) {
17435            if (DEBUG_BACKUP) {
17436                Slog.e(TAG, "Unable to write default apps for backup", e);
17437            }
17438            return null;
17439        }
17440
17441        return dataStream.toByteArray();
17442    }
17443
17444    @Override
17445    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17446        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17447            throw new SecurityException("Only the system may call restorePreferredActivities()");
17448        }
17449
17450        try {
17451            final XmlPullParser parser = Xml.newPullParser();
17452            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17453            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17454                    new BlobXmlRestorer() {
17455                        @Override
17456                        public void apply(XmlPullParser parser, int userId)
17457                                throws XmlPullParserException, IOException {
17458                            synchronized (mPackages) {
17459                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17460                                mSettings.writeLPr();
17461                            }
17462                        }
17463                    } );
17464        } catch (Exception e) {
17465            if (DEBUG_BACKUP) {
17466                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17467            }
17468        }
17469    }
17470
17471    @Override
17472    public byte[] getPermissionGrantBackup(int userId) {
17473        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17474            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17475        }
17476
17477        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17478        try {
17479            final XmlSerializer serializer = new FastXmlSerializer();
17480            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17481            serializer.startDocument(null, true);
17482            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17483
17484            synchronized (mPackages) {
17485                serializeRuntimePermissionGrantsLPr(serializer, userId);
17486            }
17487
17488            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17489            serializer.endDocument();
17490            serializer.flush();
17491        } catch (Exception e) {
17492            if (DEBUG_BACKUP) {
17493                Slog.e(TAG, "Unable to write default apps for backup", e);
17494            }
17495            return null;
17496        }
17497
17498        return dataStream.toByteArray();
17499    }
17500
17501    @Override
17502    public void restorePermissionGrants(byte[] backup, int userId) {
17503        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17504            throw new SecurityException("Only the system may call restorePermissionGrants()");
17505        }
17506
17507        try {
17508            final XmlPullParser parser = Xml.newPullParser();
17509            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17510            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17511                    new BlobXmlRestorer() {
17512                        @Override
17513                        public void apply(XmlPullParser parser, int userId)
17514                                throws XmlPullParserException, IOException {
17515                            synchronized (mPackages) {
17516                                processRestoredPermissionGrantsLPr(parser, userId);
17517                            }
17518                        }
17519                    } );
17520        } catch (Exception e) {
17521            if (DEBUG_BACKUP) {
17522                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17523            }
17524        }
17525    }
17526
17527    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17528            throws IOException {
17529        serializer.startTag(null, TAG_ALL_GRANTS);
17530
17531        final int N = mSettings.mPackages.size();
17532        for (int i = 0; i < N; i++) {
17533            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17534            boolean pkgGrantsKnown = false;
17535
17536            PermissionsState packagePerms = ps.getPermissionsState();
17537
17538            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17539                final int grantFlags = state.getFlags();
17540                // only look at grants that are not system/policy fixed
17541                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17542                    final boolean isGranted = state.isGranted();
17543                    // And only back up the user-twiddled state bits
17544                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17545                        final String packageName = mSettings.mPackages.keyAt(i);
17546                        if (!pkgGrantsKnown) {
17547                            serializer.startTag(null, TAG_GRANT);
17548                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17549                            pkgGrantsKnown = true;
17550                        }
17551
17552                        final boolean userSet =
17553                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17554                        final boolean userFixed =
17555                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17556                        final boolean revoke =
17557                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17558
17559                        serializer.startTag(null, TAG_PERMISSION);
17560                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17561                        if (isGranted) {
17562                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17563                        }
17564                        if (userSet) {
17565                            serializer.attribute(null, ATTR_USER_SET, "true");
17566                        }
17567                        if (userFixed) {
17568                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17569                        }
17570                        if (revoke) {
17571                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17572                        }
17573                        serializer.endTag(null, TAG_PERMISSION);
17574                    }
17575                }
17576            }
17577
17578            if (pkgGrantsKnown) {
17579                serializer.endTag(null, TAG_GRANT);
17580            }
17581        }
17582
17583        serializer.endTag(null, TAG_ALL_GRANTS);
17584    }
17585
17586    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17587            throws XmlPullParserException, IOException {
17588        String pkgName = null;
17589        int outerDepth = parser.getDepth();
17590        int type;
17591        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17592                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17593            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17594                continue;
17595            }
17596
17597            final String tagName = parser.getName();
17598            if (tagName.equals(TAG_GRANT)) {
17599                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17600                if (DEBUG_BACKUP) {
17601                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17602                }
17603            } else if (tagName.equals(TAG_PERMISSION)) {
17604
17605                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17606                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17607
17608                int newFlagSet = 0;
17609                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17610                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17611                }
17612                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17613                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17614                }
17615                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17616                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17617                }
17618                if (DEBUG_BACKUP) {
17619                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17620                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17621                }
17622                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17623                if (ps != null) {
17624                    // Already installed so we apply the grant immediately
17625                    if (DEBUG_BACKUP) {
17626                        Slog.v(TAG, "        + already installed; applying");
17627                    }
17628                    PermissionsState perms = ps.getPermissionsState();
17629                    BasePermission bp = mSettings.mPermissions.get(permName);
17630                    if (bp != null) {
17631                        if (isGranted) {
17632                            perms.grantRuntimePermission(bp, userId);
17633                        }
17634                        if (newFlagSet != 0) {
17635                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17636                        }
17637                    }
17638                } else {
17639                    // Need to wait for post-restore install to apply the grant
17640                    if (DEBUG_BACKUP) {
17641                        Slog.v(TAG, "        - not yet installed; saving for later");
17642                    }
17643                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17644                            isGranted, newFlagSet, userId);
17645                }
17646            } else {
17647                PackageManagerService.reportSettingsProblem(Log.WARN,
17648                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17649                XmlUtils.skipCurrentTag(parser);
17650            }
17651        }
17652
17653        scheduleWriteSettingsLocked();
17654        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17655    }
17656
17657    @Override
17658    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17659            int sourceUserId, int targetUserId, int flags) {
17660        mContext.enforceCallingOrSelfPermission(
17661                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17662        int callingUid = Binder.getCallingUid();
17663        enforceOwnerRights(ownerPackage, callingUid);
17664        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17665        if (intentFilter.countActions() == 0) {
17666            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17667            return;
17668        }
17669        synchronized (mPackages) {
17670            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17671                    ownerPackage, targetUserId, flags);
17672            CrossProfileIntentResolver resolver =
17673                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17674            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17675            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17676            if (existing != null) {
17677                int size = existing.size();
17678                for (int i = 0; i < size; i++) {
17679                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17680                        return;
17681                    }
17682                }
17683            }
17684            resolver.addFilter(newFilter);
17685            scheduleWritePackageRestrictionsLocked(sourceUserId);
17686        }
17687    }
17688
17689    @Override
17690    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17691        mContext.enforceCallingOrSelfPermission(
17692                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17693        int callingUid = Binder.getCallingUid();
17694        enforceOwnerRights(ownerPackage, callingUid);
17695        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17696        synchronized (mPackages) {
17697            CrossProfileIntentResolver resolver =
17698                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17699            ArraySet<CrossProfileIntentFilter> set =
17700                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17701            for (CrossProfileIntentFilter filter : set) {
17702                if (filter.getOwnerPackage().equals(ownerPackage)) {
17703                    resolver.removeFilter(filter);
17704                }
17705            }
17706            scheduleWritePackageRestrictionsLocked(sourceUserId);
17707        }
17708    }
17709
17710    // Enforcing that callingUid is owning pkg on userId
17711    private void enforceOwnerRights(String pkg, int callingUid) {
17712        // The system owns everything.
17713        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17714            return;
17715        }
17716        int callingUserId = UserHandle.getUserId(callingUid);
17717        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17718        if (pi == null) {
17719            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17720                    + callingUserId);
17721        }
17722        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17723            throw new SecurityException("Calling uid " + callingUid
17724                    + " does not own package " + pkg);
17725        }
17726    }
17727
17728    @Override
17729    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17730        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17731    }
17732
17733    private Intent getHomeIntent() {
17734        Intent intent = new Intent(Intent.ACTION_MAIN);
17735        intent.addCategory(Intent.CATEGORY_HOME);
17736        intent.addCategory(Intent.CATEGORY_DEFAULT);
17737        return intent;
17738    }
17739
17740    private IntentFilter getHomeFilter() {
17741        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17742        filter.addCategory(Intent.CATEGORY_HOME);
17743        filter.addCategory(Intent.CATEGORY_DEFAULT);
17744        return filter;
17745    }
17746
17747    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17748            int userId) {
17749        Intent intent  = getHomeIntent();
17750        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17751                PackageManager.GET_META_DATA, userId);
17752        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17753                true, false, false, userId);
17754
17755        allHomeCandidates.clear();
17756        if (list != null) {
17757            for (ResolveInfo ri : list) {
17758                allHomeCandidates.add(ri);
17759            }
17760        }
17761        return (preferred == null || preferred.activityInfo == null)
17762                ? null
17763                : new ComponentName(preferred.activityInfo.packageName,
17764                        preferred.activityInfo.name);
17765    }
17766
17767    @Override
17768    public void setHomeActivity(ComponentName comp, int userId) {
17769        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17770        getHomeActivitiesAsUser(homeActivities, userId);
17771
17772        boolean found = false;
17773
17774        final int size = homeActivities.size();
17775        final ComponentName[] set = new ComponentName[size];
17776        for (int i = 0; i < size; i++) {
17777            final ResolveInfo candidate = homeActivities.get(i);
17778            final ActivityInfo info = candidate.activityInfo;
17779            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17780            set[i] = activityName;
17781            if (!found && activityName.equals(comp)) {
17782                found = true;
17783            }
17784        }
17785        if (!found) {
17786            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17787                    + userId);
17788        }
17789        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17790                set, comp, userId);
17791    }
17792
17793    private @Nullable String getSetupWizardPackageName() {
17794        final Intent intent = new Intent(Intent.ACTION_MAIN);
17795        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17796
17797        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17798                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17799                        | MATCH_DISABLED_COMPONENTS,
17800                UserHandle.myUserId());
17801        if (matches.size() == 1) {
17802            return matches.get(0).getComponentInfo().packageName;
17803        } else {
17804            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17805                    + ": matches=" + matches);
17806            return null;
17807        }
17808    }
17809
17810    private @Nullable String getStorageManagerPackageName() {
17811        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
17812
17813        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17814                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17815                        | MATCH_DISABLED_COMPONENTS,
17816                UserHandle.myUserId());
17817        if (matches.size() == 1) {
17818            return matches.get(0).getComponentInfo().packageName;
17819        } else {
17820            Slog.e(TAG, "There should probably be exactly one storage manager; found "
17821                    + matches.size() + ": matches=" + matches);
17822            return null;
17823        }
17824    }
17825
17826    @Override
17827    public void setApplicationEnabledSetting(String appPackageName,
17828            int newState, int flags, int userId, String callingPackage) {
17829        if (!sUserManager.exists(userId)) return;
17830        if (callingPackage == null) {
17831            callingPackage = Integer.toString(Binder.getCallingUid());
17832        }
17833        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17834    }
17835
17836    @Override
17837    public void setComponentEnabledSetting(ComponentName componentName,
17838            int newState, int flags, int userId) {
17839        if (!sUserManager.exists(userId)) return;
17840        setEnabledSetting(componentName.getPackageName(),
17841                componentName.getClassName(), newState, flags, userId, null);
17842    }
17843
17844    private void setEnabledSetting(final String packageName, String className, int newState,
17845            final int flags, int userId, String callingPackage) {
17846        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17847              || newState == COMPONENT_ENABLED_STATE_ENABLED
17848              || newState == COMPONENT_ENABLED_STATE_DISABLED
17849              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17850              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17851            throw new IllegalArgumentException("Invalid new component state: "
17852                    + newState);
17853        }
17854        PackageSetting pkgSetting;
17855        final int uid = Binder.getCallingUid();
17856        final int permission;
17857        if (uid == Process.SYSTEM_UID) {
17858            permission = PackageManager.PERMISSION_GRANTED;
17859        } else {
17860            permission = mContext.checkCallingOrSelfPermission(
17861                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17862        }
17863        enforceCrossUserPermission(uid, userId,
17864                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17865        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17866        boolean sendNow = false;
17867        boolean isApp = (className == null);
17868        String componentName = isApp ? packageName : className;
17869        int packageUid = -1;
17870        ArrayList<String> components;
17871
17872        // writer
17873        synchronized (mPackages) {
17874            pkgSetting = mSettings.mPackages.get(packageName);
17875            if (pkgSetting == null) {
17876                if (className == null) {
17877                    throw new IllegalArgumentException("Unknown package: " + packageName);
17878                }
17879                throw new IllegalArgumentException(
17880                        "Unknown component: " + packageName + "/" + className);
17881            }
17882        }
17883
17884        // Limit who can change which apps
17885        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17886            // Don't allow apps that don't have permission to modify other apps
17887            if (!allowedByPermission) {
17888                throw new SecurityException(
17889                        "Permission Denial: attempt to change component state from pid="
17890                        + Binder.getCallingPid()
17891                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17892            }
17893            // Don't allow changing protected packages.
17894            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17895                throw new SecurityException("Cannot disable a protected package: " + packageName);
17896            }
17897        }
17898
17899        synchronized (mPackages) {
17900            if (uid == Process.SHELL_UID) {
17901                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17902                int oldState = pkgSetting.getEnabled(userId);
17903                if (className == null
17904                    &&
17905                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17906                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17907                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17908                    &&
17909                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17910                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17911                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17912                    // ok
17913                } else {
17914                    throw new SecurityException(
17915                            "Shell cannot change component state for " + packageName + "/"
17916                            + className + " to " + newState);
17917                }
17918            }
17919            if (className == null) {
17920                // We're dealing with an application/package level state change
17921                if (pkgSetting.getEnabled(userId) == newState) {
17922                    // Nothing to do
17923                    return;
17924                }
17925                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17926                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17927                    // Don't care about who enables an app.
17928                    callingPackage = null;
17929                }
17930                pkgSetting.setEnabled(newState, userId, callingPackage);
17931                // pkgSetting.pkg.mSetEnabled = newState;
17932            } else {
17933                // We're dealing with a component level state change
17934                // First, verify that this is a valid class name.
17935                PackageParser.Package pkg = pkgSetting.pkg;
17936                if (pkg == null || !pkg.hasComponentClassName(className)) {
17937                    if (pkg != null &&
17938                            pkg.applicationInfo.targetSdkVersion >=
17939                                    Build.VERSION_CODES.JELLY_BEAN) {
17940                        throw new IllegalArgumentException("Component class " + className
17941                                + " does not exist in " + packageName);
17942                    } else {
17943                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17944                                + className + " does not exist in " + packageName);
17945                    }
17946                }
17947                switch (newState) {
17948                case COMPONENT_ENABLED_STATE_ENABLED:
17949                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17950                        return;
17951                    }
17952                    break;
17953                case COMPONENT_ENABLED_STATE_DISABLED:
17954                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17955                        return;
17956                    }
17957                    break;
17958                case COMPONENT_ENABLED_STATE_DEFAULT:
17959                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17960                        return;
17961                    }
17962                    break;
17963                default:
17964                    Slog.e(TAG, "Invalid new component state: " + newState);
17965                    return;
17966                }
17967            }
17968            scheduleWritePackageRestrictionsLocked(userId);
17969            components = mPendingBroadcasts.get(userId, packageName);
17970            final boolean newPackage = components == null;
17971            if (newPackage) {
17972                components = new ArrayList<String>();
17973            }
17974            if (!components.contains(componentName)) {
17975                components.add(componentName);
17976            }
17977            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17978                sendNow = true;
17979                // Purge entry from pending broadcast list if another one exists already
17980                // since we are sending one right away.
17981                mPendingBroadcasts.remove(userId, packageName);
17982            } else {
17983                if (newPackage) {
17984                    mPendingBroadcasts.put(userId, packageName, components);
17985                }
17986                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17987                    // Schedule a message
17988                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17989                }
17990            }
17991        }
17992
17993        long callingId = Binder.clearCallingIdentity();
17994        try {
17995            if (sendNow) {
17996                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17997                sendPackageChangedBroadcast(packageName,
17998                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17999            }
18000        } finally {
18001            Binder.restoreCallingIdentity(callingId);
18002        }
18003    }
18004
18005    @Override
18006    public void flushPackageRestrictionsAsUser(int userId) {
18007        if (!sUserManager.exists(userId)) {
18008            return;
18009        }
18010        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18011                false /* checkShell */, "flushPackageRestrictions");
18012        synchronized (mPackages) {
18013            mSettings.writePackageRestrictionsLPr(userId);
18014            mDirtyUsers.remove(userId);
18015            if (mDirtyUsers.isEmpty()) {
18016                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18017            }
18018        }
18019    }
18020
18021    private void sendPackageChangedBroadcast(String packageName,
18022            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18023        if (DEBUG_INSTALL)
18024            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18025                    + componentNames);
18026        Bundle extras = new Bundle(4);
18027        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18028        String nameList[] = new String[componentNames.size()];
18029        componentNames.toArray(nameList);
18030        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18031        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18032        extras.putInt(Intent.EXTRA_UID, packageUid);
18033        // If this is not reporting a change of the overall package, then only send it
18034        // to registered receivers.  We don't want to launch a swath of apps for every
18035        // little component state change.
18036        final int flags = !componentNames.contains(packageName)
18037                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18038        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18039                new int[] {UserHandle.getUserId(packageUid)});
18040    }
18041
18042    @Override
18043    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18044        if (!sUserManager.exists(userId)) return;
18045        final int uid = Binder.getCallingUid();
18046        final int permission = mContext.checkCallingOrSelfPermission(
18047                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18048        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18049        enforceCrossUserPermission(uid, userId,
18050                true /* requireFullPermission */, true /* checkShell */, "stop package");
18051        // writer
18052        synchronized (mPackages) {
18053            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18054                    allowedByPermission, uid, userId)) {
18055                scheduleWritePackageRestrictionsLocked(userId);
18056            }
18057        }
18058    }
18059
18060    @Override
18061    public String getInstallerPackageName(String packageName) {
18062        // reader
18063        synchronized (mPackages) {
18064            return mSettings.getInstallerPackageNameLPr(packageName);
18065        }
18066    }
18067
18068    public boolean isOrphaned(String packageName) {
18069        // reader
18070        synchronized (mPackages) {
18071            return mSettings.isOrphaned(packageName);
18072        }
18073    }
18074
18075    @Override
18076    public int getApplicationEnabledSetting(String packageName, int userId) {
18077        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18078        int uid = Binder.getCallingUid();
18079        enforceCrossUserPermission(uid, userId,
18080                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18081        // reader
18082        synchronized (mPackages) {
18083            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18084        }
18085    }
18086
18087    @Override
18088    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18089        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18090        int uid = Binder.getCallingUid();
18091        enforceCrossUserPermission(uid, userId,
18092                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18093        // reader
18094        synchronized (mPackages) {
18095            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18096        }
18097    }
18098
18099    @Override
18100    public void enterSafeMode() {
18101        enforceSystemOrRoot("Only the system can request entering safe mode");
18102
18103        if (!mSystemReady) {
18104            mSafeMode = true;
18105        }
18106    }
18107
18108    @Override
18109    public void systemReady() {
18110        mSystemReady = true;
18111
18112        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18113        // disabled after already being started.
18114        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18115                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18116
18117        // Read the compatibilty setting when the system is ready.
18118        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18119                mContext.getContentResolver(),
18120                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18121        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18122        if (DEBUG_SETTINGS) {
18123            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18124        }
18125
18126        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18127
18128        synchronized (mPackages) {
18129            // Verify that all of the preferred activity components actually
18130            // exist.  It is possible for applications to be updated and at
18131            // that point remove a previously declared activity component that
18132            // had been set as a preferred activity.  We try to clean this up
18133            // the next time we encounter that preferred activity, but it is
18134            // possible for the user flow to never be able to return to that
18135            // situation so here we do a sanity check to make sure we haven't
18136            // left any junk around.
18137            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18138            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18139                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18140                removed.clear();
18141                for (PreferredActivity pa : pir.filterSet()) {
18142                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18143                        removed.add(pa);
18144                    }
18145                }
18146                if (removed.size() > 0) {
18147                    for (int r=0; r<removed.size(); r++) {
18148                        PreferredActivity pa = removed.get(r);
18149                        Slog.w(TAG, "Removing dangling preferred activity: "
18150                                + pa.mPref.mComponent);
18151                        pir.removeFilter(pa);
18152                    }
18153                    mSettings.writePackageRestrictionsLPr(
18154                            mSettings.mPreferredActivities.keyAt(i));
18155                }
18156            }
18157
18158            for (int userId : UserManagerService.getInstance().getUserIds()) {
18159                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18160                    grantPermissionsUserIds = ArrayUtils.appendInt(
18161                            grantPermissionsUserIds, userId);
18162                }
18163            }
18164        }
18165        sUserManager.systemReady();
18166
18167        // If we upgraded grant all default permissions before kicking off.
18168        for (int userId : grantPermissionsUserIds) {
18169            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18170        }
18171
18172        // If we did not grant default permissions, we preload from this the
18173        // default permission exceptions lazily to ensure we don't hit the
18174        // disk on a new user creation.
18175        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18176            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18177        }
18178
18179        // Kick off any messages waiting for system ready
18180        if (mPostSystemReadyMessages != null) {
18181            for (Message msg : mPostSystemReadyMessages) {
18182                msg.sendToTarget();
18183            }
18184            mPostSystemReadyMessages = null;
18185        }
18186
18187        // Watch for external volumes that come and go over time
18188        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18189        storage.registerListener(mStorageListener);
18190
18191        mInstallerService.systemReady();
18192        mPackageDexOptimizer.systemReady();
18193
18194        MountServiceInternal mountServiceInternal = LocalServices.getService(
18195                MountServiceInternal.class);
18196        mountServiceInternal.addExternalStoragePolicy(
18197                new MountServiceInternal.ExternalStorageMountPolicy() {
18198            @Override
18199            public int getMountMode(int uid, String packageName) {
18200                if (Process.isIsolated(uid)) {
18201                    return Zygote.MOUNT_EXTERNAL_NONE;
18202                }
18203                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18204                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18205                }
18206                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18207                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18208                }
18209                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18210                    return Zygote.MOUNT_EXTERNAL_READ;
18211                }
18212                return Zygote.MOUNT_EXTERNAL_WRITE;
18213            }
18214
18215            @Override
18216            public boolean hasExternalStorage(int uid, String packageName) {
18217                return true;
18218            }
18219        });
18220
18221        // Now that we're mostly running, clean up stale users and apps
18222        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18223        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18224    }
18225
18226    @Override
18227    public boolean isSafeMode() {
18228        return mSafeMode;
18229    }
18230
18231    @Override
18232    public boolean hasSystemUidErrors() {
18233        return mHasSystemUidErrors;
18234    }
18235
18236    static String arrayToString(int[] array) {
18237        StringBuffer buf = new StringBuffer(128);
18238        buf.append('[');
18239        if (array != null) {
18240            for (int i=0; i<array.length; i++) {
18241                if (i > 0) buf.append(", ");
18242                buf.append(array[i]);
18243            }
18244        }
18245        buf.append(']');
18246        return buf.toString();
18247    }
18248
18249    static class DumpState {
18250        public static final int DUMP_LIBS = 1 << 0;
18251        public static final int DUMP_FEATURES = 1 << 1;
18252        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18253        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18254        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18255        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18256        public static final int DUMP_PERMISSIONS = 1 << 6;
18257        public static final int DUMP_PACKAGES = 1 << 7;
18258        public static final int DUMP_SHARED_USERS = 1 << 8;
18259        public static final int DUMP_MESSAGES = 1 << 9;
18260        public static final int DUMP_PROVIDERS = 1 << 10;
18261        public static final int DUMP_VERIFIERS = 1 << 11;
18262        public static final int DUMP_PREFERRED = 1 << 12;
18263        public static final int DUMP_PREFERRED_XML = 1 << 13;
18264        public static final int DUMP_KEYSETS = 1 << 14;
18265        public static final int DUMP_VERSION = 1 << 15;
18266        public static final int DUMP_INSTALLS = 1 << 16;
18267        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18268        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18269        public static final int DUMP_FROZEN = 1 << 19;
18270        public static final int DUMP_DEXOPT = 1 << 20;
18271        public static final int DUMP_COMPILER_STATS = 1 << 21;
18272
18273        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18274
18275        private int mTypes;
18276
18277        private int mOptions;
18278
18279        private boolean mTitlePrinted;
18280
18281        private SharedUserSetting mSharedUser;
18282
18283        public boolean isDumping(int type) {
18284            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18285                return true;
18286            }
18287
18288            return (mTypes & type) != 0;
18289        }
18290
18291        public void setDump(int type) {
18292            mTypes |= type;
18293        }
18294
18295        public boolean isOptionEnabled(int option) {
18296            return (mOptions & option) != 0;
18297        }
18298
18299        public void setOptionEnabled(int option) {
18300            mOptions |= option;
18301        }
18302
18303        public boolean onTitlePrinted() {
18304            final boolean printed = mTitlePrinted;
18305            mTitlePrinted = true;
18306            return printed;
18307        }
18308
18309        public boolean getTitlePrinted() {
18310            return mTitlePrinted;
18311        }
18312
18313        public void setTitlePrinted(boolean enabled) {
18314            mTitlePrinted = enabled;
18315        }
18316
18317        public SharedUserSetting getSharedUser() {
18318            return mSharedUser;
18319        }
18320
18321        public void setSharedUser(SharedUserSetting user) {
18322            mSharedUser = user;
18323        }
18324    }
18325
18326    @Override
18327    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18328            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18329        (new PackageManagerShellCommand(this)).exec(
18330                this, in, out, err, args, resultReceiver);
18331    }
18332
18333    @Override
18334    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18335        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18336                != PackageManager.PERMISSION_GRANTED) {
18337            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18338                    + Binder.getCallingPid()
18339                    + ", uid=" + Binder.getCallingUid()
18340                    + " without permission "
18341                    + android.Manifest.permission.DUMP);
18342            return;
18343        }
18344
18345        DumpState dumpState = new DumpState();
18346        boolean fullPreferred = false;
18347        boolean checkin = false;
18348
18349        String packageName = null;
18350        ArraySet<String> permissionNames = null;
18351
18352        int opti = 0;
18353        while (opti < args.length) {
18354            String opt = args[opti];
18355            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18356                break;
18357            }
18358            opti++;
18359
18360            if ("-a".equals(opt)) {
18361                // Right now we only know how to print all.
18362            } else if ("-h".equals(opt)) {
18363                pw.println("Package manager dump options:");
18364                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18365                pw.println("    --checkin: dump for a checkin");
18366                pw.println("    -f: print details of intent filters");
18367                pw.println("    -h: print this help");
18368                pw.println("  cmd may be one of:");
18369                pw.println("    l[ibraries]: list known shared libraries");
18370                pw.println("    f[eatures]: list device features");
18371                pw.println("    k[eysets]: print known keysets");
18372                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18373                pw.println("    perm[issions]: dump permissions");
18374                pw.println("    permission [name ...]: dump declaration and use of given permission");
18375                pw.println("    pref[erred]: print preferred package settings");
18376                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18377                pw.println("    prov[iders]: dump content providers");
18378                pw.println("    p[ackages]: dump installed packages");
18379                pw.println("    s[hared-users]: dump shared user IDs");
18380                pw.println("    m[essages]: print collected runtime messages");
18381                pw.println("    v[erifiers]: print package verifier info");
18382                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18383                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18384                pw.println("    version: print database version info");
18385                pw.println("    write: write current settings now");
18386                pw.println("    installs: details about install sessions");
18387                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18388                pw.println("    dexopt: dump dexopt state");
18389                pw.println("    compiler-stats: dump compiler statistics");
18390                pw.println("    <package.name>: info about given package");
18391                return;
18392            } else if ("--checkin".equals(opt)) {
18393                checkin = true;
18394            } else if ("-f".equals(opt)) {
18395                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18396            } else {
18397                pw.println("Unknown argument: " + opt + "; use -h for help");
18398            }
18399        }
18400
18401        // Is the caller requesting to dump a particular piece of data?
18402        if (opti < args.length) {
18403            String cmd = args[opti];
18404            opti++;
18405            // Is this a package name?
18406            if ("android".equals(cmd) || cmd.contains(".")) {
18407                packageName = cmd;
18408                // When dumping a single package, we always dump all of its
18409                // filter information since the amount of data will be reasonable.
18410                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18411            } else if ("check-permission".equals(cmd)) {
18412                if (opti >= args.length) {
18413                    pw.println("Error: check-permission missing permission argument");
18414                    return;
18415                }
18416                String perm = args[opti];
18417                opti++;
18418                if (opti >= args.length) {
18419                    pw.println("Error: check-permission missing package argument");
18420                    return;
18421                }
18422                String pkg = args[opti];
18423                opti++;
18424                int user = UserHandle.getUserId(Binder.getCallingUid());
18425                if (opti < args.length) {
18426                    try {
18427                        user = Integer.parseInt(args[opti]);
18428                    } catch (NumberFormatException e) {
18429                        pw.println("Error: check-permission user argument is not a number: "
18430                                + args[opti]);
18431                        return;
18432                    }
18433                }
18434                pw.println(checkPermission(perm, pkg, user));
18435                return;
18436            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18437                dumpState.setDump(DumpState.DUMP_LIBS);
18438            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18439                dumpState.setDump(DumpState.DUMP_FEATURES);
18440            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18441                if (opti >= args.length) {
18442                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18443                            | DumpState.DUMP_SERVICE_RESOLVERS
18444                            | DumpState.DUMP_RECEIVER_RESOLVERS
18445                            | DumpState.DUMP_CONTENT_RESOLVERS);
18446                } else {
18447                    while (opti < args.length) {
18448                        String name = args[opti];
18449                        if ("a".equals(name) || "activity".equals(name)) {
18450                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18451                        } else if ("s".equals(name) || "service".equals(name)) {
18452                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18453                        } else if ("r".equals(name) || "receiver".equals(name)) {
18454                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18455                        } else if ("c".equals(name) || "content".equals(name)) {
18456                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18457                        } else {
18458                            pw.println("Error: unknown resolver table type: " + name);
18459                            return;
18460                        }
18461                        opti++;
18462                    }
18463                }
18464            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18465                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18466            } else if ("permission".equals(cmd)) {
18467                if (opti >= args.length) {
18468                    pw.println("Error: permission requires permission name");
18469                    return;
18470                }
18471                permissionNames = new ArraySet<>();
18472                while (opti < args.length) {
18473                    permissionNames.add(args[opti]);
18474                    opti++;
18475                }
18476                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18477                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18478            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18479                dumpState.setDump(DumpState.DUMP_PREFERRED);
18480            } else if ("preferred-xml".equals(cmd)) {
18481                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18482                if (opti < args.length && "--full".equals(args[opti])) {
18483                    fullPreferred = true;
18484                    opti++;
18485                }
18486            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18487                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18488            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18489                dumpState.setDump(DumpState.DUMP_PACKAGES);
18490            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18491                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18492            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18493                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18494            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18495                dumpState.setDump(DumpState.DUMP_MESSAGES);
18496            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18497                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18498            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18499                    || "intent-filter-verifiers".equals(cmd)) {
18500                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18501            } else if ("version".equals(cmd)) {
18502                dumpState.setDump(DumpState.DUMP_VERSION);
18503            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18504                dumpState.setDump(DumpState.DUMP_KEYSETS);
18505            } else if ("installs".equals(cmd)) {
18506                dumpState.setDump(DumpState.DUMP_INSTALLS);
18507            } else if ("frozen".equals(cmd)) {
18508                dumpState.setDump(DumpState.DUMP_FROZEN);
18509            } else if ("dexopt".equals(cmd)) {
18510                dumpState.setDump(DumpState.DUMP_DEXOPT);
18511            } else if ("compiler-stats".equals(cmd)) {
18512                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18513            } else if ("write".equals(cmd)) {
18514                synchronized (mPackages) {
18515                    mSettings.writeLPr();
18516                    pw.println("Settings written.");
18517                    return;
18518                }
18519            }
18520        }
18521
18522        if (checkin) {
18523            pw.println("vers,1");
18524        }
18525
18526        // reader
18527        synchronized (mPackages) {
18528            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18529                if (!checkin) {
18530                    if (dumpState.onTitlePrinted())
18531                        pw.println();
18532                    pw.println("Database versions:");
18533                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18534                }
18535            }
18536
18537            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18538                if (!checkin) {
18539                    if (dumpState.onTitlePrinted())
18540                        pw.println();
18541                    pw.println("Verifiers:");
18542                    pw.print("  Required: ");
18543                    pw.print(mRequiredVerifierPackage);
18544                    pw.print(" (uid=");
18545                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18546                            UserHandle.USER_SYSTEM));
18547                    pw.println(")");
18548                } else if (mRequiredVerifierPackage != null) {
18549                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18550                    pw.print(",");
18551                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18552                            UserHandle.USER_SYSTEM));
18553                }
18554            }
18555
18556            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18557                    packageName == null) {
18558                if (mIntentFilterVerifierComponent != null) {
18559                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18560                    if (!checkin) {
18561                        if (dumpState.onTitlePrinted())
18562                            pw.println();
18563                        pw.println("Intent Filter Verifier:");
18564                        pw.print("  Using: ");
18565                        pw.print(verifierPackageName);
18566                        pw.print(" (uid=");
18567                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18568                                UserHandle.USER_SYSTEM));
18569                        pw.println(")");
18570                    } else if (verifierPackageName != null) {
18571                        pw.print("ifv,"); pw.print(verifierPackageName);
18572                        pw.print(",");
18573                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18574                                UserHandle.USER_SYSTEM));
18575                    }
18576                } else {
18577                    pw.println();
18578                    pw.println("No Intent Filter Verifier available!");
18579                }
18580            }
18581
18582            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18583                boolean printedHeader = false;
18584                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18585                while (it.hasNext()) {
18586                    String name = it.next();
18587                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18588                    if (!checkin) {
18589                        if (!printedHeader) {
18590                            if (dumpState.onTitlePrinted())
18591                                pw.println();
18592                            pw.println("Libraries:");
18593                            printedHeader = true;
18594                        }
18595                        pw.print("  ");
18596                    } else {
18597                        pw.print("lib,");
18598                    }
18599                    pw.print(name);
18600                    if (!checkin) {
18601                        pw.print(" -> ");
18602                    }
18603                    if (ent.path != null) {
18604                        if (!checkin) {
18605                            pw.print("(jar) ");
18606                            pw.print(ent.path);
18607                        } else {
18608                            pw.print(",jar,");
18609                            pw.print(ent.path);
18610                        }
18611                    } else {
18612                        if (!checkin) {
18613                            pw.print("(apk) ");
18614                            pw.print(ent.apk);
18615                        } else {
18616                            pw.print(",apk,");
18617                            pw.print(ent.apk);
18618                        }
18619                    }
18620                    pw.println();
18621                }
18622            }
18623
18624            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18625                if (dumpState.onTitlePrinted())
18626                    pw.println();
18627                if (!checkin) {
18628                    pw.println("Features:");
18629                }
18630
18631                for (FeatureInfo feat : mAvailableFeatures.values()) {
18632                    if (checkin) {
18633                        pw.print("feat,");
18634                        pw.print(feat.name);
18635                        pw.print(",");
18636                        pw.println(feat.version);
18637                    } else {
18638                        pw.print("  ");
18639                        pw.print(feat.name);
18640                        if (feat.version > 0) {
18641                            pw.print(" version=");
18642                            pw.print(feat.version);
18643                        }
18644                        pw.println();
18645                    }
18646                }
18647            }
18648
18649            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18650                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18651                        : "Activity Resolver Table:", "  ", packageName,
18652                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18653                    dumpState.setTitlePrinted(true);
18654                }
18655            }
18656            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18657                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18658                        : "Receiver Resolver Table:", "  ", packageName,
18659                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18660                    dumpState.setTitlePrinted(true);
18661                }
18662            }
18663            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18664                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18665                        : "Service Resolver Table:", "  ", packageName,
18666                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18667                    dumpState.setTitlePrinted(true);
18668                }
18669            }
18670            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18671                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18672                        : "Provider Resolver Table:", "  ", packageName,
18673                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18674                    dumpState.setTitlePrinted(true);
18675                }
18676            }
18677
18678            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18679                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18680                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18681                    int user = mSettings.mPreferredActivities.keyAt(i);
18682                    if (pir.dump(pw,
18683                            dumpState.getTitlePrinted()
18684                                ? "\nPreferred Activities User " + user + ":"
18685                                : "Preferred Activities User " + user + ":", "  ",
18686                            packageName, true, false)) {
18687                        dumpState.setTitlePrinted(true);
18688                    }
18689                }
18690            }
18691
18692            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18693                pw.flush();
18694                FileOutputStream fout = new FileOutputStream(fd);
18695                BufferedOutputStream str = new BufferedOutputStream(fout);
18696                XmlSerializer serializer = new FastXmlSerializer();
18697                try {
18698                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18699                    serializer.startDocument(null, true);
18700                    serializer.setFeature(
18701                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18702                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18703                    serializer.endDocument();
18704                    serializer.flush();
18705                } catch (IllegalArgumentException e) {
18706                    pw.println("Failed writing: " + e);
18707                } catch (IllegalStateException e) {
18708                    pw.println("Failed writing: " + e);
18709                } catch (IOException e) {
18710                    pw.println("Failed writing: " + e);
18711                }
18712            }
18713
18714            if (!checkin
18715                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18716                    && packageName == null) {
18717                pw.println();
18718                int count = mSettings.mPackages.size();
18719                if (count == 0) {
18720                    pw.println("No applications!");
18721                    pw.println();
18722                } else {
18723                    final String prefix = "  ";
18724                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18725                    if (allPackageSettings.size() == 0) {
18726                        pw.println("No domain preferred apps!");
18727                        pw.println();
18728                    } else {
18729                        pw.println("App verification status:");
18730                        pw.println();
18731                        count = 0;
18732                        for (PackageSetting ps : allPackageSettings) {
18733                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18734                            if (ivi == null || ivi.getPackageName() == null) continue;
18735                            pw.println(prefix + "Package: " + ivi.getPackageName());
18736                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18737                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18738                            pw.println();
18739                            count++;
18740                        }
18741                        if (count == 0) {
18742                            pw.println(prefix + "No app verification established.");
18743                            pw.println();
18744                        }
18745                        for (int userId : sUserManager.getUserIds()) {
18746                            pw.println("App linkages for user " + userId + ":");
18747                            pw.println();
18748                            count = 0;
18749                            for (PackageSetting ps : allPackageSettings) {
18750                                final long status = ps.getDomainVerificationStatusForUser(userId);
18751                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18752                                    continue;
18753                                }
18754                                pw.println(prefix + "Package: " + ps.name);
18755                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18756                                String statusStr = IntentFilterVerificationInfo.
18757                                        getStatusStringFromValue(status);
18758                                pw.println(prefix + "Status:  " + statusStr);
18759                                pw.println();
18760                                count++;
18761                            }
18762                            if (count == 0) {
18763                                pw.println(prefix + "No configured app linkages.");
18764                                pw.println();
18765                            }
18766                        }
18767                    }
18768                }
18769            }
18770
18771            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18772                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18773                if (packageName == null && permissionNames == null) {
18774                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18775                        if (iperm == 0) {
18776                            if (dumpState.onTitlePrinted())
18777                                pw.println();
18778                            pw.println("AppOp Permissions:");
18779                        }
18780                        pw.print("  AppOp Permission ");
18781                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18782                        pw.println(":");
18783                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18784                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18785                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18786                        }
18787                    }
18788                }
18789            }
18790
18791            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18792                boolean printedSomething = false;
18793                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18794                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18795                        continue;
18796                    }
18797                    if (!printedSomething) {
18798                        if (dumpState.onTitlePrinted())
18799                            pw.println();
18800                        pw.println("Registered ContentProviders:");
18801                        printedSomething = true;
18802                    }
18803                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18804                    pw.print("    "); pw.println(p.toString());
18805                }
18806                printedSomething = false;
18807                for (Map.Entry<String, PackageParser.Provider> entry :
18808                        mProvidersByAuthority.entrySet()) {
18809                    PackageParser.Provider p = entry.getValue();
18810                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18811                        continue;
18812                    }
18813                    if (!printedSomething) {
18814                        if (dumpState.onTitlePrinted())
18815                            pw.println();
18816                        pw.println("ContentProvider Authorities:");
18817                        printedSomething = true;
18818                    }
18819                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18820                    pw.print("    "); pw.println(p.toString());
18821                    if (p.info != null && p.info.applicationInfo != null) {
18822                        final String appInfo = p.info.applicationInfo.toString();
18823                        pw.print("      applicationInfo="); pw.println(appInfo);
18824                    }
18825                }
18826            }
18827
18828            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18829                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18830            }
18831
18832            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18833                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18834            }
18835
18836            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18837                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18838            }
18839
18840            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18841                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18842            }
18843
18844            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18845                // XXX should handle packageName != null by dumping only install data that
18846                // the given package is involved with.
18847                if (dumpState.onTitlePrinted()) pw.println();
18848                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18849            }
18850
18851            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18852                // XXX should handle packageName != null by dumping only install data that
18853                // the given package is involved with.
18854                if (dumpState.onTitlePrinted()) pw.println();
18855
18856                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18857                ipw.println();
18858                ipw.println("Frozen packages:");
18859                ipw.increaseIndent();
18860                if (mFrozenPackages.size() == 0) {
18861                    ipw.println("(none)");
18862                } else {
18863                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18864                        ipw.println(mFrozenPackages.valueAt(i));
18865                    }
18866                }
18867                ipw.decreaseIndent();
18868            }
18869
18870            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18871                if (dumpState.onTitlePrinted()) pw.println();
18872                dumpDexoptStateLPr(pw, packageName);
18873            }
18874
18875            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
18876                if (dumpState.onTitlePrinted()) pw.println();
18877                dumpCompilerStatsLPr(pw, packageName);
18878            }
18879
18880            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18881                if (dumpState.onTitlePrinted()) pw.println();
18882                mSettings.dumpReadMessagesLPr(pw, dumpState);
18883
18884                pw.println();
18885                pw.println("Package warning messages:");
18886                BufferedReader in = null;
18887                String line = null;
18888                try {
18889                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18890                    while ((line = in.readLine()) != null) {
18891                        if (line.contains("ignored: updated version")) continue;
18892                        pw.println(line);
18893                    }
18894                } catch (IOException ignored) {
18895                } finally {
18896                    IoUtils.closeQuietly(in);
18897                }
18898            }
18899
18900            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18901                BufferedReader in = null;
18902                String line = null;
18903                try {
18904                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18905                    while ((line = in.readLine()) != null) {
18906                        if (line.contains("ignored: updated version")) continue;
18907                        pw.print("msg,");
18908                        pw.println(line);
18909                    }
18910                } catch (IOException ignored) {
18911                } finally {
18912                    IoUtils.closeQuietly(in);
18913                }
18914            }
18915        }
18916    }
18917
18918    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18919        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18920        ipw.println();
18921        ipw.println("Dexopt state:");
18922        ipw.increaseIndent();
18923        Collection<PackageParser.Package> packages = null;
18924        if (packageName != null) {
18925            PackageParser.Package targetPackage = mPackages.get(packageName);
18926            if (targetPackage != null) {
18927                packages = Collections.singletonList(targetPackage);
18928            } else {
18929                ipw.println("Unable to find package: " + packageName);
18930                return;
18931            }
18932        } else {
18933            packages = mPackages.values();
18934        }
18935
18936        for (PackageParser.Package pkg : packages) {
18937            ipw.println("[" + pkg.packageName + "]");
18938            ipw.increaseIndent();
18939            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18940            ipw.decreaseIndent();
18941        }
18942    }
18943
18944    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
18945        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18946        ipw.println();
18947        ipw.println("Compiler stats:");
18948        ipw.increaseIndent();
18949        Collection<PackageParser.Package> packages = null;
18950        if (packageName != null) {
18951            PackageParser.Package targetPackage = mPackages.get(packageName);
18952            if (targetPackage != null) {
18953                packages = Collections.singletonList(targetPackage);
18954            } else {
18955                ipw.println("Unable to find package: " + packageName);
18956                return;
18957            }
18958        } else {
18959            packages = mPackages.values();
18960        }
18961
18962        for (PackageParser.Package pkg : packages) {
18963            ipw.println("[" + pkg.packageName + "]");
18964            ipw.increaseIndent();
18965
18966            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
18967            if (stats == null) {
18968                ipw.println("(No recorded stats)");
18969            } else {
18970                stats.dump(ipw);
18971            }
18972            ipw.decreaseIndent();
18973        }
18974    }
18975
18976    private String dumpDomainString(String packageName) {
18977        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18978                .getList();
18979        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18980
18981        ArraySet<String> result = new ArraySet<>();
18982        if (iviList.size() > 0) {
18983            for (IntentFilterVerificationInfo ivi : iviList) {
18984                for (String host : ivi.getDomains()) {
18985                    result.add(host);
18986                }
18987            }
18988        }
18989        if (filters != null && filters.size() > 0) {
18990            for (IntentFilter filter : filters) {
18991                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18992                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18993                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18994                    result.addAll(filter.getHostsList());
18995                }
18996            }
18997        }
18998
18999        StringBuilder sb = new StringBuilder(result.size() * 16);
19000        for (String domain : result) {
19001            if (sb.length() > 0) sb.append(" ");
19002            sb.append(domain);
19003        }
19004        return sb.toString();
19005    }
19006
19007    // ------- apps on sdcard specific code -------
19008    static final boolean DEBUG_SD_INSTALL = false;
19009
19010    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19011
19012    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19013
19014    private boolean mMediaMounted = false;
19015
19016    static String getEncryptKey() {
19017        try {
19018            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19019                    SD_ENCRYPTION_KEYSTORE_NAME);
19020            if (sdEncKey == null) {
19021                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19022                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19023                if (sdEncKey == null) {
19024                    Slog.e(TAG, "Failed to create encryption keys");
19025                    return null;
19026                }
19027            }
19028            return sdEncKey;
19029        } catch (NoSuchAlgorithmException nsae) {
19030            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19031            return null;
19032        } catch (IOException ioe) {
19033            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19034            return null;
19035        }
19036    }
19037
19038    /*
19039     * Update media status on PackageManager.
19040     */
19041    @Override
19042    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19043        int callingUid = Binder.getCallingUid();
19044        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19045            throw new SecurityException("Media status can only be updated by the system");
19046        }
19047        // reader; this apparently protects mMediaMounted, but should probably
19048        // be a different lock in that case.
19049        synchronized (mPackages) {
19050            Log.i(TAG, "Updating external media status from "
19051                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19052                    + (mediaStatus ? "mounted" : "unmounted"));
19053            if (DEBUG_SD_INSTALL)
19054                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19055                        + ", mMediaMounted=" + mMediaMounted);
19056            if (mediaStatus == mMediaMounted) {
19057                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19058                        : 0, -1);
19059                mHandler.sendMessage(msg);
19060                return;
19061            }
19062            mMediaMounted = mediaStatus;
19063        }
19064        // Queue up an async operation since the package installation may take a
19065        // little while.
19066        mHandler.post(new Runnable() {
19067            public void run() {
19068                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19069            }
19070        });
19071    }
19072
19073    /**
19074     * Called by MountService when the initial ASECs to scan are available.
19075     * Should block until all the ASEC containers are finished being scanned.
19076     */
19077    public void scanAvailableAsecs() {
19078        updateExternalMediaStatusInner(true, false, false);
19079    }
19080
19081    /*
19082     * Collect information of applications on external media, map them against
19083     * existing containers and update information based on current mount status.
19084     * Please note that we always have to report status if reportStatus has been
19085     * set to true especially when unloading packages.
19086     */
19087    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19088            boolean externalStorage) {
19089        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19090        int[] uidArr = EmptyArray.INT;
19091
19092        final String[] list = PackageHelper.getSecureContainerList();
19093        if (ArrayUtils.isEmpty(list)) {
19094            Log.i(TAG, "No secure containers found");
19095        } else {
19096            // Process list of secure containers and categorize them
19097            // as active or stale based on their package internal state.
19098
19099            // reader
19100            synchronized (mPackages) {
19101                for (String cid : list) {
19102                    // Leave stages untouched for now; installer service owns them
19103                    if (PackageInstallerService.isStageName(cid)) continue;
19104
19105                    if (DEBUG_SD_INSTALL)
19106                        Log.i(TAG, "Processing container " + cid);
19107                    String pkgName = getAsecPackageName(cid);
19108                    if (pkgName == null) {
19109                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19110                        continue;
19111                    }
19112                    if (DEBUG_SD_INSTALL)
19113                        Log.i(TAG, "Looking for pkg : " + pkgName);
19114
19115                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19116                    if (ps == null) {
19117                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19118                        continue;
19119                    }
19120
19121                    /*
19122                     * Skip packages that are not external if we're unmounting
19123                     * external storage.
19124                     */
19125                    if (externalStorage && !isMounted && !isExternal(ps)) {
19126                        continue;
19127                    }
19128
19129                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19130                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19131                    // The package status is changed only if the code path
19132                    // matches between settings and the container id.
19133                    if (ps.codePathString != null
19134                            && ps.codePathString.startsWith(args.getCodePath())) {
19135                        if (DEBUG_SD_INSTALL) {
19136                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19137                                    + " at code path: " + ps.codePathString);
19138                        }
19139
19140                        // We do have a valid package installed on sdcard
19141                        processCids.put(args, ps.codePathString);
19142                        final int uid = ps.appId;
19143                        if (uid != -1) {
19144                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19145                        }
19146                    } else {
19147                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19148                                + ps.codePathString);
19149                    }
19150                }
19151            }
19152
19153            Arrays.sort(uidArr);
19154        }
19155
19156        // Process packages with valid entries.
19157        if (isMounted) {
19158            if (DEBUG_SD_INSTALL)
19159                Log.i(TAG, "Loading packages");
19160            loadMediaPackages(processCids, uidArr, externalStorage);
19161            startCleaningPackages();
19162            mInstallerService.onSecureContainersAvailable();
19163        } else {
19164            if (DEBUG_SD_INSTALL)
19165                Log.i(TAG, "Unloading packages");
19166            unloadMediaPackages(processCids, uidArr, reportStatus);
19167        }
19168    }
19169
19170    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19171            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19172        final int size = infos.size();
19173        final String[] packageNames = new String[size];
19174        final int[] packageUids = new int[size];
19175        for (int i = 0; i < size; i++) {
19176            final ApplicationInfo info = infos.get(i);
19177            packageNames[i] = info.packageName;
19178            packageUids[i] = info.uid;
19179        }
19180        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19181                finishedReceiver);
19182    }
19183
19184    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19185            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19186        sendResourcesChangedBroadcast(mediaStatus, replacing,
19187                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19188    }
19189
19190    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19191            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19192        int size = pkgList.length;
19193        if (size > 0) {
19194            // Send broadcasts here
19195            Bundle extras = new Bundle();
19196            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19197            if (uidArr != null) {
19198                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19199            }
19200            if (replacing) {
19201                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19202            }
19203            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19204                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19205            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19206        }
19207    }
19208
19209   /*
19210     * Look at potentially valid container ids from processCids If package
19211     * information doesn't match the one on record or package scanning fails,
19212     * the cid is added to list of removeCids. We currently don't delete stale
19213     * containers.
19214     */
19215    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19216            boolean externalStorage) {
19217        ArrayList<String> pkgList = new ArrayList<String>();
19218        Set<AsecInstallArgs> keys = processCids.keySet();
19219
19220        for (AsecInstallArgs args : keys) {
19221            String codePath = processCids.get(args);
19222            if (DEBUG_SD_INSTALL)
19223                Log.i(TAG, "Loading container : " + args.cid);
19224            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19225            try {
19226                // Make sure there are no container errors first.
19227                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19228                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19229                            + " when installing from sdcard");
19230                    continue;
19231                }
19232                // Check code path here.
19233                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19234                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19235                            + " does not match one in settings " + codePath);
19236                    continue;
19237                }
19238                // Parse package
19239                int parseFlags = mDefParseFlags;
19240                if (args.isExternalAsec()) {
19241                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19242                }
19243                if (args.isFwdLocked()) {
19244                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19245                }
19246
19247                synchronized (mInstallLock) {
19248                    PackageParser.Package pkg = null;
19249                    try {
19250                        // Sadly we don't know the package name yet to freeze it
19251                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19252                                SCAN_IGNORE_FROZEN, 0, null);
19253                    } catch (PackageManagerException e) {
19254                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19255                    }
19256                    // Scan the package
19257                    if (pkg != null) {
19258                        /*
19259                         * TODO why is the lock being held? doPostInstall is
19260                         * called in other places without the lock. This needs
19261                         * to be straightened out.
19262                         */
19263                        // writer
19264                        synchronized (mPackages) {
19265                            retCode = PackageManager.INSTALL_SUCCEEDED;
19266                            pkgList.add(pkg.packageName);
19267                            // Post process args
19268                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19269                                    pkg.applicationInfo.uid);
19270                        }
19271                    } else {
19272                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19273                    }
19274                }
19275
19276            } finally {
19277                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19278                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19279                }
19280            }
19281        }
19282        // writer
19283        synchronized (mPackages) {
19284            // If the platform SDK has changed since the last time we booted,
19285            // we need to re-grant app permission to catch any new ones that
19286            // appear. This is really a hack, and means that apps can in some
19287            // cases get permissions that the user didn't initially explicitly
19288            // allow... it would be nice to have some better way to handle
19289            // this situation.
19290            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19291                    : mSettings.getInternalVersion();
19292            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19293                    : StorageManager.UUID_PRIVATE_INTERNAL;
19294
19295            int updateFlags = UPDATE_PERMISSIONS_ALL;
19296            if (ver.sdkVersion != mSdkVersion) {
19297                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19298                        + mSdkVersion + "; regranting permissions for external");
19299                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19300            }
19301            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19302
19303            // Yay, everything is now upgraded
19304            ver.forceCurrent();
19305
19306            // can downgrade to reader
19307            // Persist settings
19308            mSettings.writeLPr();
19309        }
19310        // Send a broadcast to let everyone know we are done processing
19311        if (pkgList.size() > 0) {
19312            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19313        }
19314    }
19315
19316   /*
19317     * Utility method to unload a list of specified containers
19318     */
19319    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19320        // Just unmount all valid containers.
19321        for (AsecInstallArgs arg : cidArgs) {
19322            synchronized (mInstallLock) {
19323                arg.doPostDeleteLI(false);
19324           }
19325       }
19326   }
19327
19328    /*
19329     * Unload packages mounted on external media. This involves deleting package
19330     * data from internal structures, sending broadcasts about disabled packages,
19331     * gc'ing to free up references, unmounting all secure containers
19332     * corresponding to packages on external media, and posting a
19333     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19334     * that we always have to post this message if status has been requested no
19335     * matter what.
19336     */
19337    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19338            final boolean reportStatus) {
19339        if (DEBUG_SD_INSTALL)
19340            Log.i(TAG, "unloading media packages");
19341        ArrayList<String> pkgList = new ArrayList<String>();
19342        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19343        final Set<AsecInstallArgs> keys = processCids.keySet();
19344        for (AsecInstallArgs args : keys) {
19345            String pkgName = args.getPackageName();
19346            if (DEBUG_SD_INSTALL)
19347                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19348            // Delete package internally
19349            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19350            synchronized (mInstallLock) {
19351                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19352                final boolean res;
19353                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19354                        "unloadMediaPackages")) {
19355                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19356                            null);
19357                }
19358                if (res) {
19359                    pkgList.add(pkgName);
19360                } else {
19361                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19362                    failedList.add(args);
19363                }
19364            }
19365        }
19366
19367        // reader
19368        synchronized (mPackages) {
19369            // We didn't update the settings after removing each package;
19370            // write them now for all packages.
19371            mSettings.writeLPr();
19372        }
19373
19374        // We have to absolutely send UPDATED_MEDIA_STATUS only
19375        // after confirming that all the receivers processed the ordered
19376        // broadcast when packages get disabled, force a gc to clean things up.
19377        // and unload all the containers.
19378        if (pkgList.size() > 0) {
19379            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19380                    new IIntentReceiver.Stub() {
19381                public void performReceive(Intent intent, int resultCode, String data,
19382                        Bundle extras, boolean ordered, boolean sticky,
19383                        int sendingUser) throws RemoteException {
19384                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19385                            reportStatus ? 1 : 0, 1, keys);
19386                    mHandler.sendMessage(msg);
19387                }
19388            });
19389        } else {
19390            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19391                    keys);
19392            mHandler.sendMessage(msg);
19393        }
19394    }
19395
19396    private void loadPrivatePackages(final VolumeInfo vol) {
19397        mHandler.post(new Runnable() {
19398            @Override
19399            public void run() {
19400                loadPrivatePackagesInner(vol);
19401            }
19402        });
19403    }
19404
19405    private void loadPrivatePackagesInner(VolumeInfo vol) {
19406        final String volumeUuid = vol.fsUuid;
19407        if (TextUtils.isEmpty(volumeUuid)) {
19408            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19409            return;
19410        }
19411
19412        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19413        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19414        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19415
19416        final VersionInfo ver;
19417        final List<PackageSetting> packages;
19418        synchronized (mPackages) {
19419            ver = mSettings.findOrCreateVersion(volumeUuid);
19420            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19421        }
19422
19423        for (PackageSetting ps : packages) {
19424            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19425            synchronized (mInstallLock) {
19426                final PackageParser.Package pkg;
19427                try {
19428                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19429                    loaded.add(pkg.applicationInfo);
19430
19431                } catch (PackageManagerException e) {
19432                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19433                }
19434
19435                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19436                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19437                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19438                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19439                }
19440            }
19441        }
19442
19443        // Reconcile app data for all started/unlocked users
19444        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19445        final UserManager um = mContext.getSystemService(UserManager.class);
19446        UserManagerInternal umInternal = getUserManagerInternal();
19447        for (UserInfo user : um.getUsers()) {
19448            final int flags;
19449            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19450                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19451            } else if (umInternal.isUserRunning(user.id)) {
19452                flags = StorageManager.FLAG_STORAGE_DE;
19453            } else {
19454                continue;
19455            }
19456
19457            try {
19458                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19459                synchronized (mInstallLock) {
19460                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
19461                }
19462            } catch (IllegalStateException e) {
19463                // Device was probably ejected, and we'll process that event momentarily
19464                Slog.w(TAG, "Failed to prepare storage: " + e);
19465            }
19466        }
19467
19468        synchronized (mPackages) {
19469            int updateFlags = UPDATE_PERMISSIONS_ALL;
19470            if (ver.sdkVersion != mSdkVersion) {
19471                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19472                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19473                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19474            }
19475            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19476
19477            // Yay, everything is now upgraded
19478            ver.forceCurrent();
19479
19480            mSettings.writeLPr();
19481        }
19482
19483        for (PackageFreezer freezer : freezers) {
19484            freezer.close();
19485        }
19486
19487        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19488        sendResourcesChangedBroadcast(true, false, loaded, null);
19489    }
19490
19491    private void unloadPrivatePackages(final VolumeInfo vol) {
19492        mHandler.post(new Runnable() {
19493            @Override
19494            public void run() {
19495                unloadPrivatePackagesInner(vol);
19496            }
19497        });
19498    }
19499
19500    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19501        final String volumeUuid = vol.fsUuid;
19502        if (TextUtils.isEmpty(volumeUuid)) {
19503            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19504            return;
19505        }
19506
19507        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19508        synchronized (mInstallLock) {
19509        synchronized (mPackages) {
19510            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19511            for (PackageSetting ps : packages) {
19512                if (ps.pkg == null) continue;
19513
19514                final ApplicationInfo info = ps.pkg.applicationInfo;
19515                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19516                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19517
19518                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19519                        "unloadPrivatePackagesInner")) {
19520                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19521                            false, null)) {
19522                        unloaded.add(info);
19523                    } else {
19524                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19525                    }
19526                }
19527
19528                // Try very hard to release any references to this package
19529                // so we don't risk the system server being killed due to
19530                // open FDs
19531                AttributeCache.instance().removePackage(ps.name);
19532            }
19533
19534            mSettings.writeLPr();
19535        }
19536        }
19537
19538        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19539        sendResourcesChangedBroadcast(false, false, unloaded, null);
19540
19541        // Try very hard to release any references to this path so we don't risk
19542        // the system server being killed due to open FDs
19543        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19544
19545        for (int i = 0; i < 3; i++) {
19546            System.gc();
19547            System.runFinalization();
19548        }
19549    }
19550
19551    /**
19552     * Prepare storage areas for given user on all mounted devices.
19553     */
19554    void prepareUserData(int userId, int userSerial, int flags) {
19555        synchronized (mInstallLock) {
19556            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19557            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19558                final String volumeUuid = vol.getFsUuid();
19559                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19560            }
19561        }
19562    }
19563
19564    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19565            boolean allowRecover) {
19566        // Prepare storage and verify that serial numbers are consistent; if
19567        // there's a mismatch we need to destroy to avoid leaking data
19568        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19569        try {
19570            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19571
19572            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19573                UserManagerService.enforceSerialNumber(
19574                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19575                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19576                    UserManagerService.enforceSerialNumber(
19577                            Environment.getDataSystemDeDirectory(userId), userSerial);
19578                }
19579            }
19580            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19581                UserManagerService.enforceSerialNumber(
19582                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19583                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19584                    UserManagerService.enforceSerialNumber(
19585                            Environment.getDataSystemCeDirectory(userId), userSerial);
19586                }
19587            }
19588
19589            synchronized (mInstallLock) {
19590                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19591            }
19592        } catch (Exception e) {
19593            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19594                    + " because we failed to prepare: " + e);
19595            destroyUserDataLI(volumeUuid, userId,
19596                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19597
19598            if (allowRecover) {
19599                // Try one last time; if we fail again we're really in trouble
19600                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19601            }
19602        }
19603    }
19604
19605    /**
19606     * Destroy storage areas for given user on all mounted devices.
19607     */
19608    void destroyUserData(int userId, int flags) {
19609        synchronized (mInstallLock) {
19610            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19611            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19612                final String volumeUuid = vol.getFsUuid();
19613                destroyUserDataLI(volumeUuid, userId, flags);
19614            }
19615        }
19616    }
19617
19618    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19619        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19620        try {
19621            // Clean up app data, profile data, and media data
19622            mInstaller.destroyUserData(volumeUuid, userId, flags);
19623
19624            // Clean up system data
19625            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19626                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19627                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19628                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19629                }
19630                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19631                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19632                }
19633            }
19634
19635            // Data with special labels is now gone, so finish the job
19636            storage.destroyUserStorage(volumeUuid, userId, flags);
19637
19638        } catch (Exception e) {
19639            logCriticalInfo(Log.WARN,
19640                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19641        }
19642    }
19643
19644    /**
19645     * Examine all users present on given mounted volume, and destroy data
19646     * belonging to users that are no longer valid, or whose user ID has been
19647     * recycled.
19648     */
19649    private void reconcileUsers(String volumeUuid) {
19650        final List<File> files = new ArrayList<>();
19651        Collections.addAll(files, FileUtils
19652                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19653        Collections.addAll(files, FileUtils
19654                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19655        Collections.addAll(files, FileUtils
19656                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19657        Collections.addAll(files, FileUtils
19658                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19659        for (File file : files) {
19660            if (!file.isDirectory()) continue;
19661
19662            final int userId;
19663            final UserInfo info;
19664            try {
19665                userId = Integer.parseInt(file.getName());
19666                info = sUserManager.getUserInfo(userId);
19667            } catch (NumberFormatException e) {
19668                Slog.w(TAG, "Invalid user directory " + file);
19669                continue;
19670            }
19671
19672            boolean destroyUser = false;
19673            if (info == null) {
19674                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19675                        + " because no matching user was found");
19676                destroyUser = true;
19677            } else if (!mOnlyCore) {
19678                try {
19679                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19680                } catch (IOException e) {
19681                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19682                            + " because we failed to enforce serial number: " + e);
19683                    destroyUser = true;
19684                }
19685            }
19686
19687            if (destroyUser) {
19688                synchronized (mInstallLock) {
19689                    destroyUserDataLI(volumeUuid, userId,
19690                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19691                }
19692            }
19693        }
19694    }
19695
19696    private void assertPackageKnown(String volumeUuid, String packageName)
19697            throws PackageManagerException {
19698        synchronized (mPackages) {
19699            final PackageSetting ps = mSettings.mPackages.get(packageName);
19700            if (ps == null) {
19701                throw new PackageManagerException("Package " + packageName + " is unknown");
19702            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19703                throw new PackageManagerException(
19704                        "Package " + packageName + " found on unknown volume " + volumeUuid
19705                                + "; expected volume " + ps.volumeUuid);
19706            }
19707        }
19708    }
19709
19710    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19711            throws PackageManagerException {
19712        synchronized (mPackages) {
19713            final PackageSetting ps = mSettings.mPackages.get(packageName);
19714            if (ps == null) {
19715                throw new PackageManagerException("Package " + packageName + " is unknown");
19716            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19717                throw new PackageManagerException(
19718                        "Package " + packageName + " found on unknown volume " + volumeUuid
19719                                + "; expected volume " + ps.volumeUuid);
19720            } else if (!ps.getInstalled(userId)) {
19721                throw new PackageManagerException(
19722                        "Package " + packageName + " not installed for user " + userId);
19723            }
19724        }
19725    }
19726
19727    /**
19728     * Examine all apps present on given mounted volume, and destroy apps that
19729     * aren't expected, either due to uninstallation or reinstallation on
19730     * another volume.
19731     */
19732    private void reconcileApps(String volumeUuid) {
19733        final File[] files = FileUtils
19734                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19735        for (File file : files) {
19736            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19737                    && !PackageInstallerService.isStageName(file.getName());
19738            if (!isPackage) {
19739                // Ignore entries which are not packages
19740                continue;
19741            }
19742
19743            try {
19744                final PackageLite pkg = PackageParser.parsePackageLite(file,
19745                        PackageParser.PARSE_MUST_BE_APK);
19746                assertPackageKnown(volumeUuid, pkg.packageName);
19747
19748            } catch (PackageParserException | PackageManagerException e) {
19749                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19750                synchronized (mInstallLock) {
19751                    removeCodePathLI(file);
19752                }
19753            }
19754        }
19755    }
19756
19757    /**
19758     * Reconcile all app data for the given user.
19759     * <p>
19760     * Verifies that directories exist and that ownership and labeling is
19761     * correct for all installed apps on all mounted volumes.
19762     */
19763    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
19764        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19765        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19766            final String volumeUuid = vol.getFsUuid();
19767            synchronized (mInstallLock) {
19768                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
19769            }
19770        }
19771    }
19772
19773    /**
19774     * Reconcile all app data on given mounted volume.
19775     * <p>
19776     * Destroys app data that isn't expected, either due to uninstallation or
19777     * reinstallation on another volume.
19778     * <p>
19779     * Verifies that directories exist and that ownership and labeling is
19780     * correct for all installed apps.
19781     */
19782    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
19783            boolean migrateAppData) {
19784        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19785                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
19786
19787        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19788        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19789
19790        boolean restoreconNeeded = false;
19791
19792        // First look for stale data that doesn't belong, and check if things
19793        // have changed since we did our last restorecon
19794        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19795            if (StorageManager.isFileEncryptedNativeOrEmulated()
19796                    && !StorageManager.isUserKeyUnlocked(userId)) {
19797                throw new RuntimeException(
19798                        "Yikes, someone asked us to reconcile CE storage while " + userId
19799                                + " was still locked; this would have caused massive data loss!");
19800            }
19801
19802            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19803
19804            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19805            for (File file : files) {
19806                final String packageName = file.getName();
19807                try {
19808                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19809                } catch (PackageManagerException e) {
19810                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19811                    try {
19812                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19813                                StorageManager.FLAG_STORAGE_CE, 0);
19814                    } catch (InstallerException e2) {
19815                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19816                    }
19817                }
19818            }
19819        }
19820        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19821            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19822
19823            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19824            for (File file : files) {
19825                final String packageName = file.getName();
19826                try {
19827                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19828                } catch (PackageManagerException e) {
19829                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19830                    try {
19831                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19832                                StorageManager.FLAG_STORAGE_DE, 0);
19833                    } catch (InstallerException e2) {
19834                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19835                    }
19836                }
19837            }
19838        }
19839
19840        // Ensure that data directories are ready to roll for all packages
19841        // installed for this volume and user
19842        final List<PackageSetting> packages;
19843        synchronized (mPackages) {
19844            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19845        }
19846        int preparedCount = 0;
19847        for (PackageSetting ps : packages) {
19848            final String packageName = ps.name;
19849            if (ps.pkg == null) {
19850                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19851                // TODO: might be due to legacy ASEC apps; we should circle back
19852                // and reconcile again once they're scanned
19853                continue;
19854            }
19855
19856            if (ps.getInstalled(userId)) {
19857                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19858
19859                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
19860                    // We may have just shuffled around app data directories, so
19861                    // prepare them one more time
19862                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19863                }
19864
19865                preparedCount++;
19866            }
19867        }
19868
19869        if (restoreconNeeded) {
19870            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19871                SELinuxMMAC.setRestoreconDone(ceDir);
19872            }
19873            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19874                SELinuxMMAC.setRestoreconDone(deDir);
19875            }
19876        }
19877
19878        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19879                + " packages; restoreconNeeded was " + restoreconNeeded);
19880    }
19881
19882    /**
19883     * Prepare app data for the given app just after it was installed or
19884     * upgraded. This method carefully only touches users that it's installed
19885     * for, and it forces a restorecon to handle any seinfo changes.
19886     * <p>
19887     * Verifies that directories exist and that ownership and labeling is
19888     * correct for all installed apps. If there is an ownership mismatch, it
19889     * will try recovering system apps by wiping data; third-party app data is
19890     * left intact.
19891     * <p>
19892     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19893     */
19894    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19895        final PackageSetting ps;
19896        synchronized (mPackages) {
19897            ps = mSettings.mPackages.get(pkg.packageName);
19898            mSettings.writeKernelMappingLPr(ps);
19899        }
19900
19901        final UserManager um = mContext.getSystemService(UserManager.class);
19902        UserManagerInternal umInternal = getUserManagerInternal();
19903        for (UserInfo user : um.getUsers()) {
19904            final int flags;
19905            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19906                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19907            } else if (umInternal.isUserRunning(user.id)) {
19908                flags = StorageManager.FLAG_STORAGE_DE;
19909            } else {
19910                continue;
19911            }
19912
19913            if (ps.getInstalled(user.id)) {
19914                // Whenever an app changes, force a restorecon of its data
19915                // TODO: when user data is locked, mark that we're still dirty
19916                prepareAppDataLIF(pkg, user.id, flags, true);
19917            }
19918        }
19919    }
19920
19921    /**
19922     * Prepare app data for the given app.
19923     * <p>
19924     * Verifies that directories exist and that ownership and labeling is
19925     * correct for all installed apps. If there is an ownership mismatch, this
19926     * will try recovering system apps by wiping data; third-party app data is
19927     * left intact.
19928     */
19929    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19930            boolean restoreconNeeded) {
19931        if (pkg == null) {
19932            Slog.wtf(TAG, "Package was null!", new Throwable());
19933            return;
19934        }
19935        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19936        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19937        for (int i = 0; i < childCount; i++) {
19938            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19939        }
19940    }
19941
19942    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19943            boolean restoreconNeeded) {
19944        if (DEBUG_APP_DATA) {
19945            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19946                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19947        }
19948
19949        final String volumeUuid = pkg.volumeUuid;
19950        final String packageName = pkg.packageName;
19951        final ApplicationInfo app = pkg.applicationInfo;
19952        final int appId = UserHandle.getAppId(app.uid);
19953
19954        Preconditions.checkNotNull(app.seinfo);
19955
19956        try {
19957            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19958                    appId, app.seinfo, app.targetSdkVersion);
19959        } catch (InstallerException e) {
19960            if (app.isSystemApp()) {
19961                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19962                        + ", but trying to recover: " + e);
19963                destroyAppDataLeafLIF(pkg, userId, flags);
19964                try {
19965                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19966                            appId, app.seinfo, app.targetSdkVersion);
19967                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19968                } catch (InstallerException e2) {
19969                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19970                }
19971            } else {
19972                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19973            }
19974        }
19975
19976        if (restoreconNeeded) {
19977            try {
19978                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19979                        app.seinfo);
19980            } catch (InstallerException e) {
19981                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19982            }
19983        }
19984
19985        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19986            try {
19987                // CE storage is unlocked right now, so read out the inode and
19988                // remember for use later when it's locked
19989                // TODO: mark this structure as dirty so we persist it!
19990                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19991                        StorageManager.FLAG_STORAGE_CE);
19992                synchronized (mPackages) {
19993                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19994                    if (ps != null) {
19995                        ps.setCeDataInode(ceDataInode, userId);
19996                    }
19997                }
19998            } catch (InstallerException e) {
19999                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
20000            }
20001        }
20002
20003        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20004    }
20005
20006    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20007        if (pkg == null) {
20008            Slog.wtf(TAG, "Package was null!", new Throwable());
20009            return;
20010        }
20011        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20012        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20013        for (int i = 0; i < childCount; i++) {
20014            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20015        }
20016    }
20017
20018    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20019        final String volumeUuid = pkg.volumeUuid;
20020        final String packageName = pkg.packageName;
20021        final ApplicationInfo app = pkg.applicationInfo;
20022
20023        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20024            // Create a native library symlink only if we have native libraries
20025            // and if the native libraries are 32 bit libraries. We do not provide
20026            // this symlink for 64 bit libraries.
20027            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20028                final String nativeLibPath = app.nativeLibraryDir;
20029                try {
20030                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20031                            nativeLibPath, userId);
20032                } catch (InstallerException e) {
20033                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20034                }
20035            }
20036        }
20037    }
20038
20039    /**
20040     * For system apps on non-FBE devices, this method migrates any existing
20041     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20042     * requested by the app.
20043     */
20044    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20045        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20046                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20047            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20048                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20049            try {
20050                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20051                        storageTarget);
20052            } catch (InstallerException e) {
20053                logCriticalInfo(Log.WARN,
20054                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20055            }
20056            return true;
20057        } else {
20058            return false;
20059        }
20060    }
20061
20062    public PackageFreezer freezePackage(String packageName, String killReason) {
20063        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20064    }
20065
20066    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20067        return new PackageFreezer(packageName, userId, killReason);
20068    }
20069
20070    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20071            String killReason) {
20072        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20073    }
20074
20075    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20076            String killReason) {
20077        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20078            return new PackageFreezer();
20079        } else {
20080            return freezePackage(packageName, userId, killReason);
20081        }
20082    }
20083
20084    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20085            String killReason) {
20086        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20087    }
20088
20089    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20090            String killReason) {
20091        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20092            return new PackageFreezer();
20093        } else {
20094            return freezePackage(packageName, userId, killReason);
20095        }
20096    }
20097
20098    /**
20099     * Class that freezes and kills the given package upon creation, and
20100     * unfreezes it upon closing. This is typically used when doing surgery on
20101     * app code/data to prevent the app from running while you're working.
20102     */
20103    private class PackageFreezer implements AutoCloseable {
20104        private final String mPackageName;
20105        private final PackageFreezer[] mChildren;
20106
20107        private final boolean mWeFroze;
20108
20109        private final AtomicBoolean mClosed = new AtomicBoolean();
20110        private final CloseGuard mCloseGuard = CloseGuard.get();
20111
20112        /**
20113         * Create and return a stub freezer that doesn't actually do anything,
20114         * typically used when someone requested
20115         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20116         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20117         */
20118        public PackageFreezer() {
20119            mPackageName = null;
20120            mChildren = null;
20121            mWeFroze = false;
20122            mCloseGuard.open("close");
20123        }
20124
20125        public PackageFreezer(String packageName, int userId, String killReason) {
20126            synchronized (mPackages) {
20127                mPackageName = packageName;
20128                mWeFroze = mFrozenPackages.add(mPackageName);
20129
20130                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20131                if (ps != null) {
20132                    killApplication(ps.name, ps.appId, userId, killReason);
20133                }
20134
20135                final PackageParser.Package p = mPackages.get(packageName);
20136                if (p != null && p.childPackages != null) {
20137                    final int N = p.childPackages.size();
20138                    mChildren = new PackageFreezer[N];
20139                    for (int i = 0; i < N; i++) {
20140                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20141                                userId, killReason);
20142                    }
20143                } else {
20144                    mChildren = null;
20145                }
20146            }
20147            mCloseGuard.open("close");
20148        }
20149
20150        @Override
20151        protected void finalize() throws Throwable {
20152            try {
20153                mCloseGuard.warnIfOpen();
20154                close();
20155            } finally {
20156                super.finalize();
20157            }
20158        }
20159
20160        @Override
20161        public void close() {
20162            mCloseGuard.close();
20163            if (mClosed.compareAndSet(false, true)) {
20164                synchronized (mPackages) {
20165                    if (mWeFroze) {
20166                        mFrozenPackages.remove(mPackageName);
20167                    }
20168
20169                    if (mChildren != null) {
20170                        for (PackageFreezer freezer : mChildren) {
20171                            freezer.close();
20172                        }
20173                    }
20174                }
20175            }
20176        }
20177    }
20178
20179    /**
20180     * Verify that given package is currently frozen.
20181     */
20182    private void checkPackageFrozen(String packageName) {
20183        synchronized (mPackages) {
20184            if (!mFrozenPackages.contains(packageName)) {
20185                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20186            }
20187        }
20188    }
20189
20190    @Override
20191    public int movePackage(final String packageName, final String volumeUuid) {
20192        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20193
20194        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20195        final int moveId = mNextMoveId.getAndIncrement();
20196        mHandler.post(new Runnable() {
20197            @Override
20198            public void run() {
20199                try {
20200                    movePackageInternal(packageName, volumeUuid, moveId, user);
20201                } catch (PackageManagerException e) {
20202                    Slog.w(TAG, "Failed to move " + packageName, e);
20203                    mMoveCallbacks.notifyStatusChanged(moveId,
20204                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20205                }
20206            }
20207        });
20208        return moveId;
20209    }
20210
20211    private void movePackageInternal(final String packageName, final String volumeUuid,
20212            final int moveId, UserHandle user) throws PackageManagerException {
20213        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20214        final PackageManager pm = mContext.getPackageManager();
20215
20216        final boolean currentAsec;
20217        final String currentVolumeUuid;
20218        final File codeFile;
20219        final String installerPackageName;
20220        final String packageAbiOverride;
20221        final int appId;
20222        final String seinfo;
20223        final String label;
20224        final int targetSdkVersion;
20225        final PackageFreezer freezer;
20226        final int[] installedUserIds;
20227
20228        // reader
20229        synchronized (mPackages) {
20230            final PackageParser.Package pkg = mPackages.get(packageName);
20231            final PackageSetting ps = mSettings.mPackages.get(packageName);
20232            if (pkg == null || ps == null) {
20233                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20234            }
20235
20236            if (pkg.applicationInfo.isSystemApp()) {
20237                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20238                        "Cannot move system application");
20239            }
20240
20241            if (pkg.applicationInfo.isExternalAsec()) {
20242                currentAsec = true;
20243                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20244            } else if (pkg.applicationInfo.isForwardLocked()) {
20245                currentAsec = true;
20246                currentVolumeUuid = "forward_locked";
20247            } else {
20248                currentAsec = false;
20249                currentVolumeUuid = ps.volumeUuid;
20250
20251                final File probe = new File(pkg.codePath);
20252                final File probeOat = new File(probe, "oat");
20253                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20254                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20255                            "Move only supported for modern cluster style installs");
20256                }
20257            }
20258
20259            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20260                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20261                        "Package already moved to " + volumeUuid);
20262            }
20263            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20264                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20265                        "Device admin cannot be moved");
20266            }
20267
20268            if (mFrozenPackages.contains(packageName)) {
20269                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20270                        "Failed to move already frozen package");
20271            }
20272
20273            codeFile = new File(pkg.codePath);
20274            installerPackageName = ps.installerPackageName;
20275            packageAbiOverride = ps.cpuAbiOverrideString;
20276            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20277            seinfo = pkg.applicationInfo.seinfo;
20278            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20279            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20280            freezer = freezePackage(packageName, "movePackageInternal");
20281            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20282        }
20283
20284        final Bundle extras = new Bundle();
20285        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20286        extras.putString(Intent.EXTRA_TITLE, label);
20287        mMoveCallbacks.notifyCreated(moveId, extras);
20288
20289        int installFlags;
20290        final boolean moveCompleteApp;
20291        final File measurePath;
20292
20293        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20294            installFlags = INSTALL_INTERNAL;
20295            moveCompleteApp = !currentAsec;
20296            measurePath = Environment.getDataAppDirectory(volumeUuid);
20297        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20298            installFlags = INSTALL_EXTERNAL;
20299            moveCompleteApp = false;
20300            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20301        } else {
20302            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20303            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20304                    || !volume.isMountedWritable()) {
20305                freezer.close();
20306                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20307                        "Move location not mounted private volume");
20308            }
20309
20310            Preconditions.checkState(!currentAsec);
20311
20312            installFlags = INSTALL_INTERNAL;
20313            moveCompleteApp = true;
20314            measurePath = Environment.getDataAppDirectory(volumeUuid);
20315        }
20316
20317        final PackageStats stats = new PackageStats(null, -1);
20318        synchronized (mInstaller) {
20319            for (int userId : installedUserIds) {
20320                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20321                    freezer.close();
20322                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20323                            "Failed to measure package size");
20324                }
20325            }
20326        }
20327
20328        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20329                + stats.dataSize);
20330
20331        final long startFreeBytes = measurePath.getFreeSpace();
20332        final long sizeBytes;
20333        if (moveCompleteApp) {
20334            sizeBytes = stats.codeSize + stats.dataSize;
20335        } else {
20336            sizeBytes = stats.codeSize;
20337        }
20338
20339        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20340            freezer.close();
20341            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20342                    "Not enough free space to move");
20343        }
20344
20345        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20346
20347        final CountDownLatch installedLatch = new CountDownLatch(1);
20348        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20349            @Override
20350            public void onUserActionRequired(Intent intent) throws RemoteException {
20351                throw new IllegalStateException();
20352            }
20353
20354            @Override
20355            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20356                    Bundle extras) throws RemoteException {
20357                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20358                        + PackageManager.installStatusToString(returnCode, msg));
20359
20360                installedLatch.countDown();
20361                freezer.close();
20362
20363                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20364                switch (status) {
20365                    case PackageInstaller.STATUS_SUCCESS:
20366                        mMoveCallbacks.notifyStatusChanged(moveId,
20367                                PackageManager.MOVE_SUCCEEDED);
20368                        break;
20369                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20370                        mMoveCallbacks.notifyStatusChanged(moveId,
20371                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20372                        break;
20373                    default:
20374                        mMoveCallbacks.notifyStatusChanged(moveId,
20375                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20376                        break;
20377                }
20378            }
20379        };
20380
20381        final MoveInfo move;
20382        if (moveCompleteApp) {
20383            // Kick off a thread to report progress estimates
20384            new Thread() {
20385                @Override
20386                public void run() {
20387                    while (true) {
20388                        try {
20389                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20390                                break;
20391                            }
20392                        } catch (InterruptedException ignored) {
20393                        }
20394
20395                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20396                        final int progress = 10 + (int) MathUtils.constrain(
20397                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20398                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20399                    }
20400                }
20401            }.start();
20402
20403            final String dataAppName = codeFile.getName();
20404            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20405                    dataAppName, appId, seinfo, targetSdkVersion);
20406        } else {
20407            move = null;
20408        }
20409
20410        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20411
20412        final Message msg = mHandler.obtainMessage(INIT_COPY);
20413        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20414        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20415                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20416                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20417        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20418        msg.obj = params;
20419
20420        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20421                System.identityHashCode(msg.obj));
20422        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20423                System.identityHashCode(msg.obj));
20424
20425        mHandler.sendMessage(msg);
20426    }
20427
20428    @Override
20429    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20430        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20431
20432        final int realMoveId = mNextMoveId.getAndIncrement();
20433        final Bundle extras = new Bundle();
20434        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20435        mMoveCallbacks.notifyCreated(realMoveId, extras);
20436
20437        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20438            @Override
20439            public void onCreated(int moveId, Bundle extras) {
20440                // Ignored
20441            }
20442
20443            @Override
20444            public void onStatusChanged(int moveId, int status, long estMillis) {
20445                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20446            }
20447        };
20448
20449        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20450        storage.setPrimaryStorageUuid(volumeUuid, callback);
20451        return realMoveId;
20452    }
20453
20454    @Override
20455    public int getMoveStatus(int moveId) {
20456        mContext.enforceCallingOrSelfPermission(
20457                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20458        return mMoveCallbacks.mLastStatus.get(moveId);
20459    }
20460
20461    @Override
20462    public void registerMoveCallback(IPackageMoveObserver callback) {
20463        mContext.enforceCallingOrSelfPermission(
20464                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20465        mMoveCallbacks.register(callback);
20466    }
20467
20468    @Override
20469    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20470        mContext.enforceCallingOrSelfPermission(
20471                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20472        mMoveCallbacks.unregister(callback);
20473    }
20474
20475    @Override
20476    public boolean setInstallLocation(int loc) {
20477        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20478                null);
20479        if (getInstallLocation() == loc) {
20480            return true;
20481        }
20482        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20483                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20484            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20485                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20486            return true;
20487        }
20488        return false;
20489   }
20490
20491    @Override
20492    public int getInstallLocation() {
20493        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20494                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20495                PackageHelper.APP_INSTALL_AUTO);
20496    }
20497
20498    /** Called by UserManagerService */
20499    void cleanUpUser(UserManagerService userManager, int userHandle) {
20500        synchronized (mPackages) {
20501            mDirtyUsers.remove(userHandle);
20502            mUserNeedsBadging.delete(userHandle);
20503            mSettings.removeUserLPw(userHandle);
20504            mPendingBroadcasts.remove(userHandle);
20505            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20506            removeUnusedPackagesLPw(userManager, userHandle);
20507        }
20508    }
20509
20510    /**
20511     * We're removing userHandle and would like to remove any downloaded packages
20512     * that are no longer in use by any other user.
20513     * @param userHandle the user being removed
20514     */
20515    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20516        final boolean DEBUG_CLEAN_APKS = false;
20517        int [] users = userManager.getUserIds();
20518        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20519        while (psit.hasNext()) {
20520            PackageSetting ps = psit.next();
20521            if (ps.pkg == null) {
20522                continue;
20523            }
20524            final String packageName = ps.pkg.packageName;
20525            // Skip over if system app
20526            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20527                continue;
20528            }
20529            if (DEBUG_CLEAN_APKS) {
20530                Slog.i(TAG, "Checking package " + packageName);
20531            }
20532            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20533            if (keep) {
20534                if (DEBUG_CLEAN_APKS) {
20535                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20536                }
20537            } else {
20538                for (int i = 0; i < users.length; i++) {
20539                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20540                        keep = true;
20541                        if (DEBUG_CLEAN_APKS) {
20542                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20543                                    + users[i]);
20544                        }
20545                        break;
20546                    }
20547                }
20548            }
20549            if (!keep) {
20550                if (DEBUG_CLEAN_APKS) {
20551                    Slog.i(TAG, "  Removing package " + packageName);
20552                }
20553                mHandler.post(new Runnable() {
20554                    public void run() {
20555                        deletePackageX(packageName, userHandle, 0);
20556                    } //end run
20557                });
20558            }
20559        }
20560    }
20561
20562    /** Called by UserManagerService */
20563    void createNewUser(int userId) {
20564        synchronized (mInstallLock) {
20565            mSettings.createNewUserLI(this, mInstaller, userId);
20566        }
20567        synchronized (mPackages) {
20568            scheduleWritePackageRestrictionsLocked(userId);
20569            scheduleWritePackageListLocked(userId);
20570            applyFactoryDefaultBrowserLPw(userId);
20571            primeDomainVerificationsLPw(userId);
20572        }
20573    }
20574
20575    void onNewUserCreated(final int userId) {
20576        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20577        // If permission review for legacy apps is required, we represent
20578        // dagerous permissions for such apps as always granted runtime
20579        // permissions to keep per user flag state whether review is needed.
20580        // Hence, if a new user is added we have to propagate dangerous
20581        // permission grants for these legacy apps.
20582        if (mPermissionReviewRequired) {
20583            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20584                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20585        }
20586    }
20587
20588    @Override
20589    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20590        mContext.enforceCallingOrSelfPermission(
20591                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20592                "Only package verification agents can read the verifier device identity");
20593
20594        synchronized (mPackages) {
20595            return mSettings.getVerifierDeviceIdentityLPw();
20596        }
20597    }
20598
20599    @Override
20600    public void setPermissionEnforced(String permission, boolean enforced) {
20601        // TODO: Now that we no longer change GID for storage, this should to away.
20602        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20603                "setPermissionEnforced");
20604        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20605            synchronized (mPackages) {
20606                if (mSettings.mReadExternalStorageEnforced == null
20607                        || mSettings.mReadExternalStorageEnforced != enforced) {
20608                    mSettings.mReadExternalStorageEnforced = enforced;
20609                    mSettings.writeLPr();
20610                }
20611            }
20612            // kill any non-foreground processes so we restart them and
20613            // grant/revoke the GID.
20614            final IActivityManager am = ActivityManagerNative.getDefault();
20615            if (am != null) {
20616                final long token = Binder.clearCallingIdentity();
20617                try {
20618                    am.killProcessesBelowForeground("setPermissionEnforcement");
20619                } catch (RemoteException e) {
20620                } finally {
20621                    Binder.restoreCallingIdentity(token);
20622                }
20623            }
20624        } else {
20625            throw new IllegalArgumentException("No selective enforcement for " + permission);
20626        }
20627    }
20628
20629    @Override
20630    @Deprecated
20631    public boolean isPermissionEnforced(String permission) {
20632        return true;
20633    }
20634
20635    @Override
20636    public boolean isStorageLow() {
20637        final long token = Binder.clearCallingIdentity();
20638        try {
20639            final DeviceStorageMonitorInternal
20640                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20641            if (dsm != null) {
20642                return dsm.isMemoryLow();
20643            } else {
20644                return false;
20645            }
20646        } finally {
20647            Binder.restoreCallingIdentity(token);
20648        }
20649    }
20650
20651    @Override
20652    public IPackageInstaller getPackageInstaller() {
20653        return mInstallerService;
20654    }
20655
20656    private boolean userNeedsBadging(int userId) {
20657        int index = mUserNeedsBadging.indexOfKey(userId);
20658        if (index < 0) {
20659            final UserInfo userInfo;
20660            final long token = Binder.clearCallingIdentity();
20661            try {
20662                userInfo = sUserManager.getUserInfo(userId);
20663            } finally {
20664                Binder.restoreCallingIdentity(token);
20665            }
20666            final boolean b;
20667            if (userInfo != null && userInfo.isManagedProfile()) {
20668                b = true;
20669            } else {
20670                b = false;
20671            }
20672            mUserNeedsBadging.put(userId, b);
20673            return b;
20674        }
20675        return mUserNeedsBadging.valueAt(index);
20676    }
20677
20678    @Override
20679    public KeySet getKeySetByAlias(String packageName, String alias) {
20680        if (packageName == null || alias == null) {
20681            return null;
20682        }
20683        synchronized(mPackages) {
20684            final PackageParser.Package pkg = mPackages.get(packageName);
20685            if (pkg == null) {
20686                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20687                throw new IllegalArgumentException("Unknown package: " + packageName);
20688            }
20689            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20690            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20691        }
20692    }
20693
20694    @Override
20695    public KeySet getSigningKeySet(String packageName) {
20696        if (packageName == null) {
20697            return null;
20698        }
20699        synchronized(mPackages) {
20700            final PackageParser.Package pkg = mPackages.get(packageName);
20701            if (pkg == null) {
20702                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20703                throw new IllegalArgumentException("Unknown package: " + packageName);
20704            }
20705            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20706                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20707                throw new SecurityException("May not access signing KeySet of other apps.");
20708            }
20709            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20710            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20711        }
20712    }
20713
20714    @Override
20715    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20716        if (packageName == null || ks == null) {
20717            return false;
20718        }
20719        synchronized(mPackages) {
20720            final PackageParser.Package pkg = mPackages.get(packageName);
20721            if (pkg == null) {
20722                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20723                throw new IllegalArgumentException("Unknown package: " + packageName);
20724            }
20725            IBinder ksh = ks.getToken();
20726            if (ksh instanceof KeySetHandle) {
20727                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20728                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20729            }
20730            return false;
20731        }
20732    }
20733
20734    @Override
20735    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20736        if (packageName == null || ks == null) {
20737            return false;
20738        }
20739        synchronized(mPackages) {
20740            final PackageParser.Package pkg = mPackages.get(packageName);
20741            if (pkg == null) {
20742                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20743                throw new IllegalArgumentException("Unknown package: " + packageName);
20744            }
20745            IBinder ksh = ks.getToken();
20746            if (ksh instanceof KeySetHandle) {
20747                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20748                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20749            }
20750            return false;
20751        }
20752    }
20753
20754    private void deletePackageIfUnusedLPr(final String packageName) {
20755        PackageSetting ps = mSettings.mPackages.get(packageName);
20756        if (ps == null) {
20757            return;
20758        }
20759        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20760            // TODO Implement atomic delete if package is unused
20761            // It is currently possible that the package will be deleted even if it is installed
20762            // after this method returns.
20763            mHandler.post(new Runnable() {
20764                public void run() {
20765                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20766                }
20767            });
20768        }
20769    }
20770
20771    /**
20772     * Check and throw if the given before/after packages would be considered a
20773     * downgrade.
20774     */
20775    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20776            throws PackageManagerException {
20777        if (after.versionCode < before.mVersionCode) {
20778            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20779                    "Update version code " + after.versionCode + " is older than current "
20780                    + before.mVersionCode);
20781        } else if (after.versionCode == before.mVersionCode) {
20782            if (after.baseRevisionCode < before.baseRevisionCode) {
20783                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20784                        "Update base revision code " + after.baseRevisionCode
20785                        + " is older than current " + before.baseRevisionCode);
20786            }
20787
20788            if (!ArrayUtils.isEmpty(after.splitNames)) {
20789                for (int i = 0; i < after.splitNames.length; i++) {
20790                    final String splitName = after.splitNames[i];
20791                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20792                    if (j != -1) {
20793                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20794                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20795                                    "Update split " + splitName + " revision code "
20796                                    + after.splitRevisionCodes[i] + " is older than current "
20797                                    + before.splitRevisionCodes[j]);
20798                        }
20799                    }
20800                }
20801            }
20802        }
20803    }
20804
20805    private static class MoveCallbacks extends Handler {
20806        private static final int MSG_CREATED = 1;
20807        private static final int MSG_STATUS_CHANGED = 2;
20808
20809        private final RemoteCallbackList<IPackageMoveObserver>
20810                mCallbacks = new RemoteCallbackList<>();
20811
20812        private final SparseIntArray mLastStatus = new SparseIntArray();
20813
20814        public MoveCallbacks(Looper looper) {
20815            super(looper);
20816        }
20817
20818        public void register(IPackageMoveObserver callback) {
20819            mCallbacks.register(callback);
20820        }
20821
20822        public void unregister(IPackageMoveObserver callback) {
20823            mCallbacks.unregister(callback);
20824        }
20825
20826        @Override
20827        public void handleMessage(Message msg) {
20828            final SomeArgs args = (SomeArgs) msg.obj;
20829            final int n = mCallbacks.beginBroadcast();
20830            for (int i = 0; i < n; i++) {
20831                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20832                try {
20833                    invokeCallback(callback, msg.what, args);
20834                } catch (RemoteException ignored) {
20835                }
20836            }
20837            mCallbacks.finishBroadcast();
20838            args.recycle();
20839        }
20840
20841        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20842                throws RemoteException {
20843            switch (what) {
20844                case MSG_CREATED: {
20845                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20846                    break;
20847                }
20848                case MSG_STATUS_CHANGED: {
20849                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20850                    break;
20851                }
20852            }
20853        }
20854
20855        private void notifyCreated(int moveId, Bundle extras) {
20856            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20857
20858            final SomeArgs args = SomeArgs.obtain();
20859            args.argi1 = moveId;
20860            args.arg2 = extras;
20861            obtainMessage(MSG_CREATED, args).sendToTarget();
20862        }
20863
20864        private void notifyStatusChanged(int moveId, int status) {
20865            notifyStatusChanged(moveId, status, -1);
20866        }
20867
20868        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20869            Slog.v(TAG, "Move " + moveId + " status " + status);
20870
20871            final SomeArgs args = SomeArgs.obtain();
20872            args.argi1 = moveId;
20873            args.argi2 = status;
20874            args.arg3 = estMillis;
20875            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20876
20877            synchronized (mLastStatus) {
20878                mLastStatus.put(moveId, status);
20879            }
20880        }
20881    }
20882
20883    private final static class OnPermissionChangeListeners extends Handler {
20884        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20885
20886        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20887                new RemoteCallbackList<>();
20888
20889        public OnPermissionChangeListeners(Looper looper) {
20890            super(looper);
20891        }
20892
20893        @Override
20894        public void handleMessage(Message msg) {
20895            switch (msg.what) {
20896                case MSG_ON_PERMISSIONS_CHANGED: {
20897                    final int uid = msg.arg1;
20898                    handleOnPermissionsChanged(uid);
20899                } break;
20900            }
20901        }
20902
20903        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20904            mPermissionListeners.register(listener);
20905
20906        }
20907
20908        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20909            mPermissionListeners.unregister(listener);
20910        }
20911
20912        public void onPermissionsChanged(int uid) {
20913            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20914                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20915            }
20916        }
20917
20918        private void handleOnPermissionsChanged(int uid) {
20919            final int count = mPermissionListeners.beginBroadcast();
20920            try {
20921                for (int i = 0; i < count; i++) {
20922                    IOnPermissionsChangeListener callback = mPermissionListeners
20923                            .getBroadcastItem(i);
20924                    try {
20925                        callback.onPermissionsChanged(uid);
20926                    } catch (RemoteException e) {
20927                        Log.e(TAG, "Permission listener is dead", e);
20928                    }
20929                }
20930            } finally {
20931                mPermissionListeners.finishBroadcast();
20932            }
20933        }
20934    }
20935
20936    private class PackageManagerInternalImpl extends PackageManagerInternal {
20937        @Override
20938        public void setLocationPackagesProvider(PackagesProvider provider) {
20939            synchronized (mPackages) {
20940                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20941            }
20942        }
20943
20944        @Override
20945        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20946            synchronized (mPackages) {
20947                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20948            }
20949        }
20950
20951        @Override
20952        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20953            synchronized (mPackages) {
20954                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20955            }
20956        }
20957
20958        @Override
20959        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20960            synchronized (mPackages) {
20961                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20962            }
20963        }
20964
20965        @Override
20966        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20967            synchronized (mPackages) {
20968                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20969            }
20970        }
20971
20972        @Override
20973        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20974            synchronized (mPackages) {
20975                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20976            }
20977        }
20978
20979        @Override
20980        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20981            synchronized (mPackages) {
20982                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20983                        packageName, userId);
20984            }
20985        }
20986
20987        @Override
20988        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20989            synchronized (mPackages) {
20990                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20991                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20992                        packageName, userId);
20993            }
20994        }
20995
20996        @Override
20997        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20998            synchronized (mPackages) {
20999                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21000                        packageName, userId);
21001            }
21002        }
21003
21004        @Override
21005        public void setKeepUninstalledPackages(final List<String> packageList) {
21006            Preconditions.checkNotNull(packageList);
21007            List<String> removedFromList = null;
21008            synchronized (mPackages) {
21009                if (mKeepUninstalledPackages != null) {
21010                    final int packagesCount = mKeepUninstalledPackages.size();
21011                    for (int i = 0; i < packagesCount; i++) {
21012                        String oldPackage = mKeepUninstalledPackages.get(i);
21013                        if (packageList != null && packageList.contains(oldPackage)) {
21014                            continue;
21015                        }
21016                        if (removedFromList == null) {
21017                            removedFromList = new ArrayList<>();
21018                        }
21019                        removedFromList.add(oldPackage);
21020                    }
21021                }
21022                mKeepUninstalledPackages = new ArrayList<>(packageList);
21023                if (removedFromList != null) {
21024                    final int removedCount = removedFromList.size();
21025                    for (int i = 0; i < removedCount; i++) {
21026                        deletePackageIfUnusedLPr(removedFromList.get(i));
21027                    }
21028                }
21029            }
21030        }
21031
21032        @Override
21033        public boolean isPermissionsReviewRequired(String packageName, int userId) {
21034            synchronized (mPackages) {
21035                // If we do not support permission review, done.
21036                if (!mPermissionReviewRequired) {
21037                    return false;
21038                }
21039
21040                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21041                if (packageSetting == null) {
21042                    return false;
21043                }
21044
21045                // Permission review applies only to apps not supporting the new permission model.
21046                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21047                    return false;
21048                }
21049
21050                // Legacy apps have the permission and get user consent on launch.
21051                PermissionsState permissionsState = packageSetting.getPermissionsState();
21052                return permissionsState.isPermissionReviewRequired(userId);
21053            }
21054        }
21055
21056        @Override
21057        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21058            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21059        }
21060
21061        @Override
21062        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21063                int userId) {
21064            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21065        }
21066
21067        @Override
21068        public void setDeviceAndProfileOwnerPackages(
21069                int deviceOwnerUserId, String deviceOwnerPackage,
21070                SparseArray<String> profileOwnerPackages) {
21071            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21072                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21073        }
21074
21075        @Override
21076        public boolean isPackageDataProtected(int userId, String packageName) {
21077            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21078        }
21079    }
21080
21081    @Override
21082    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21083        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21084        synchronized (mPackages) {
21085            final long identity = Binder.clearCallingIdentity();
21086            try {
21087                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21088                        packageNames, userId);
21089            } finally {
21090                Binder.restoreCallingIdentity(identity);
21091            }
21092        }
21093    }
21094
21095    private static void enforceSystemOrPhoneCaller(String tag) {
21096        int callingUid = Binder.getCallingUid();
21097        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21098            throw new SecurityException(
21099                    "Cannot call " + tag + " from UID " + callingUid);
21100        }
21101    }
21102
21103    boolean isHistoricalPackageUsageAvailable() {
21104        return mPackageUsage.isHistoricalPackageUsageAvailable();
21105    }
21106
21107    /**
21108     * Return a <b>copy</b> of the collection of packages known to the package manager.
21109     * @return A copy of the values of mPackages.
21110     */
21111    Collection<PackageParser.Package> getPackages() {
21112        synchronized (mPackages) {
21113            return new ArrayList<>(mPackages.values());
21114        }
21115    }
21116
21117    /**
21118     * Logs process start information (including base APK hash) to the security log.
21119     * @hide
21120     */
21121    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21122            String apkFile, int pid) {
21123        if (!SecurityLog.isLoggingEnabled()) {
21124            return;
21125        }
21126        Bundle data = new Bundle();
21127        data.putLong("startTimestamp", System.currentTimeMillis());
21128        data.putString("processName", processName);
21129        data.putInt("uid", uid);
21130        data.putString("seinfo", seinfo);
21131        data.putString("apkFile", apkFile);
21132        data.putInt("pid", pid);
21133        Message msg = mProcessLoggingHandler.obtainMessage(
21134                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21135        msg.setData(data);
21136        mProcessLoggingHandler.sendMessage(msg);
21137    }
21138
21139    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21140        return mCompilerStats.getPackageStats(pkgName);
21141    }
21142
21143    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21144        return getOrCreateCompilerPackageStats(pkg.packageName);
21145    }
21146
21147    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21148        return mCompilerStats.getOrCreatePackageStats(pkgName);
21149    }
21150
21151    public void deleteCompilerPackageStats(String pkgName) {
21152        mCompilerStats.deletePackageStats(pkgName);
21153    }
21154}
21155