PackageManagerService.java revision 7e2bb3e6dd1e016f74d174eb154ef44b72fe4b4c
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.ContentResolver;
113import android.content.Context;
114import android.content.IIntentReceiver;
115import android.content.Intent;
116import android.content.IntentFilter;
117import android.content.IntentSender;
118import android.content.IntentSender.SendIntentException;
119import android.content.ServiceConnection;
120import android.content.pm.ActivityInfo;
121import android.content.pm.ApplicationInfo;
122import android.content.pm.AppsQueryHelper;
123import android.content.pm.ComponentInfo;
124import android.content.pm.EphemeralApplicationInfo;
125import android.content.pm.EphemeralResolveInfo;
126import android.content.pm.EphemeralResolveInfo.EphemeralDigest;
127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
128import android.content.pm.FeatureInfo;
129import android.content.pm.IOnPermissionsChangeListener;
130import android.content.pm.IPackageDataObserver;
131import android.content.pm.IPackageDeleteObserver;
132import android.content.pm.IPackageDeleteObserver2;
133import android.content.pm.IPackageInstallObserver2;
134import android.content.pm.IPackageInstaller;
135import android.content.pm.IPackageManager;
136import android.content.pm.IPackageMoveObserver;
137import android.content.pm.IPackageStatsObserver;
138import android.content.pm.InstrumentationInfo;
139import android.content.pm.IntentFilterVerificationInfo;
140import android.content.pm.KeySet;
141import android.content.pm.PackageCleanItem;
142import android.content.pm.PackageInfo;
143import android.content.pm.PackageInfoLite;
144import android.content.pm.PackageInstaller;
145import android.content.pm.PackageManager;
146import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
147import android.content.pm.PackageManagerInternal;
148import android.content.pm.PackageParser;
149import android.content.pm.PackageParser.ActivityIntentInfo;
150import android.content.pm.PackageParser.PackageLite;
151import android.content.pm.PackageParser.PackageParserException;
152import android.content.pm.PackageStats;
153import android.content.pm.PackageUserState;
154import android.content.pm.ParceledListSlice;
155import android.content.pm.PermissionGroupInfo;
156import android.content.pm.PermissionInfo;
157import android.content.pm.ProviderInfo;
158import android.content.pm.ResolveInfo;
159import android.content.pm.ServiceInfo;
160import android.content.pm.Signature;
161import android.content.pm.UserInfo;
162import android.content.pm.VerifierDeviceIdentity;
163import android.content.pm.VerifierInfo;
164import android.content.res.Resources;
165import android.graphics.Bitmap;
166import android.hardware.display.DisplayManager;
167import android.net.Uri;
168import android.os.Binder;
169import android.os.Build;
170import android.os.Bundle;
171import android.os.Debug;
172import android.os.Environment;
173import android.os.Environment.UserEnvironment;
174import android.os.FileUtils;
175import android.os.Handler;
176import android.os.IBinder;
177import android.os.Looper;
178import android.os.Message;
179import android.os.Parcel;
180import android.os.ParcelFileDescriptor;
181import android.os.PatternMatcher;
182import android.os.Process;
183import android.os.RemoteCallbackList;
184import android.os.RemoteException;
185import android.os.ResultReceiver;
186import android.os.SELinux;
187import android.os.ServiceManager;
188import android.os.SystemClock;
189import android.os.SystemProperties;
190import android.os.Trace;
191import android.os.UserHandle;
192import android.os.UserManager;
193import android.os.UserManagerInternal;
194import android.os.storage.IMountService;
195import android.os.storage.MountServiceInternal;
196import android.os.storage.StorageEventListener;
197import android.os.storage.StorageManager;
198import android.os.storage.VolumeInfo;
199import android.os.storage.VolumeRecord;
200import android.provider.Settings.Global;
201import android.provider.Settings.Secure;
202import android.security.KeyStore;
203import android.security.SystemKeyStore;
204import android.system.ErrnoException;
205import android.system.Os;
206import android.text.TextUtils;
207import android.text.format.DateUtils;
208import android.util.ArrayMap;
209import android.util.ArraySet;
210import android.util.DisplayMetrics;
211import android.util.EventLog;
212import android.util.ExceptionUtils;
213import android.util.Log;
214import android.util.LogPrinter;
215import android.util.MathUtils;
216import android.util.Pair;
217import android.util.PrintStreamPrinter;
218import android.util.Slog;
219import android.util.SparseArray;
220import android.util.SparseBooleanArray;
221import android.util.SparseIntArray;
222import android.util.Xml;
223import android.util.jar.StrictJarFile;
224import android.view.Display;
225
226import com.android.internal.R;
227import com.android.internal.annotations.GuardedBy;
228import com.android.internal.app.IMediaContainerService;
229import com.android.internal.app.ResolverActivity;
230import com.android.internal.content.NativeLibraryHelper;
231import com.android.internal.content.PackageHelper;
232import com.android.internal.logging.MetricsLogger;
233import com.android.internal.os.IParcelFileDescriptorFactory;
234import com.android.internal.os.InstallerConnection.InstallerException;
235import com.android.internal.os.SomeArgs;
236import com.android.internal.os.Zygote;
237import com.android.internal.telephony.CarrierAppUtils;
238import com.android.internal.util.ArrayUtils;
239import com.android.internal.util.FastPrintWriter;
240import com.android.internal.util.FastXmlSerializer;
241import com.android.internal.util.IndentingPrintWriter;
242import com.android.internal.util.Preconditions;
243import com.android.internal.util.XmlUtils;
244import com.android.server.AttributeCache;
245import com.android.server.EventLogTags;
246import com.android.server.FgThread;
247import com.android.server.IntentResolver;
248import com.android.server.LocalServices;
249import com.android.server.ServiceThread;
250import com.android.server.SystemConfig;
251import com.android.server.Watchdog;
252import com.android.server.net.NetworkPolicyManagerInternal;
253import com.android.server.pm.PermissionsState.PermissionState;
254import com.android.server.pm.Settings.DatabaseVersion;
255import com.android.server.pm.Settings.VersionInfo;
256import com.android.server.storage.DeviceStorageMonitorInternal;
257
258import dalvik.system.CloseGuard;
259import dalvik.system.DexFile;
260import dalvik.system.VMRuntime;
261
262import libcore.io.IoUtils;
263import libcore.util.EmptyArray;
264
265import org.xmlpull.v1.XmlPullParser;
266import org.xmlpull.v1.XmlPullParserException;
267import org.xmlpull.v1.XmlSerializer;
268
269import java.io.BufferedOutputStream;
270import java.io.BufferedReader;
271import java.io.ByteArrayInputStream;
272import java.io.ByteArrayOutputStream;
273import java.io.File;
274import java.io.FileDescriptor;
275import java.io.FileInputStream;
276import java.io.FileNotFoundException;
277import java.io.FileOutputStream;
278import java.io.FileReader;
279import java.io.FilenameFilter;
280import java.io.IOException;
281import java.io.PrintWriter;
282import java.nio.charset.StandardCharsets;
283import java.security.DigestInputStream;
284import java.security.MessageDigest;
285import java.security.NoSuchAlgorithmException;
286import java.security.PublicKey;
287import java.security.cert.Certificate;
288import java.security.cert.CertificateEncodingException;
289import java.security.cert.CertificateException;
290import java.text.SimpleDateFormat;
291import java.util.ArrayList;
292import java.util.Arrays;
293import java.util.Collection;
294import java.util.Collections;
295import java.util.Comparator;
296import java.util.Date;
297import java.util.HashSet;
298import java.util.Iterator;
299import java.util.List;
300import java.util.Map;
301import java.util.Objects;
302import java.util.Set;
303import java.util.concurrent.CountDownLatch;
304import java.util.concurrent.TimeUnit;
305import java.util.concurrent.atomic.AtomicBoolean;
306import java.util.concurrent.atomic.AtomicInteger;
307
308/**
309 * Keep track of all those APKs everywhere.
310 * <p>
311 * Internally there are two important locks:
312 * <ul>
313 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
314 * and other related state. It is a fine-grained lock that should only be held
315 * momentarily, as it's one of the most contended locks in the system.
316 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
317 * operations typically involve heavy lifting of application data on disk. Since
318 * {@code installd} is single-threaded, and it's operations can often be slow,
319 * this lock should never be acquired while already holding {@link #mPackages}.
320 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
321 * holding {@link #mInstallLock}.
322 * </ul>
323 * Many internal methods rely on the caller to hold the appropriate locks, and
324 * this contract is expressed through method name suffixes:
325 * <ul>
326 * <li>fooLI(): the caller must hold {@link #mInstallLock}
327 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
328 * being modified must be frozen
329 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
330 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
331 * </ul>
332 * <p>
333 * Because this class is very central to the platform's security; please run all
334 * CTS and unit tests whenever making modifications:
335 *
336 * <pre>
337 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
338 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
339 * </pre>
340 */
341public class PackageManagerService extends IPackageManager.Stub {
342    static final String TAG = "PackageManager";
343    static final boolean DEBUG_SETTINGS = false;
344    static final boolean DEBUG_PREFERRED = false;
345    static final boolean DEBUG_UPGRADE = false;
346    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
347    private static final boolean DEBUG_BACKUP = false;
348    private static final boolean DEBUG_INSTALL = false;
349    private static final boolean DEBUG_REMOVE = false;
350    private static final boolean DEBUG_BROADCASTS = false;
351    private static final boolean DEBUG_SHOW_INFO = false;
352    private static final boolean DEBUG_PACKAGE_INFO = false;
353    private static final boolean DEBUG_INTENT_MATCHING = false;
354    private static final boolean DEBUG_PACKAGE_SCANNING = false;
355    private static final boolean DEBUG_VERIFY = false;
356    private static final boolean DEBUG_FILTERS = false;
357
358    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
359    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
360    // user, but by default initialize to this.
361    static final boolean DEBUG_DEXOPT = false;
362
363    private static final boolean DEBUG_ABI_SELECTION = false;
364    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
365    private static final boolean DEBUG_TRIAGED_MISSING = false;
366    private static final boolean DEBUG_APP_DATA = false;
367
368    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
369
370    private static final boolean DISABLE_EPHEMERAL_APPS = false;
371    private static final boolean HIDE_EPHEMERAL_APIS = true;
372
373    private static final int RADIO_UID = Process.PHONE_UID;
374    private static final int LOG_UID = Process.LOG_UID;
375    private static final int NFC_UID = Process.NFC_UID;
376    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
377    private static final int SHELL_UID = Process.SHELL_UID;
378
379    // Cap the size of permission trees that 3rd party apps can define
380    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
381
382    // Suffix used during package installation when copying/moving
383    // package apks to install directory.
384    private static final String INSTALL_PACKAGE_SUFFIX = "-";
385
386    static final int SCAN_NO_DEX = 1<<1;
387    static final int SCAN_FORCE_DEX = 1<<2;
388    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
389    static final int SCAN_NEW_INSTALL = 1<<4;
390    static final int SCAN_NO_PATHS = 1<<5;
391    static final int SCAN_UPDATE_TIME = 1<<6;
392    static final int SCAN_DEFER_DEX = 1<<7;
393    static final int SCAN_BOOTING = 1<<8;
394    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
395    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
396    static final int SCAN_REPLACING = 1<<11;
397    static final int SCAN_REQUIRE_KNOWN = 1<<12;
398    static final int SCAN_MOVE = 1<<13;
399    static final int SCAN_INITIAL = 1<<14;
400    static final int SCAN_CHECK_ONLY = 1<<15;
401    static final int SCAN_DONT_KILL_APP = 1<<17;
402    static final int SCAN_IGNORE_FROZEN = 1<<18;
403
404    static final int REMOVE_CHATTY = 1<<16;
405
406    private static final int[] EMPTY_INT_ARRAY = new int[0];
407
408    /**
409     * Timeout (in milliseconds) after which the watchdog should declare that
410     * our handler thread is wedged.  The usual default for such things is one
411     * minute but we sometimes do very lengthy I/O operations on this thread,
412     * such as installing multi-gigabyte applications, so ours needs to be longer.
413     */
414    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
415
416    /**
417     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
418     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
419     * settings entry if available, otherwise we use the hardcoded default.  If it's been
420     * more than this long since the last fstrim, we force one during the boot sequence.
421     *
422     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
423     * one gets run at the next available charging+idle time.  This final mandatory
424     * no-fstrim check kicks in only of the other scheduling criteria is never met.
425     */
426    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
427
428    /**
429     * Whether verification is enabled by default.
430     */
431    private static final boolean DEFAULT_VERIFY_ENABLE = true;
432
433    /**
434     * The default maximum time to wait for the verification agent to return in
435     * milliseconds.
436     */
437    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
438
439    /**
440     * The default response for package verification timeout.
441     *
442     * This can be either PackageManager.VERIFICATION_ALLOW or
443     * PackageManager.VERIFICATION_REJECT.
444     */
445    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
446
447    static final String PLATFORM_PACKAGE_NAME = "android";
448
449    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
450
451    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
452            DEFAULT_CONTAINER_PACKAGE,
453            "com.android.defcontainer.DefaultContainerService");
454
455    private static final String KILL_APP_REASON_GIDS_CHANGED =
456            "permission grant or revoke changed gids";
457
458    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
459            "permissions revoked";
460
461    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
462
463    private static final String PACKAGE_SCHEME = "package";
464
465    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
466
467    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
468    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
469
470    /** Permission grant: not grant the permission. */
471    private static final int GRANT_DENIED = 1;
472
473    /** Permission grant: grant the permission as an install permission. */
474    private static final int GRANT_INSTALL = 2;
475
476    /** Permission grant: grant the permission as a runtime one. */
477    private static final int GRANT_RUNTIME = 3;
478
479    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
480    private static final int GRANT_UPGRADE = 4;
481
482    /** Canonical intent used to identify what counts as a "web browser" app */
483    private static final Intent sBrowserIntent;
484    static {
485        sBrowserIntent = new Intent();
486        sBrowserIntent.setAction(Intent.ACTION_VIEW);
487        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
488        sBrowserIntent.setData(Uri.parse("http:"));
489    }
490
491    /**
492     * The set of all protected actions [i.e. those actions for which a high priority
493     * intent filter is disallowed].
494     */
495    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
496    static {
497        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
498        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
499        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
500        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
501    }
502
503    // Compilation reasons.
504    public static final int REASON_FIRST_BOOT = 0;
505    public static final int REASON_BOOT = 1;
506    public static final int REASON_INSTALL = 2;
507    public static final int REASON_BACKGROUND_DEXOPT = 3;
508    public static final int REASON_AB_OTA = 4;
509    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
510    public static final int REASON_SHARED_APK = 6;
511    public static final int REASON_FORCED_DEXOPT = 7;
512    public static final int REASON_CORE_APP = 8;
513
514    public static final int REASON_LAST = REASON_CORE_APP;
515
516    /** Special library name that skips shared libraries check during compilation. */
517    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
518
519    final ServiceThread mHandlerThread;
520
521    final PackageHandler mHandler;
522
523    private final ProcessLoggingHandler mProcessLoggingHandler;
524
525    /**
526     * Messages for {@link #mHandler} that need to wait for system ready before
527     * being dispatched.
528     */
529    private ArrayList<Message> mPostSystemReadyMessages;
530
531    final int mSdkVersion = Build.VERSION.SDK_INT;
532
533    final Context mContext;
534    final boolean mFactoryTest;
535    final boolean mOnlyCore;
536    final DisplayMetrics mMetrics;
537    final int mDefParseFlags;
538    final String[] mSeparateProcesses;
539    final boolean mIsUpgrade;
540    final boolean mIsPreNUpgrade;
541    final boolean mIsPreNMR1Upgrade;
542
543    @GuardedBy("mPackages")
544    private boolean mDexOptDialogShown;
545
546    /** The location for ASEC container files on internal storage. */
547    final String mAsecInternalPath;
548
549    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
550    // LOCK HELD.  Can be called with mInstallLock held.
551    @GuardedBy("mInstallLock")
552    final Installer mInstaller;
553
554    /** Directory where installed third-party apps stored */
555    final File mAppInstallDir;
556    final File mEphemeralInstallDir;
557
558    /**
559     * Directory to which applications installed internally have their
560     * 32 bit native libraries copied.
561     */
562    private File mAppLib32InstallDir;
563
564    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
565    // apps.
566    final File mDrmAppPrivateInstallDir;
567
568    // ----------------------------------------------------------------
569
570    // Lock for state used when installing and doing other long running
571    // operations.  Methods that must be called with this lock held have
572    // the suffix "LI".
573    final Object mInstallLock = new Object();
574
575    // ----------------------------------------------------------------
576
577    // Keys are String (package name), values are Package.  This also serves
578    // as the lock for the global state.  Methods that must be called with
579    // this lock held have the prefix "LP".
580    @GuardedBy("mPackages")
581    final ArrayMap<String, PackageParser.Package> mPackages =
582            new ArrayMap<String, PackageParser.Package>();
583
584    final ArrayMap<String, Set<String>> mKnownCodebase =
585            new ArrayMap<String, Set<String>>();
586
587    // Tracks available target package names -> overlay package paths.
588    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
589        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
590
591    /**
592     * Tracks new system packages [received in an OTA] that we expect to
593     * find updated user-installed versions. Keys are package name, values
594     * are package location.
595     */
596    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
597    /**
598     * Tracks high priority intent filters for protected actions. During boot, certain
599     * filter actions are protected and should never be allowed to have a high priority
600     * intent filter for them. However, there is one, and only one exception -- the
601     * setup wizard. It must be able to define a high priority intent filter for these
602     * actions to ensure there are no escapes from the wizard. We need to delay processing
603     * of these during boot as we need to look at all of the system packages in order
604     * to know which component is the setup wizard.
605     */
606    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
607    /**
608     * Whether or not processing protected filters should be deferred.
609     */
610    private boolean mDeferProtectedFilters = true;
611
612    /**
613     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
614     */
615    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
616    /**
617     * Whether or not system app permissions should be promoted from install to runtime.
618     */
619    boolean mPromoteSystemApps;
620
621    @GuardedBy("mPackages")
622    final Settings mSettings;
623
624    /**
625     * Set of package names that are currently "frozen", which means active
626     * surgery is being done on the code/data for that package. The platform
627     * will refuse to launch frozen packages to avoid race conditions.
628     *
629     * @see PackageFreezer
630     */
631    @GuardedBy("mPackages")
632    final ArraySet<String> mFrozenPackages = new ArraySet<>();
633
634    final ProtectedPackages mProtectedPackages;
635
636    boolean mFirstBoot;
637
638    // System configuration read by SystemConfig.
639    final int[] mGlobalGids;
640    final SparseArray<ArraySet<String>> mSystemPermissions;
641    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
642
643    // If mac_permissions.xml was found for seinfo labeling.
644    boolean mFoundPolicyFile;
645
646    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
647
648    public static final class SharedLibraryEntry {
649        public final String path;
650        public final String apk;
651
652        SharedLibraryEntry(String _path, String _apk) {
653            path = _path;
654            apk = _apk;
655        }
656    }
657
658    // Currently known shared libraries.
659    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
660            new ArrayMap<String, SharedLibraryEntry>();
661
662    // All available activities, for your resolving pleasure.
663    final ActivityIntentResolver mActivities =
664            new ActivityIntentResolver();
665
666    // All available receivers, for your resolving pleasure.
667    final ActivityIntentResolver mReceivers =
668            new ActivityIntentResolver();
669
670    // All available services, for your resolving pleasure.
671    final ServiceIntentResolver mServices = new ServiceIntentResolver();
672
673    // All available providers, for your resolving pleasure.
674    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
675
676    // Mapping from provider base names (first directory in content URI codePath)
677    // to the provider information.
678    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
679            new ArrayMap<String, PackageParser.Provider>();
680
681    // Mapping from instrumentation class names to info about them.
682    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
683            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
684
685    // Mapping from permission names to info about them.
686    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
687            new ArrayMap<String, PackageParser.PermissionGroup>();
688
689    // Packages whose data we have transfered into another package, thus
690    // should no longer exist.
691    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
692
693    // Broadcast actions that are only available to the system.
694    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
695
696    /** List of packages waiting for verification. */
697    final SparseArray<PackageVerificationState> mPendingVerification
698            = new SparseArray<PackageVerificationState>();
699
700    /** Set of packages associated with each app op permission. */
701    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
702
703    final PackageInstallerService mInstallerService;
704
705    private final PackageDexOptimizer mPackageDexOptimizer;
706
707    private AtomicInteger mNextMoveId = new AtomicInteger();
708    private final MoveCallbacks mMoveCallbacks;
709
710    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
711
712    // Cache of users who need badging.
713    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
714
715    /** Token for keys in mPendingVerification. */
716    private int mPendingVerificationToken = 0;
717
718    volatile boolean mSystemReady;
719    volatile boolean mSafeMode;
720    volatile boolean mHasSystemUidErrors;
721
722    ApplicationInfo mAndroidApplication;
723    final ActivityInfo mResolveActivity = new ActivityInfo();
724    final ResolveInfo mResolveInfo = new ResolveInfo();
725    ComponentName mResolveComponentName;
726    PackageParser.Package mPlatformPackage;
727    ComponentName mCustomResolverComponentName;
728
729    boolean mResolverReplaced = false;
730
731    private final @Nullable ComponentName mIntentFilterVerifierComponent;
732    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
733
734    private int mIntentFilterVerificationToken = 0;
735
736    /** Component that knows whether or not an ephemeral application exists */
737    final ComponentName mEphemeralResolverComponent;
738    /** The service connection to the ephemeral resolver */
739    final EphemeralResolverConnection mEphemeralResolverConnection;
740
741    /** Component used to install ephemeral applications */
742    final ComponentName mEphemeralInstallerComponent;
743    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
744    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
745
746    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
747            = new SparseArray<IntentFilterVerificationState>();
748
749    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
750
751    // List of packages names to keep cached, even if they are uninstalled for all users
752    private List<String> mKeepUninstalledPackages;
753
754    private UserManagerInternal mUserManagerInternal;
755
756    private static class IFVerificationParams {
757        PackageParser.Package pkg;
758        boolean replacing;
759        int userId;
760        int verifierUid;
761
762        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
763                int _userId, int _verifierUid) {
764            pkg = _pkg;
765            replacing = _replacing;
766            userId = _userId;
767            replacing = _replacing;
768            verifierUid = _verifierUid;
769        }
770    }
771
772    private interface IntentFilterVerifier<T extends IntentFilter> {
773        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
774                                               T filter, String packageName);
775        void startVerifications(int userId);
776        void receiveVerificationResponse(int verificationId);
777    }
778
779    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
780        private Context mContext;
781        private ComponentName mIntentFilterVerifierComponent;
782        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
783
784        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
785            mContext = context;
786            mIntentFilterVerifierComponent = verifierComponent;
787        }
788
789        private String getDefaultScheme() {
790            return IntentFilter.SCHEME_HTTPS;
791        }
792
793        @Override
794        public void startVerifications(int userId) {
795            // Launch verifications requests
796            int count = mCurrentIntentFilterVerifications.size();
797            for (int n=0; n<count; n++) {
798                int verificationId = mCurrentIntentFilterVerifications.get(n);
799                final IntentFilterVerificationState ivs =
800                        mIntentFilterVerificationStates.get(verificationId);
801
802                String packageName = ivs.getPackageName();
803
804                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
805                final int filterCount = filters.size();
806                ArraySet<String> domainsSet = new ArraySet<>();
807                for (int m=0; m<filterCount; m++) {
808                    PackageParser.ActivityIntentInfo filter = filters.get(m);
809                    domainsSet.addAll(filter.getHostsList());
810                }
811                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
812                synchronized (mPackages) {
813                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
814                            packageName, domainsList) != null) {
815                        scheduleWriteSettingsLocked();
816                    }
817                }
818                sendVerificationRequest(userId, verificationId, ivs);
819            }
820            mCurrentIntentFilterVerifications.clear();
821        }
822
823        private void sendVerificationRequest(int userId, int verificationId,
824                IntentFilterVerificationState ivs) {
825
826            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
827            verificationIntent.putExtra(
828                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
829                    verificationId);
830            verificationIntent.putExtra(
831                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
832                    getDefaultScheme());
833            verificationIntent.putExtra(
834                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
835                    ivs.getHostsString());
836            verificationIntent.putExtra(
837                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
838                    ivs.getPackageName());
839            verificationIntent.setComponent(mIntentFilterVerifierComponent);
840            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
841
842            UserHandle user = new UserHandle(userId);
843            mContext.sendBroadcastAsUser(verificationIntent, user);
844            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
845                    "Sending IntentFilter verification broadcast");
846        }
847
848        public void receiveVerificationResponse(int verificationId) {
849            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
850
851            final boolean verified = ivs.isVerified();
852
853            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
854            final int count = filters.size();
855            if (DEBUG_DOMAIN_VERIFICATION) {
856                Slog.i(TAG, "Received verification response " + verificationId
857                        + " for " + count + " filters, verified=" + verified);
858            }
859            for (int n=0; n<count; n++) {
860                PackageParser.ActivityIntentInfo filter = filters.get(n);
861                filter.setVerified(verified);
862
863                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
864                        + " verified with result:" + verified + " and hosts:"
865                        + ivs.getHostsString());
866            }
867
868            mIntentFilterVerificationStates.remove(verificationId);
869
870            final String packageName = ivs.getPackageName();
871            IntentFilterVerificationInfo ivi = null;
872
873            synchronized (mPackages) {
874                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
875            }
876            if (ivi == null) {
877                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
878                        + verificationId + " packageName:" + packageName);
879                return;
880            }
881            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
882                    "Updating IntentFilterVerificationInfo for package " + packageName
883                            +" verificationId:" + verificationId);
884
885            synchronized (mPackages) {
886                if (verified) {
887                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
888                } else {
889                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
890                }
891                scheduleWriteSettingsLocked();
892
893                final int userId = ivs.getUserId();
894                if (userId != UserHandle.USER_ALL) {
895                    final int userStatus =
896                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
897
898                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
899                    boolean needUpdate = false;
900
901                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
902                    // already been set by the User thru the Disambiguation dialog
903                    switch (userStatus) {
904                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
905                            if (verified) {
906                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
907                            } else {
908                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
909                            }
910                            needUpdate = true;
911                            break;
912
913                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
914                            if (verified) {
915                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
916                                needUpdate = true;
917                            }
918                            break;
919
920                        default:
921                            // Nothing to do
922                    }
923
924                    if (needUpdate) {
925                        mSettings.updateIntentFilterVerificationStatusLPw(
926                                packageName, updatedStatus, userId);
927                        scheduleWritePackageRestrictionsLocked(userId);
928                    }
929                }
930            }
931        }
932
933        @Override
934        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
935                    ActivityIntentInfo filter, String packageName) {
936            if (!hasValidDomains(filter)) {
937                return false;
938            }
939            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
940            if (ivs == null) {
941                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
942                        packageName);
943            }
944            if (DEBUG_DOMAIN_VERIFICATION) {
945                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
946            }
947            ivs.addFilter(filter);
948            return true;
949        }
950
951        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
952                int userId, int verificationId, String packageName) {
953            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
954                    verifierUid, userId, packageName);
955            ivs.setPendingState();
956            synchronized (mPackages) {
957                mIntentFilterVerificationStates.append(verificationId, ivs);
958                mCurrentIntentFilterVerifications.add(verificationId);
959            }
960            return ivs;
961        }
962    }
963
964    private static boolean hasValidDomains(ActivityIntentInfo filter) {
965        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
966                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
967                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
968    }
969
970    // Set of pending broadcasts for aggregating enable/disable of components.
971    static class PendingPackageBroadcasts {
972        // for each user id, a map of <package name -> components within that package>
973        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
974
975        public PendingPackageBroadcasts() {
976            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
977        }
978
979        public ArrayList<String> get(int userId, String packageName) {
980            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
981            return packages.get(packageName);
982        }
983
984        public void put(int userId, String packageName, ArrayList<String> components) {
985            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
986            packages.put(packageName, components);
987        }
988
989        public void remove(int userId, String packageName) {
990            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
991            if (packages != null) {
992                packages.remove(packageName);
993            }
994        }
995
996        public void remove(int userId) {
997            mUidMap.remove(userId);
998        }
999
1000        public int userIdCount() {
1001            return mUidMap.size();
1002        }
1003
1004        public int userIdAt(int n) {
1005            return mUidMap.keyAt(n);
1006        }
1007
1008        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1009            return mUidMap.get(userId);
1010        }
1011
1012        public int size() {
1013            // total number of pending broadcast entries across all userIds
1014            int num = 0;
1015            for (int i = 0; i< mUidMap.size(); i++) {
1016                num += mUidMap.valueAt(i).size();
1017            }
1018            return num;
1019        }
1020
1021        public void clear() {
1022            mUidMap.clear();
1023        }
1024
1025        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1026            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1027            if (map == null) {
1028                map = new ArrayMap<String, ArrayList<String>>();
1029                mUidMap.put(userId, map);
1030            }
1031            return map;
1032        }
1033    }
1034    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1035
1036    // Service Connection to remote media container service to copy
1037    // package uri's from external media onto secure containers
1038    // or internal storage.
1039    private IMediaContainerService mContainerService = null;
1040
1041    static final int SEND_PENDING_BROADCAST = 1;
1042    static final int MCS_BOUND = 3;
1043    static final int END_COPY = 4;
1044    static final int INIT_COPY = 5;
1045    static final int MCS_UNBIND = 6;
1046    static final int START_CLEANING_PACKAGE = 7;
1047    static final int FIND_INSTALL_LOC = 8;
1048    static final int POST_INSTALL = 9;
1049    static final int MCS_RECONNECT = 10;
1050    static final int MCS_GIVE_UP = 11;
1051    static final int UPDATED_MEDIA_STATUS = 12;
1052    static final int WRITE_SETTINGS = 13;
1053    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1054    static final int PACKAGE_VERIFIED = 15;
1055    static final int CHECK_PENDING_VERIFICATION = 16;
1056    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1057    static final int INTENT_FILTER_VERIFIED = 18;
1058    static final int WRITE_PACKAGE_LIST = 19;
1059
1060    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1061
1062    // Delay time in millisecs
1063    static final int BROADCAST_DELAY = 10 * 1000;
1064
1065    static UserManagerService sUserManager;
1066
1067    // Stores a list of users whose package restrictions file needs to be updated
1068    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1069
1070    final private DefaultContainerConnection mDefContainerConn =
1071            new DefaultContainerConnection();
1072    class DefaultContainerConnection implements ServiceConnection {
1073        public void onServiceConnected(ComponentName name, IBinder service) {
1074            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1075            IMediaContainerService imcs =
1076                IMediaContainerService.Stub.asInterface(service);
1077            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1078        }
1079
1080        public void onServiceDisconnected(ComponentName name) {
1081            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1082        }
1083    }
1084
1085    // Recordkeeping of restore-after-install operations that are currently in flight
1086    // between the Package Manager and the Backup Manager
1087    static class PostInstallData {
1088        public InstallArgs args;
1089        public PackageInstalledInfo res;
1090
1091        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1092            args = _a;
1093            res = _r;
1094        }
1095    }
1096
1097    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1098    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1099
1100    // XML tags for backup/restore of various bits of state
1101    private static final String TAG_PREFERRED_BACKUP = "pa";
1102    private static final String TAG_DEFAULT_APPS = "da";
1103    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1104
1105    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1106    private static final String TAG_ALL_GRANTS = "rt-grants";
1107    private static final String TAG_GRANT = "grant";
1108    private static final String ATTR_PACKAGE_NAME = "pkg";
1109
1110    private static final String TAG_PERMISSION = "perm";
1111    private static final String ATTR_PERMISSION_NAME = "name";
1112    private static final String ATTR_IS_GRANTED = "g";
1113    private static final String ATTR_USER_SET = "set";
1114    private static final String ATTR_USER_FIXED = "fixed";
1115    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1116
1117    // System/policy permission grants are not backed up
1118    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1119            FLAG_PERMISSION_POLICY_FIXED
1120            | FLAG_PERMISSION_SYSTEM_FIXED
1121            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1122
1123    // And we back up these user-adjusted states
1124    private static final int USER_RUNTIME_GRANT_MASK =
1125            FLAG_PERMISSION_USER_SET
1126            | FLAG_PERMISSION_USER_FIXED
1127            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1128
1129    final @Nullable String mRequiredVerifierPackage;
1130    final @NonNull String mRequiredInstallerPackage;
1131    final @NonNull String mRequiredUninstallerPackage;
1132    final @Nullable String mSetupWizardPackage;
1133    final @Nullable String mStorageManagerPackage;
1134    final @NonNull String mServicesSystemSharedLibraryPackageName;
1135    final @NonNull String mSharedSystemSharedLibraryPackageName;
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        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2060                SystemClock.uptimeMillis());
2061
2062        if (mSdkVersion <= 0) {
2063            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2064        }
2065
2066        mContext = context;
2067        mFactoryTest = factoryTest;
2068        mOnlyCore = onlyCore;
2069        mMetrics = new DisplayMetrics();
2070        mSettings = new Settings(mPackages);
2071        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2072                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2073        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2074                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2075        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2076                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2077        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2078                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2079        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2080                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2081        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2082                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2083
2084        String separateProcesses = SystemProperties.get("debug.separate_processes");
2085        if (separateProcesses != null && separateProcesses.length() > 0) {
2086            if ("*".equals(separateProcesses)) {
2087                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2088                mSeparateProcesses = null;
2089                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2090            } else {
2091                mDefParseFlags = 0;
2092                mSeparateProcesses = separateProcesses.split(",");
2093                Slog.w(TAG, "Running with debug.separate_processes: "
2094                        + separateProcesses);
2095            }
2096        } else {
2097            mDefParseFlags = 0;
2098            mSeparateProcesses = null;
2099        }
2100
2101        mInstaller = installer;
2102        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2103                "*dexopt*");
2104        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2105
2106        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2107                FgThread.get().getLooper());
2108
2109        getDefaultDisplayMetrics(context, mMetrics);
2110
2111        SystemConfig systemConfig = SystemConfig.getInstance();
2112        mGlobalGids = systemConfig.getGlobalGids();
2113        mSystemPermissions = systemConfig.getSystemPermissions();
2114        mAvailableFeatures = systemConfig.getAvailableFeatures();
2115
2116        mProtectedPackages = new ProtectedPackages(mContext);
2117
2118        synchronized (mInstallLock) {
2119        // writer
2120        synchronized (mPackages) {
2121            mHandlerThread = new ServiceThread(TAG,
2122                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2123            mHandlerThread.start();
2124            mHandler = new PackageHandler(mHandlerThread.getLooper());
2125            mProcessLoggingHandler = new ProcessLoggingHandler();
2126            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2127
2128            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2129
2130            File dataDir = Environment.getDataDirectory();
2131            mAppInstallDir = new File(dataDir, "app");
2132            mAppLib32InstallDir = new File(dataDir, "app-lib");
2133            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2134            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2135            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2136
2137            sUserManager = new UserManagerService(context, this, mPackages);
2138
2139            // Propagate permission configuration in to package manager.
2140            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2141                    = systemConfig.getPermissions();
2142            for (int i=0; i<permConfig.size(); i++) {
2143                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2144                BasePermission bp = mSettings.mPermissions.get(perm.name);
2145                if (bp == null) {
2146                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2147                    mSettings.mPermissions.put(perm.name, bp);
2148                }
2149                if (perm.gids != null) {
2150                    bp.setGids(perm.gids, perm.perUser);
2151                }
2152            }
2153
2154            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2155            for (int i=0; i<libConfig.size(); i++) {
2156                mSharedLibraries.put(libConfig.keyAt(i),
2157                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2158            }
2159
2160            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2161
2162            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2163
2164            if (mFirstBoot) {
2165                requestCopyPreoptedFiles();
2166            }
2167
2168            String customResolverActivity = Resources.getSystem().getString(
2169                    R.string.config_customResolverActivity);
2170            if (TextUtils.isEmpty(customResolverActivity)) {
2171                customResolverActivity = null;
2172            } else {
2173                mCustomResolverComponentName = ComponentName.unflattenFromString(
2174                        customResolverActivity);
2175            }
2176
2177            long startTime = SystemClock.uptimeMillis();
2178
2179            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2180                    startTime);
2181
2182            // Set flag to monitor and not change apk file paths when
2183            // scanning install directories.
2184            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2185
2186            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2187            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2188
2189            if (bootClassPath == null) {
2190                Slog.w(TAG, "No BOOTCLASSPATH found!");
2191            }
2192
2193            if (systemServerClassPath == null) {
2194                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2195            }
2196
2197            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2198            final String[] dexCodeInstructionSets =
2199                    getDexCodeInstructionSets(
2200                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2201
2202            /**
2203             * Ensure all external libraries have had dexopt run on them.
2204             */
2205            if (mSharedLibraries.size() > 0) {
2206                // NOTE: For now, we're compiling these system "shared libraries"
2207                // (and framework jars) into all available architectures. It's possible
2208                // to compile them only when we come across an app that uses them (there's
2209                // already logic for that in scanPackageLI) but that adds some complexity.
2210                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2211                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2212                        final String lib = libEntry.path;
2213                        if (lib == null) {
2214                            continue;
2215                        }
2216
2217                        try {
2218                            // Shared libraries do not have profiles so we perform a full
2219                            // AOT compilation (if needed).
2220                            int dexoptNeeded = DexFile.getDexOptNeeded(
2221                                    lib, dexCodeInstructionSet,
2222                                    getCompilerFilterForReason(REASON_SHARED_APK),
2223                                    false /* newProfile */);
2224                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2225                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2226                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2227                                        getCompilerFilterForReason(REASON_SHARED_APK),
2228                                        StorageManager.UUID_PRIVATE_INTERNAL,
2229                                        SKIP_SHARED_LIBRARY_CHECK);
2230                            }
2231                        } catch (FileNotFoundException e) {
2232                            Slog.w(TAG, "Library not found: " + lib);
2233                        } catch (IOException | InstallerException e) {
2234                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2235                                    + e.getMessage());
2236                        }
2237                    }
2238                }
2239            }
2240
2241            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2242
2243            final VersionInfo ver = mSettings.getInternalVersion();
2244            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2245
2246            // when upgrading from pre-M, promote system app permissions from install to runtime
2247            mPromoteSystemApps =
2248                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2249
2250            // When upgrading from pre-N, we need to handle package extraction like first boot,
2251            // as there is no profiling data available.
2252            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2253
2254            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2255
2256            // save off the names of pre-existing system packages prior to scanning; we don't
2257            // want to automatically grant runtime permissions for new system apps
2258            if (mPromoteSystemApps) {
2259                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2260                while (pkgSettingIter.hasNext()) {
2261                    PackageSetting ps = pkgSettingIter.next();
2262                    if (isSystemApp(ps)) {
2263                        mExistingSystemPackages.add(ps.name);
2264                    }
2265                }
2266            }
2267
2268            // Collect vendor overlay packages.
2269            // (Do this before scanning any apps.)
2270            // For security and version matching reason, only consider
2271            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2272            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2273            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2274                    | PackageParser.PARSE_IS_SYSTEM
2275                    | PackageParser.PARSE_IS_SYSTEM_DIR
2276                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2277
2278            // Find base frameworks (resource packages without code).
2279            scanDirTracedLI(frameworkDir, mDefParseFlags
2280                    | PackageParser.PARSE_IS_SYSTEM
2281                    | PackageParser.PARSE_IS_SYSTEM_DIR
2282                    | PackageParser.PARSE_IS_PRIVILEGED,
2283                    scanFlags | SCAN_NO_DEX, 0);
2284
2285            // Collected privileged system packages.
2286            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2287            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2288                    | PackageParser.PARSE_IS_SYSTEM
2289                    | PackageParser.PARSE_IS_SYSTEM_DIR
2290                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2291
2292            // Collect ordinary system packages.
2293            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2294            scanDirTracedLI(systemAppDir, mDefParseFlags
2295                    | PackageParser.PARSE_IS_SYSTEM
2296                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2297
2298            // Collect all vendor packages.
2299            File vendorAppDir = new File("/vendor/app");
2300            try {
2301                vendorAppDir = vendorAppDir.getCanonicalFile();
2302            } catch (IOException e) {
2303                // failed to look up canonical path, continue with original one
2304            }
2305            scanDirTracedLI(vendorAppDir, mDefParseFlags
2306                    | PackageParser.PARSE_IS_SYSTEM
2307                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2308
2309            // Collect all OEM packages.
2310            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2311            scanDirTracedLI(oemAppDir, mDefParseFlags
2312                    | PackageParser.PARSE_IS_SYSTEM
2313                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2314
2315            // Prune any system packages that no longer exist.
2316            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2317            if (!mOnlyCore) {
2318                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2319                while (psit.hasNext()) {
2320                    PackageSetting ps = psit.next();
2321
2322                    /*
2323                     * If this is not a system app, it can't be a
2324                     * disable system app.
2325                     */
2326                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2327                        continue;
2328                    }
2329
2330                    /*
2331                     * If the package is scanned, it's not erased.
2332                     */
2333                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2334                    if (scannedPkg != null) {
2335                        /*
2336                         * If the system app is both scanned and in the
2337                         * disabled packages list, then it must have been
2338                         * added via OTA. Remove it from the currently
2339                         * scanned package so the previously user-installed
2340                         * application can be scanned.
2341                         */
2342                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2343                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2344                                    + ps.name + "; removing system app.  Last known codePath="
2345                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2346                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2347                                    + scannedPkg.mVersionCode);
2348                            removePackageLI(scannedPkg, true);
2349                            mExpectingBetter.put(ps.name, ps.codePath);
2350                        }
2351
2352                        continue;
2353                    }
2354
2355                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2356                        psit.remove();
2357                        logCriticalInfo(Log.WARN, "System package " + ps.name
2358                                + " no longer exists; it's data will be wiped");
2359                        // Actual deletion of code and data will be handled by later
2360                        // reconciliation step
2361                    } else {
2362                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2363                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2364                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2365                        }
2366                    }
2367                }
2368            }
2369
2370            //look for any incomplete package installations
2371            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2372            for (int i = 0; i < deletePkgsList.size(); i++) {
2373                // Actual deletion of code and data will be handled by later
2374                // reconciliation step
2375                final String packageName = deletePkgsList.get(i).name;
2376                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2377                synchronized (mPackages) {
2378                    mSettings.removePackageLPw(packageName);
2379                }
2380            }
2381
2382            //delete tmp files
2383            deleteTempPackageFiles();
2384
2385            // Remove any shared userIDs that have no associated packages
2386            mSettings.pruneSharedUsersLPw();
2387
2388            if (!mOnlyCore) {
2389                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2390                        SystemClock.uptimeMillis());
2391                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2392
2393                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2394                        | PackageParser.PARSE_FORWARD_LOCK,
2395                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2396
2397                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2398                        | PackageParser.PARSE_IS_EPHEMERAL,
2399                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2400
2401                /**
2402                 * Remove disable package settings for any updated system
2403                 * apps that were removed via an OTA. If they're not a
2404                 * previously-updated app, remove them completely.
2405                 * Otherwise, just revoke their system-level permissions.
2406                 */
2407                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2408                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2409                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2410
2411                    String msg;
2412                    if (deletedPkg == null) {
2413                        msg = "Updated system package " + deletedAppName
2414                                + " no longer exists; it's data will be wiped";
2415                        // Actual deletion of code and data will be handled by later
2416                        // reconciliation step
2417                    } else {
2418                        msg = "Updated system app + " + deletedAppName
2419                                + " no longer present; removing system privileges for "
2420                                + deletedAppName;
2421
2422                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2423
2424                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2425                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2426                    }
2427                    logCriticalInfo(Log.WARN, msg);
2428                }
2429
2430                /**
2431                 * Make sure all system apps that we expected to appear on
2432                 * the userdata partition actually showed up. If they never
2433                 * appeared, crawl back and revive the system version.
2434                 */
2435                for (int i = 0; i < mExpectingBetter.size(); i++) {
2436                    final String packageName = mExpectingBetter.keyAt(i);
2437                    if (!mPackages.containsKey(packageName)) {
2438                        final File scanFile = mExpectingBetter.valueAt(i);
2439
2440                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2441                                + " but never showed up; reverting to system");
2442
2443                        int reparseFlags = mDefParseFlags;
2444                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2445                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2446                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2447                                    | PackageParser.PARSE_IS_PRIVILEGED;
2448                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2449                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2450                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2451                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2452                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2453                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2454                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2455                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2456                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2457                        } else {
2458                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2459                            continue;
2460                        }
2461
2462                        mSettings.enableSystemPackageLPw(packageName);
2463
2464                        try {
2465                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2466                        } catch (PackageManagerException e) {
2467                            Slog.e(TAG, "Failed to parse original system package: "
2468                                    + e.getMessage());
2469                        }
2470                    }
2471                }
2472            }
2473            mExpectingBetter.clear();
2474
2475            // Resolve the storage manager.
2476            mStorageManagerPackage = getStorageManagerPackageName();
2477
2478            // Resolve protected action filters. Only the setup wizard is allowed to
2479            // have a high priority filter for these actions.
2480            mSetupWizardPackage = getSetupWizardPackageName();
2481            if (mProtectedFilters.size() > 0) {
2482                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2483                    Slog.i(TAG, "No setup wizard;"
2484                        + " All protected intents capped to priority 0");
2485                }
2486                for (ActivityIntentInfo filter : mProtectedFilters) {
2487                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2488                        if (DEBUG_FILTERS) {
2489                            Slog.i(TAG, "Found setup wizard;"
2490                                + " allow priority " + filter.getPriority() + ";"
2491                                + " package: " + filter.activity.info.packageName
2492                                + " activity: " + filter.activity.className
2493                                + " priority: " + filter.getPriority());
2494                        }
2495                        // skip setup wizard; allow it to keep the high priority filter
2496                        continue;
2497                    }
2498                    Slog.w(TAG, "Protected action; cap priority to 0;"
2499                            + " package: " + filter.activity.info.packageName
2500                            + " activity: " + filter.activity.className
2501                            + " origPrio: " + filter.getPriority());
2502                    filter.setPriority(0);
2503                }
2504            }
2505            mDeferProtectedFilters = false;
2506            mProtectedFilters.clear();
2507
2508            // Now that we know all of the shared libraries, update all clients to have
2509            // the correct library paths.
2510            updateAllSharedLibrariesLPw();
2511
2512            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2513                // NOTE: We ignore potential failures here during a system scan (like
2514                // the rest of the commands above) because there's precious little we
2515                // can do about it. A settings error is reported, though.
2516                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2517                        false /* boot complete */);
2518            }
2519
2520            // Now that we know all the packages we are keeping,
2521            // read and update their last usage times.
2522            mPackageUsage.read(mPackages);
2523            mCompilerStats.read();
2524
2525            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2526                    SystemClock.uptimeMillis());
2527            Slog.i(TAG, "Time to scan packages: "
2528                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2529                    + " seconds");
2530
2531            // If the platform SDK has changed since the last time we booted,
2532            // we need to re-grant app permission to catch any new ones that
2533            // appear.  This is really a hack, and means that apps can in some
2534            // cases get permissions that the user didn't initially explicitly
2535            // allow...  it would be nice to have some better way to handle
2536            // this situation.
2537            int updateFlags = UPDATE_PERMISSIONS_ALL;
2538            if (ver.sdkVersion != mSdkVersion) {
2539                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2540                        + mSdkVersion + "; regranting permissions for internal storage");
2541                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2542            }
2543            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2544            ver.sdkVersion = mSdkVersion;
2545
2546            // If this is the first boot or an update from pre-M, and it is a normal
2547            // boot, then we need to initialize the default preferred apps across
2548            // all defined users.
2549            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2550                for (UserInfo user : sUserManager.getUsers(true)) {
2551                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2552                    applyFactoryDefaultBrowserLPw(user.id);
2553                    primeDomainVerificationsLPw(user.id);
2554                }
2555            }
2556
2557            // Prepare storage for system user really early during boot,
2558            // since core system apps like SettingsProvider and SystemUI
2559            // can't wait for user to start
2560            final int storageFlags;
2561            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2562                storageFlags = StorageManager.FLAG_STORAGE_DE;
2563            } else {
2564                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2565            }
2566            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2567                    storageFlags);
2568
2569            // If this is first boot after an OTA, and a normal boot, then
2570            // we need to clear code cache directories.
2571            // Note that we do *not* clear the application profiles. These remain valid
2572            // across OTAs and are used to drive profile verification (post OTA) and
2573            // profile compilation (without waiting to collect a fresh set of profiles).
2574            if (mIsUpgrade && !onlyCore) {
2575                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2576                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2577                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2578                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2579                        // No apps are running this early, so no need to freeze
2580                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2581                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2582                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2583                    }
2584                }
2585                ver.fingerprint = Build.FINGERPRINT;
2586            }
2587
2588            checkDefaultBrowser();
2589
2590            // clear only after permissions and other defaults have been updated
2591            mExistingSystemPackages.clear();
2592            mPromoteSystemApps = false;
2593
2594            // All the changes are done during package scanning.
2595            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2596
2597            // can downgrade to reader
2598            mSettings.writeLPr();
2599
2600            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2601            // early on (before the package manager declares itself as early) because other
2602            // components in the system server might ask for package contexts for these apps.
2603            //
2604            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2605            // (i.e, that the data partition is unavailable).
2606            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2607                long start = System.nanoTime();
2608                List<PackageParser.Package> coreApps = new ArrayList<>();
2609                for (PackageParser.Package pkg : mPackages.values()) {
2610                    if (pkg.coreApp) {
2611                        coreApps.add(pkg);
2612                    }
2613                }
2614
2615                int[] stats = performDexOptUpgrade(coreApps, false,
2616                        getCompilerFilterForReason(REASON_CORE_APP));
2617
2618                final int elapsedTimeSeconds =
2619                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2620                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2621
2622                if (DEBUG_DEXOPT) {
2623                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2624                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2625                }
2626
2627
2628                // TODO: Should we log these stats to tron too ?
2629                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2630                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2631                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2632                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2633            }
2634
2635            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2636                    SystemClock.uptimeMillis());
2637
2638            if (!mOnlyCore) {
2639                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2640                mRequiredInstallerPackage = getRequiredInstallerLPr();
2641                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2642                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2643                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2644                        mIntentFilterVerifierComponent);
2645                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2646                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2647                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2648                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2649            } else {
2650                mRequiredVerifierPackage = null;
2651                mRequiredInstallerPackage = null;
2652                mRequiredUninstallerPackage = null;
2653                mIntentFilterVerifierComponent = null;
2654                mIntentFilterVerifier = null;
2655                mServicesSystemSharedLibraryPackageName = null;
2656                mSharedSystemSharedLibraryPackageName = null;
2657            }
2658
2659            mInstallerService = new PackageInstallerService(context, this);
2660
2661            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2662            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2663            // both the installer and resolver must be present to enable ephemeral
2664            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2665                if (DEBUG_EPHEMERAL) {
2666                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2667                            + " installer:" + ephemeralInstallerComponent);
2668                }
2669                mEphemeralResolverComponent = ephemeralResolverComponent;
2670                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2671                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2672                mEphemeralResolverConnection =
2673                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2674            } else {
2675                if (DEBUG_EPHEMERAL) {
2676                    final String missingComponent =
2677                            (ephemeralResolverComponent == null)
2678                            ? (ephemeralInstallerComponent == null)
2679                                    ? "resolver and installer"
2680                                    : "resolver"
2681                            : "installer";
2682                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2683                }
2684                mEphemeralResolverComponent = null;
2685                mEphemeralInstallerComponent = null;
2686                mEphemeralResolverConnection = null;
2687            }
2688
2689            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2690        } // synchronized (mPackages)
2691        } // synchronized (mInstallLock)
2692
2693        // Now after opening every single application zip, make sure they
2694        // are all flushed.  Not really needed, but keeps things nice and
2695        // tidy.
2696        Runtime.getRuntime().gc();
2697
2698        // The initial scanning above does many calls into installd while
2699        // holding the mPackages lock, but we're mostly interested in yelling
2700        // once we have a booted system.
2701        mInstaller.setWarnIfHeld(mPackages);
2702
2703        // Expose private service for system components to use.
2704        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2705    }
2706
2707    @Override
2708    public boolean isFirstBoot() {
2709        return mFirstBoot;
2710    }
2711
2712    @Override
2713    public boolean isOnlyCoreApps() {
2714        return mOnlyCore;
2715    }
2716
2717    @Override
2718    public boolean isUpgrade() {
2719        return mIsUpgrade;
2720    }
2721
2722    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2723        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2724
2725        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2726                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2727                UserHandle.USER_SYSTEM);
2728        if (matches.size() == 1) {
2729            return matches.get(0).getComponentInfo().packageName;
2730        } else if (matches.size() == 0) {
2731            Log.e(TAG, "There should probably be a verifier, but, none were found");
2732            return null;
2733        }
2734        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2735    }
2736
2737    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2738        synchronized (mPackages) {
2739            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2740            if (libraryEntry == null) {
2741                throw new IllegalStateException("Missing required shared library:" + libraryName);
2742            }
2743            return libraryEntry.apk;
2744        }
2745    }
2746
2747    private @NonNull String getRequiredInstallerLPr() {
2748        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2749        intent.addCategory(Intent.CATEGORY_DEFAULT);
2750        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2751
2752        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2753                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2754                UserHandle.USER_SYSTEM);
2755        if (matches.size() == 1) {
2756            ResolveInfo resolveInfo = matches.get(0);
2757            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2758                throw new RuntimeException("The installer must be a privileged app");
2759            }
2760            return matches.get(0).getComponentInfo().packageName;
2761        } else {
2762            throw new RuntimeException("There must be exactly one installer; found " + matches);
2763        }
2764    }
2765
2766    private @NonNull String getRequiredUninstallerLPr() {
2767        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2768        intent.addCategory(Intent.CATEGORY_DEFAULT);
2769        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2770
2771        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2772                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2773                UserHandle.USER_SYSTEM);
2774        if (resolveInfo == null ||
2775                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2776            throw new RuntimeException("There must be exactly one uninstaller; found "
2777                    + resolveInfo);
2778        }
2779        return resolveInfo.getComponentInfo().packageName;
2780    }
2781
2782    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2783        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2784
2785        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2786                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2787                UserHandle.USER_SYSTEM);
2788        ResolveInfo best = null;
2789        final int N = matches.size();
2790        for (int i = 0; i < N; i++) {
2791            final ResolveInfo cur = matches.get(i);
2792            final String packageName = cur.getComponentInfo().packageName;
2793            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2794                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2795                continue;
2796            }
2797
2798            if (best == null || cur.priority > best.priority) {
2799                best = cur;
2800            }
2801        }
2802
2803        if (best != null) {
2804            return best.getComponentInfo().getComponentName();
2805        } else {
2806            throw new RuntimeException("There must be at least one intent filter verifier");
2807        }
2808    }
2809
2810    private @Nullable ComponentName getEphemeralResolverLPr() {
2811        final String[] packageArray =
2812                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2813        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2814            if (DEBUG_EPHEMERAL) {
2815                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2816            }
2817            return null;
2818        }
2819
2820        final int resolveFlags =
2821                MATCH_DIRECT_BOOT_AWARE
2822                | MATCH_DIRECT_BOOT_UNAWARE
2823                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2824        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2825        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2826                resolveFlags, UserHandle.USER_SYSTEM);
2827
2828        final int N = resolvers.size();
2829        if (N == 0) {
2830            if (DEBUG_EPHEMERAL) {
2831                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2832            }
2833            return null;
2834        }
2835
2836        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2837        for (int i = 0; i < N; i++) {
2838            final ResolveInfo info = resolvers.get(i);
2839
2840            if (info.serviceInfo == null) {
2841                continue;
2842            }
2843
2844            final String packageName = info.serviceInfo.packageName;
2845            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2846                if (DEBUG_EPHEMERAL) {
2847                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2848                            + " pkg: " + packageName + ", info:" + info);
2849                }
2850                continue;
2851            }
2852
2853            if (DEBUG_EPHEMERAL) {
2854                Slog.v(TAG, "Ephemeral resolver found;"
2855                        + " pkg: " + packageName + ", info:" + info);
2856            }
2857            return new ComponentName(packageName, info.serviceInfo.name);
2858        }
2859        if (DEBUG_EPHEMERAL) {
2860            Slog.v(TAG, "Ephemeral resolver NOT found");
2861        }
2862        return null;
2863    }
2864
2865    private @Nullable ComponentName getEphemeralInstallerLPr() {
2866        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2867        intent.addCategory(Intent.CATEGORY_DEFAULT);
2868        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2869
2870        final int resolveFlags =
2871                MATCH_DIRECT_BOOT_AWARE
2872                | MATCH_DIRECT_BOOT_UNAWARE
2873                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2874        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2875                resolveFlags, UserHandle.USER_SYSTEM);
2876        if (matches.size() == 0) {
2877            return null;
2878        } else if (matches.size() == 1) {
2879            return matches.get(0).getComponentInfo().getComponentName();
2880        } else {
2881            throw new RuntimeException(
2882                    "There must be at most one ephemeral installer; found " + matches);
2883        }
2884    }
2885
2886    private void primeDomainVerificationsLPw(int userId) {
2887        if (DEBUG_DOMAIN_VERIFICATION) {
2888            Slog.d(TAG, "Priming domain verifications in user " + userId);
2889        }
2890
2891        SystemConfig systemConfig = SystemConfig.getInstance();
2892        ArraySet<String> packages = systemConfig.getLinkedApps();
2893        ArraySet<String> domains = new ArraySet<String>();
2894
2895        for (String packageName : packages) {
2896            PackageParser.Package pkg = mPackages.get(packageName);
2897            if (pkg != null) {
2898                if (!pkg.isSystemApp()) {
2899                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2900                    continue;
2901                }
2902
2903                domains.clear();
2904                for (PackageParser.Activity a : pkg.activities) {
2905                    for (ActivityIntentInfo filter : a.intents) {
2906                        if (hasValidDomains(filter)) {
2907                            domains.addAll(filter.getHostsList());
2908                        }
2909                    }
2910                }
2911
2912                if (domains.size() > 0) {
2913                    if (DEBUG_DOMAIN_VERIFICATION) {
2914                        Slog.v(TAG, "      + " + packageName);
2915                    }
2916                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2917                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2918                    // and then 'always' in the per-user state actually used for intent resolution.
2919                    final IntentFilterVerificationInfo ivi;
2920                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2921                            new ArrayList<String>(domains));
2922                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2923                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2924                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2925                } else {
2926                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2927                            + "' does not handle web links");
2928                }
2929            } else {
2930                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2931            }
2932        }
2933
2934        scheduleWritePackageRestrictionsLocked(userId);
2935        scheduleWriteSettingsLocked();
2936    }
2937
2938    private void applyFactoryDefaultBrowserLPw(int userId) {
2939        // The default browser app's package name is stored in a string resource,
2940        // with a product-specific overlay used for vendor customization.
2941        String browserPkg = mContext.getResources().getString(
2942                com.android.internal.R.string.default_browser);
2943        if (!TextUtils.isEmpty(browserPkg)) {
2944            // non-empty string => required to be a known package
2945            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2946            if (ps == null) {
2947                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2948                browserPkg = null;
2949            } else {
2950                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2951            }
2952        }
2953
2954        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2955        // default.  If there's more than one, just leave everything alone.
2956        if (browserPkg == null) {
2957            calculateDefaultBrowserLPw(userId);
2958        }
2959    }
2960
2961    private void calculateDefaultBrowserLPw(int userId) {
2962        List<String> allBrowsers = resolveAllBrowserApps(userId);
2963        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2964        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2965    }
2966
2967    private List<String> resolveAllBrowserApps(int userId) {
2968        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2969        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2970                PackageManager.MATCH_ALL, userId);
2971
2972        final int count = list.size();
2973        List<String> result = new ArrayList<String>(count);
2974        for (int i=0; i<count; i++) {
2975            ResolveInfo info = list.get(i);
2976            if (info.activityInfo == null
2977                    || !info.handleAllWebDataURI
2978                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2979                    || result.contains(info.activityInfo.packageName)) {
2980                continue;
2981            }
2982            result.add(info.activityInfo.packageName);
2983        }
2984
2985        return result;
2986    }
2987
2988    private boolean packageIsBrowser(String packageName, int userId) {
2989        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2990                PackageManager.MATCH_ALL, userId);
2991        final int N = list.size();
2992        for (int i = 0; i < N; i++) {
2993            ResolveInfo info = list.get(i);
2994            if (packageName.equals(info.activityInfo.packageName)) {
2995                return true;
2996            }
2997        }
2998        return false;
2999    }
3000
3001    private void checkDefaultBrowser() {
3002        final int myUserId = UserHandle.myUserId();
3003        final String packageName = getDefaultBrowserPackageName(myUserId);
3004        if (packageName != null) {
3005            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3006            if (info == null) {
3007                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3008                synchronized (mPackages) {
3009                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3010                }
3011            }
3012        }
3013    }
3014
3015    @Override
3016    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3017            throws RemoteException {
3018        try {
3019            return super.onTransact(code, data, reply, flags);
3020        } catch (RuntimeException e) {
3021            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3022                Slog.wtf(TAG, "Package Manager Crash", e);
3023            }
3024            throw e;
3025        }
3026    }
3027
3028    static int[] appendInts(int[] cur, int[] add) {
3029        if (add == null) return cur;
3030        if (cur == null) return add;
3031        final int N = add.length;
3032        for (int i=0; i<N; i++) {
3033            cur = appendInt(cur, add[i]);
3034        }
3035        return cur;
3036    }
3037
3038    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3039        if (!sUserManager.exists(userId)) return null;
3040        if (ps == null) {
3041            return null;
3042        }
3043        final PackageParser.Package p = ps.pkg;
3044        if (p == null) {
3045            return null;
3046        }
3047
3048        final PermissionsState permissionsState = ps.getPermissionsState();
3049
3050        // Compute GIDs only if requested
3051        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3052                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3053        // Compute granted permissions only if package has requested permissions
3054        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3055                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3056        final PackageUserState state = ps.readUserState(userId);
3057
3058        return PackageParser.generatePackageInfo(p, gids, flags,
3059                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3060    }
3061
3062    @Override
3063    public void checkPackageStartable(String packageName, int userId) {
3064        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3065
3066        synchronized (mPackages) {
3067            final PackageSetting ps = mSettings.mPackages.get(packageName);
3068            if (ps == null) {
3069                throw new SecurityException("Package " + packageName + " was not found!");
3070            }
3071
3072            if (!ps.getInstalled(userId)) {
3073                throw new SecurityException(
3074                        "Package " + packageName + " was not installed for user " + userId + "!");
3075            }
3076
3077            if (mSafeMode && !ps.isSystem()) {
3078                throw new SecurityException("Package " + packageName + " not a system app!");
3079            }
3080
3081            if (mFrozenPackages.contains(packageName)) {
3082                throw new SecurityException("Package " + packageName + " is currently frozen!");
3083            }
3084
3085            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3086                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3087                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3088            }
3089        }
3090    }
3091
3092    @Override
3093    public boolean isPackageAvailable(String packageName, int userId) {
3094        if (!sUserManager.exists(userId)) return false;
3095        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3096                false /* requireFullPermission */, false /* checkShell */, "is package available");
3097        synchronized (mPackages) {
3098            PackageParser.Package p = mPackages.get(packageName);
3099            if (p != null) {
3100                final PackageSetting ps = (PackageSetting) p.mExtras;
3101                if (ps != null) {
3102                    final PackageUserState state = ps.readUserState(userId);
3103                    if (state != null) {
3104                        return PackageParser.isAvailable(state);
3105                    }
3106                }
3107            }
3108        }
3109        return false;
3110    }
3111
3112    @Override
3113    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3114        if (!sUserManager.exists(userId)) return null;
3115        flags = updateFlagsForPackage(flags, userId, packageName);
3116        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3117                false /* requireFullPermission */, false /* checkShell */, "get package info");
3118        // reader
3119        synchronized (mPackages) {
3120            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3121            PackageParser.Package p = null;
3122            if (matchFactoryOnly) {
3123                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3124                if (ps != null) {
3125                    return generatePackageInfo(ps, flags, userId);
3126                }
3127            }
3128            if (p == null) {
3129                p = mPackages.get(packageName);
3130                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3131                    return null;
3132                }
3133            }
3134            if (DEBUG_PACKAGE_INFO)
3135                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3136            if (p != null) {
3137                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3138            }
3139            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3140                final PackageSetting ps = mSettings.mPackages.get(packageName);
3141                return generatePackageInfo(ps, flags, userId);
3142            }
3143        }
3144        return null;
3145    }
3146
3147    @Override
3148    public String[] currentToCanonicalPackageNames(String[] names) {
3149        String[] out = new String[names.length];
3150        // reader
3151        synchronized (mPackages) {
3152            for (int i=names.length-1; i>=0; i--) {
3153                PackageSetting ps = mSettings.mPackages.get(names[i]);
3154                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3155            }
3156        }
3157        return out;
3158    }
3159
3160    @Override
3161    public String[] canonicalToCurrentPackageNames(String[] names) {
3162        String[] out = new String[names.length];
3163        // reader
3164        synchronized (mPackages) {
3165            for (int i=names.length-1; i>=0; i--) {
3166                String cur = mSettings.mRenamedPackages.get(names[i]);
3167                out[i] = cur != null ? cur : names[i];
3168            }
3169        }
3170        return out;
3171    }
3172
3173    @Override
3174    public int getPackageUid(String packageName, int flags, int userId) {
3175        if (!sUserManager.exists(userId)) return -1;
3176        flags = updateFlagsForPackage(flags, userId, packageName);
3177        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3178                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3179
3180        // reader
3181        synchronized (mPackages) {
3182            final PackageParser.Package p = mPackages.get(packageName);
3183            if (p != null && p.isMatch(flags)) {
3184                return UserHandle.getUid(userId, p.applicationInfo.uid);
3185            }
3186            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3187                final PackageSetting ps = mSettings.mPackages.get(packageName);
3188                if (ps != null && ps.isMatch(flags)) {
3189                    return UserHandle.getUid(userId, ps.appId);
3190                }
3191            }
3192        }
3193
3194        return -1;
3195    }
3196
3197    @Override
3198    public int[] getPackageGids(String packageName, int flags, int userId) {
3199        if (!sUserManager.exists(userId)) return null;
3200        flags = updateFlagsForPackage(flags, userId, packageName);
3201        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3202                false /* requireFullPermission */, false /* checkShell */,
3203                "getPackageGids");
3204
3205        // reader
3206        synchronized (mPackages) {
3207            final PackageParser.Package p = mPackages.get(packageName);
3208            if (p != null && p.isMatch(flags)) {
3209                PackageSetting ps = (PackageSetting) p.mExtras;
3210                return ps.getPermissionsState().computeGids(userId);
3211            }
3212            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3213                final PackageSetting ps = mSettings.mPackages.get(packageName);
3214                if (ps != null && ps.isMatch(flags)) {
3215                    return ps.getPermissionsState().computeGids(userId);
3216                }
3217            }
3218        }
3219
3220        return null;
3221    }
3222
3223    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3224        if (bp.perm != null) {
3225            return PackageParser.generatePermissionInfo(bp.perm, flags);
3226        }
3227        PermissionInfo pi = new PermissionInfo();
3228        pi.name = bp.name;
3229        pi.packageName = bp.sourcePackage;
3230        pi.nonLocalizedLabel = bp.name;
3231        pi.protectionLevel = bp.protectionLevel;
3232        return pi;
3233    }
3234
3235    @Override
3236    public PermissionInfo getPermissionInfo(String name, int flags) {
3237        // reader
3238        synchronized (mPackages) {
3239            final BasePermission p = mSettings.mPermissions.get(name);
3240            if (p != null) {
3241                return generatePermissionInfo(p, flags);
3242            }
3243            return null;
3244        }
3245    }
3246
3247    @Override
3248    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3249            int flags) {
3250        // reader
3251        synchronized (mPackages) {
3252            if (group != null && !mPermissionGroups.containsKey(group)) {
3253                // This is thrown as NameNotFoundException
3254                return null;
3255            }
3256
3257            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3258            for (BasePermission p : mSettings.mPermissions.values()) {
3259                if (group == null) {
3260                    if (p.perm == null || p.perm.info.group == null) {
3261                        out.add(generatePermissionInfo(p, flags));
3262                    }
3263                } else {
3264                    if (p.perm != null && group.equals(p.perm.info.group)) {
3265                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3266                    }
3267                }
3268            }
3269            return new ParceledListSlice<>(out);
3270        }
3271    }
3272
3273    @Override
3274    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3275        // reader
3276        synchronized (mPackages) {
3277            return PackageParser.generatePermissionGroupInfo(
3278                    mPermissionGroups.get(name), flags);
3279        }
3280    }
3281
3282    @Override
3283    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3284        // reader
3285        synchronized (mPackages) {
3286            final int N = mPermissionGroups.size();
3287            ArrayList<PermissionGroupInfo> out
3288                    = new ArrayList<PermissionGroupInfo>(N);
3289            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3290                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3291            }
3292            return new ParceledListSlice<>(out);
3293        }
3294    }
3295
3296    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3297            int userId) {
3298        if (!sUserManager.exists(userId)) return null;
3299        PackageSetting ps = mSettings.mPackages.get(packageName);
3300        if (ps != null) {
3301            if (ps.pkg == null) {
3302                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3303                if (pInfo != null) {
3304                    return pInfo.applicationInfo;
3305                }
3306                return null;
3307            }
3308            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3309                    ps.readUserState(userId), userId);
3310        }
3311        return null;
3312    }
3313
3314    @Override
3315    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3316        if (!sUserManager.exists(userId)) return null;
3317        flags = updateFlagsForApplication(flags, userId, packageName);
3318        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3319                false /* requireFullPermission */, false /* checkShell */, "get application info");
3320        // writer
3321        synchronized (mPackages) {
3322            PackageParser.Package p = mPackages.get(packageName);
3323            if (DEBUG_PACKAGE_INFO) Log.v(
3324                    TAG, "getApplicationInfo " + packageName
3325                    + ": " + p);
3326            if (p != null) {
3327                PackageSetting ps = mSettings.mPackages.get(packageName);
3328                if (ps == null) return null;
3329                // Note: isEnabledLP() does not apply here - always return info
3330                return PackageParser.generateApplicationInfo(
3331                        p, flags, ps.readUserState(userId), userId);
3332            }
3333            if ("android".equals(packageName)||"system".equals(packageName)) {
3334                return mAndroidApplication;
3335            }
3336            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3337                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3338            }
3339        }
3340        return null;
3341    }
3342
3343    @Override
3344    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3345            final IPackageDataObserver observer) {
3346        mContext.enforceCallingOrSelfPermission(
3347                android.Manifest.permission.CLEAR_APP_CACHE, null);
3348        // Queue up an async operation since clearing cache may take a little while.
3349        mHandler.post(new Runnable() {
3350            public void run() {
3351                mHandler.removeCallbacks(this);
3352                boolean success = true;
3353                synchronized (mInstallLock) {
3354                    try {
3355                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3356                    } catch (InstallerException e) {
3357                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3358                        success = false;
3359                    }
3360                }
3361                if (observer != null) {
3362                    try {
3363                        observer.onRemoveCompleted(null, success);
3364                    } catch (RemoteException e) {
3365                        Slog.w(TAG, "RemoveException when invoking call back");
3366                    }
3367                }
3368            }
3369        });
3370    }
3371
3372    @Override
3373    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3374            final IntentSender pi) {
3375        mContext.enforceCallingOrSelfPermission(
3376                android.Manifest.permission.CLEAR_APP_CACHE, null);
3377        // Queue up an async operation since clearing cache may take a little while.
3378        mHandler.post(new Runnable() {
3379            public void run() {
3380                mHandler.removeCallbacks(this);
3381                boolean success = true;
3382                synchronized (mInstallLock) {
3383                    try {
3384                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3385                    } catch (InstallerException e) {
3386                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3387                        success = false;
3388                    }
3389                }
3390                if(pi != null) {
3391                    try {
3392                        // Callback via pending intent
3393                        int code = success ? 1 : 0;
3394                        pi.sendIntent(null, code, null,
3395                                null, null);
3396                    } catch (SendIntentException e1) {
3397                        Slog.i(TAG, "Failed to send pending intent");
3398                    }
3399                }
3400            }
3401        });
3402    }
3403
3404    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3405        synchronized (mInstallLock) {
3406            try {
3407                mInstaller.freeCache(volumeUuid, freeStorageSize);
3408            } catch (InstallerException e) {
3409                throw new IOException("Failed to free enough space", e);
3410            }
3411        }
3412    }
3413
3414    /**
3415     * Update given flags based on encryption status of current user.
3416     */
3417    private int updateFlags(int flags, int userId) {
3418        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3419                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3420            // Caller expressed an explicit opinion about what encryption
3421            // aware/unaware components they want to see, so fall through and
3422            // give them what they want
3423        } else {
3424            // Caller expressed no opinion, so match based on user state
3425            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3426                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3427            } else {
3428                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3429            }
3430        }
3431        return flags;
3432    }
3433
3434    private UserManagerInternal getUserManagerInternal() {
3435        if (mUserManagerInternal == null) {
3436            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3437        }
3438        return mUserManagerInternal;
3439    }
3440
3441    /**
3442     * Update given flags when being used to request {@link PackageInfo}.
3443     */
3444    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3445        boolean triaged = true;
3446        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3447                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3448            // Caller is asking for component details, so they'd better be
3449            // asking for specific encryption matching behavior, or be triaged
3450            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3451                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3452                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3453                triaged = false;
3454            }
3455        }
3456        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3457                | PackageManager.MATCH_SYSTEM_ONLY
3458                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3459            triaged = false;
3460        }
3461        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3462            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3463                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3464        }
3465        return updateFlags(flags, userId);
3466    }
3467
3468    /**
3469     * Update given flags when being used to request {@link ApplicationInfo}.
3470     */
3471    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3472        return updateFlagsForPackage(flags, userId, cookie);
3473    }
3474
3475    /**
3476     * Update given flags when being used to request {@link ComponentInfo}.
3477     */
3478    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3479        if (cookie instanceof Intent) {
3480            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3481                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3482            }
3483        }
3484
3485        boolean triaged = true;
3486        // Caller is asking for component details, so they'd better be
3487        // asking for specific encryption matching behavior, or be triaged
3488        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3489                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3490                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3491            triaged = false;
3492        }
3493        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3494            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3495                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3496        }
3497
3498        return updateFlags(flags, userId);
3499    }
3500
3501    /**
3502     * Update given flags when being used to request {@link ResolveInfo}.
3503     */
3504    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3505        // Safe mode means we shouldn't match any third-party components
3506        if (mSafeMode) {
3507            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3508        }
3509
3510        return updateFlagsForComponent(flags, userId, cookie);
3511    }
3512
3513    @Override
3514    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3515        if (!sUserManager.exists(userId)) return null;
3516        flags = updateFlagsForComponent(flags, userId, component);
3517        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3518                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3519        synchronized (mPackages) {
3520            PackageParser.Activity a = mActivities.mActivities.get(component);
3521
3522            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3523            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3524                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3525                if (ps == null) return null;
3526                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3527                        userId);
3528            }
3529            if (mResolveComponentName.equals(component)) {
3530                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3531                        new PackageUserState(), userId);
3532            }
3533        }
3534        return null;
3535    }
3536
3537    @Override
3538    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3539            String resolvedType) {
3540        synchronized (mPackages) {
3541            if (component.equals(mResolveComponentName)) {
3542                // The resolver supports EVERYTHING!
3543                return true;
3544            }
3545            PackageParser.Activity a = mActivities.mActivities.get(component);
3546            if (a == null) {
3547                return false;
3548            }
3549            for (int i=0; i<a.intents.size(); i++) {
3550                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3551                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3552                    return true;
3553                }
3554            }
3555            return false;
3556        }
3557    }
3558
3559    @Override
3560    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3561        if (!sUserManager.exists(userId)) return null;
3562        flags = updateFlagsForComponent(flags, userId, component);
3563        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3564                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3565        synchronized (mPackages) {
3566            PackageParser.Activity a = mReceivers.mActivities.get(component);
3567            if (DEBUG_PACKAGE_INFO) Log.v(
3568                TAG, "getReceiverInfo " + component + ": " + a);
3569            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3570                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3571                if (ps == null) return null;
3572                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3573                        userId);
3574            }
3575        }
3576        return null;
3577    }
3578
3579    @Override
3580    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3581        if (!sUserManager.exists(userId)) return null;
3582        flags = updateFlagsForComponent(flags, userId, component);
3583        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3584                false /* requireFullPermission */, false /* checkShell */, "get service info");
3585        synchronized (mPackages) {
3586            PackageParser.Service s = mServices.mServices.get(component);
3587            if (DEBUG_PACKAGE_INFO) Log.v(
3588                TAG, "getServiceInfo " + component + ": " + s);
3589            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3590                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3591                if (ps == null) return null;
3592                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3593                        userId);
3594            }
3595        }
3596        return null;
3597    }
3598
3599    @Override
3600    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3601        if (!sUserManager.exists(userId)) return null;
3602        flags = updateFlagsForComponent(flags, userId, component);
3603        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3604                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3605        synchronized (mPackages) {
3606            PackageParser.Provider p = mProviders.mProviders.get(component);
3607            if (DEBUG_PACKAGE_INFO) Log.v(
3608                TAG, "getProviderInfo " + component + ": " + p);
3609            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3610                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3611                if (ps == null) return null;
3612                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3613                        userId);
3614            }
3615        }
3616        return null;
3617    }
3618
3619    @Override
3620    public String[] getSystemSharedLibraryNames() {
3621        Set<String> libSet;
3622        synchronized (mPackages) {
3623            libSet = mSharedLibraries.keySet();
3624            int size = libSet.size();
3625            if (size > 0) {
3626                String[] libs = new String[size];
3627                libSet.toArray(libs);
3628                return libs;
3629            }
3630        }
3631        return null;
3632    }
3633
3634    @Override
3635    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3636        synchronized (mPackages) {
3637            return mServicesSystemSharedLibraryPackageName;
3638        }
3639    }
3640
3641    @Override
3642    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3643        synchronized (mPackages) {
3644            return mSharedSystemSharedLibraryPackageName;
3645        }
3646    }
3647
3648    @Override
3649    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3650        synchronized (mPackages) {
3651            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3652
3653            final FeatureInfo fi = new FeatureInfo();
3654            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3655                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3656            res.add(fi);
3657
3658            return new ParceledListSlice<>(res);
3659        }
3660    }
3661
3662    @Override
3663    public boolean hasSystemFeature(String name, int version) {
3664        synchronized (mPackages) {
3665            final FeatureInfo feat = mAvailableFeatures.get(name);
3666            if (feat == null) {
3667                return false;
3668            } else {
3669                return feat.version >= version;
3670            }
3671        }
3672    }
3673
3674    @Override
3675    public int checkPermission(String permName, String pkgName, int userId) {
3676        if (!sUserManager.exists(userId)) {
3677            return PackageManager.PERMISSION_DENIED;
3678        }
3679
3680        synchronized (mPackages) {
3681            final PackageParser.Package p = mPackages.get(pkgName);
3682            if (p != null && p.mExtras != null) {
3683                final PackageSetting ps = (PackageSetting) p.mExtras;
3684                final PermissionsState permissionsState = ps.getPermissionsState();
3685                if (permissionsState.hasPermission(permName, userId)) {
3686                    return PackageManager.PERMISSION_GRANTED;
3687                }
3688                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3689                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3690                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3691                    return PackageManager.PERMISSION_GRANTED;
3692                }
3693            }
3694        }
3695
3696        return PackageManager.PERMISSION_DENIED;
3697    }
3698
3699    @Override
3700    public int checkUidPermission(String permName, int uid) {
3701        final int userId = UserHandle.getUserId(uid);
3702
3703        if (!sUserManager.exists(userId)) {
3704            return PackageManager.PERMISSION_DENIED;
3705        }
3706
3707        synchronized (mPackages) {
3708            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3709            if (obj != null) {
3710                final SettingBase ps = (SettingBase) obj;
3711                final PermissionsState permissionsState = ps.getPermissionsState();
3712                if (permissionsState.hasPermission(permName, userId)) {
3713                    return PackageManager.PERMISSION_GRANTED;
3714                }
3715                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3716                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3717                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3718                    return PackageManager.PERMISSION_GRANTED;
3719                }
3720            } else {
3721                ArraySet<String> perms = mSystemPermissions.get(uid);
3722                if (perms != null) {
3723                    if (perms.contains(permName)) {
3724                        return PackageManager.PERMISSION_GRANTED;
3725                    }
3726                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3727                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3728                        return PackageManager.PERMISSION_GRANTED;
3729                    }
3730                }
3731            }
3732        }
3733
3734        return PackageManager.PERMISSION_DENIED;
3735    }
3736
3737    @Override
3738    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3739        if (UserHandle.getCallingUserId() != userId) {
3740            mContext.enforceCallingPermission(
3741                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3742                    "isPermissionRevokedByPolicy for user " + userId);
3743        }
3744
3745        if (checkPermission(permission, packageName, userId)
3746                == PackageManager.PERMISSION_GRANTED) {
3747            return false;
3748        }
3749
3750        final long identity = Binder.clearCallingIdentity();
3751        try {
3752            final int flags = getPermissionFlags(permission, packageName, userId);
3753            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3754        } finally {
3755            Binder.restoreCallingIdentity(identity);
3756        }
3757    }
3758
3759    @Override
3760    public String getPermissionControllerPackageName() {
3761        synchronized (mPackages) {
3762            return mRequiredInstallerPackage;
3763        }
3764    }
3765
3766    /**
3767     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3768     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3769     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3770     * @param message the message to log on security exception
3771     */
3772    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3773            boolean checkShell, String message) {
3774        if (userId < 0) {
3775            throw new IllegalArgumentException("Invalid userId " + userId);
3776        }
3777        if (checkShell) {
3778            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3779        }
3780        if (userId == UserHandle.getUserId(callingUid)) return;
3781        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3782            if (requireFullPermission) {
3783                mContext.enforceCallingOrSelfPermission(
3784                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3785            } else {
3786                try {
3787                    mContext.enforceCallingOrSelfPermission(
3788                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3789                } catch (SecurityException se) {
3790                    mContext.enforceCallingOrSelfPermission(
3791                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3792                }
3793            }
3794        }
3795    }
3796
3797    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3798        if (callingUid == Process.SHELL_UID) {
3799            if (userHandle >= 0
3800                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3801                throw new SecurityException("Shell does not have permission to access user "
3802                        + userHandle);
3803            } else if (userHandle < 0) {
3804                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3805                        + Debug.getCallers(3));
3806            }
3807        }
3808    }
3809
3810    private BasePermission findPermissionTreeLP(String permName) {
3811        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3812            if (permName.startsWith(bp.name) &&
3813                    permName.length() > bp.name.length() &&
3814                    permName.charAt(bp.name.length()) == '.') {
3815                return bp;
3816            }
3817        }
3818        return null;
3819    }
3820
3821    private BasePermission checkPermissionTreeLP(String permName) {
3822        if (permName != null) {
3823            BasePermission bp = findPermissionTreeLP(permName);
3824            if (bp != null) {
3825                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3826                    return bp;
3827                }
3828                throw new SecurityException("Calling uid "
3829                        + Binder.getCallingUid()
3830                        + " is not allowed to add to permission tree "
3831                        + bp.name + " owned by uid " + bp.uid);
3832            }
3833        }
3834        throw new SecurityException("No permission tree found for " + permName);
3835    }
3836
3837    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3838        if (s1 == null) {
3839            return s2 == null;
3840        }
3841        if (s2 == null) {
3842            return false;
3843        }
3844        if (s1.getClass() != s2.getClass()) {
3845            return false;
3846        }
3847        return s1.equals(s2);
3848    }
3849
3850    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3851        if (pi1.icon != pi2.icon) return false;
3852        if (pi1.logo != pi2.logo) return false;
3853        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3854        if (!compareStrings(pi1.name, pi2.name)) return false;
3855        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3856        // We'll take care of setting this one.
3857        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3858        // These are not currently stored in settings.
3859        //if (!compareStrings(pi1.group, pi2.group)) return false;
3860        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3861        //if (pi1.labelRes != pi2.labelRes) return false;
3862        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3863        return true;
3864    }
3865
3866    int permissionInfoFootprint(PermissionInfo info) {
3867        int size = info.name.length();
3868        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3869        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3870        return size;
3871    }
3872
3873    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3874        int size = 0;
3875        for (BasePermission perm : mSettings.mPermissions.values()) {
3876            if (perm.uid == tree.uid) {
3877                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3878            }
3879        }
3880        return size;
3881    }
3882
3883    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3884        // We calculate the max size of permissions defined by this uid and throw
3885        // if that plus the size of 'info' would exceed our stated maximum.
3886        if (tree.uid != Process.SYSTEM_UID) {
3887            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3888            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3889                throw new SecurityException("Permission tree size cap exceeded");
3890            }
3891        }
3892    }
3893
3894    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3895        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3896            throw new SecurityException("Label must be specified in permission");
3897        }
3898        BasePermission tree = checkPermissionTreeLP(info.name);
3899        BasePermission bp = mSettings.mPermissions.get(info.name);
3900        boolean added = bp == null;
3901        boolean changed = true;
3902        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3903        if (added) {
3904            enforcePermissionCapLocked(info, tree);
3905            bp = new BasePermission(info.name, tree.sourcePackage,
3906                    BasePermission.TYPE_DYNAMIC);
3907        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3908            throw new SecurityException(
3909                    "Not allowed to modify non-dynamic permission "
3910                    + info.name);
3911        } else {
3912            if (bp.protectionLevel == fixedLevel
3913                    && bp.perm.owner.equals(tree.perm.owner)
3914                    && bp.uid == tree.uid
3915                    && comparePermissionInfos(bp.perm.info, info)) {
3916                changed = false;
3917            }
3918        }
3919        bp.protectionLevel = fixedLevel;
3920        info = new PermissionInfo(info);
3921        info.protectionLevel = fixedLevel;
3922        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3923        bp.perm.info.packageName = tree.perm.info.packageName;
3924        bp.uid = tree.uid;
3925        if (added) {
3926            mSettings.mPermissions.put(info.name, bp);
3927        }
3928        if (changed) {
3929            if (!async) {
3930                mSettings.writeLPr();
3931            } else {
3932                scheduleWriteSettingsLocked();
3933            }
3934        }
3935        return added;
3936    }
3937
3938    @Override
3939    public boolean addPermission(PermissionInfo info) {
3940        synchronized (mPackages) {
3941            return addPermissionLocked(info, false);
3942        }
3943    }
3944
3945    @Override
3946    public boolean addPermissionAsync(PermissionInfo info) {
3947        synchronized (mPackages) {
3948            return addPermissionLocked(info, true);
3949        }
3950    }
3951
3952    @Override
3953    public void removePermission(String name) {
3954        synchronized (mPackages) {
3955            checkPermissionTreeLP(name);
3956            BasePermission bp = mSettings.mPermissions.get(name);
3957            if (bp != null) {
3958                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3959                    throw new SecurityException(
3960                            "Not allowed to modify non-dynamic permission "
3961                            + name);
3962                }
3963                mSettings.mPermissions.remove(name);
3964                mSettings.writeLPr();
3965            }
3966        }
3967    }
3968
3969    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3970            BasePermission bp) {
3971        int index = pkg.requestedPermissions.indexOf(bp.name);
3972        if (index == -1) {
3973            throw new SecurityException("Package " + pkg.packageName
3974                    + " has not requested permission " + bp.name);
3975        }
3976        if (!bp.isRuntime() && !bp.isDevelopment()) {
3977            throw new SecurityException("Permission " + bp.name
3978                    + " is not a changeable permission type");
3979        }
3980    }
3981
3982    @Override
3983    public void grantRuntimePermission(String packageName, String name, final int userId) {
3984        if (!sUserManager.exists(userId)) {
3985            Log.e(TAG, "No such user:" + userId);
3986            return;
3987        }
3988
3989        mContext.enforceCallingOrSelfPermission(
3990                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3991                "grantRuntimePermission");
3992
3993        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3994                true /* requireFullPermission */, true /* checkShell */,
3995                "grantRuntimePermission");
3996
3997        final int uid;
3998        final SettingBase sb;
3999
4000        synchronized (mPackages) {
4001            final PackageParser.Package pkg = mPackages.get(packageName);
4002            if (pkg == null) {
4003                throw new IllegalArgumentException("Unknown package: " + packageName);
4004            }
4005
4006            final BasePermission bp = mSettings.mPermissions.get(name);
4007            if (bp == null) {
4008                throw new IllegalArgumentException("Unknown permission: " + name);
4009            }
4010
4011            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4012
4013            // If a permission review is required for legacy apps we represent
4014            // their permissions as always granted runtime ones since we need
4015            // to keep the review required permission flag per user while an
4016            // install permission's state is shared across all users.
4017            if (Build.PERMISSIONS_REVIEW_REQUIRED
4018                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4019                    && bp.isRuntime()) {
4020                return;
4021            }
4022
4023            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4024            sb = (SettingBase) pkg.mExtras;
4025            if (sb == null) {
4026                throw new IllegalArgumentException("Unknown package: " + packageName);
4027            }
4028
4029            final PermissionsState permissionsState = sb.getPermissionsState();
4030
4031            final int flags = permissionsState.getPermissionFlags(name, userId);
4032            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4033                throw new SecurityException("Cannot grant system fixed permission "
4034                        + name + " for package " + packageName);
4035            }
4036
4037            if (bp.isDevelopment()) {
4038                // Development permissions must be handled specially, since they are not
4039                // normal runtime permissions.  For now they apply to all users.
4040                if (permissionsState.grantInstallPermission(bp) !=
4041                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4042                    scheduleWriteSettingsLocked();
4043                }
4044                return;
4045            }
4046
4047            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4048                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4049                return;
4050            }
4051
4052            final int result = permissionsState.grantRuntimePermission(bp, userId);
4053            switch (result) {
4054                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4055                    return;
4056                }
4057
4058                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4059                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4060                    mHandler.post(new Runnable() {
4061                        @Override
4062                        public void run() {
4063                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4064                        }
4065                    });
4066                }
4067                break;
4068            }
4069
4070            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4071
4072            // Not critical if that is lost - app has to request again.
4073            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4074        }
4075
4076        // Only need to do this if user is initialized. Otherwise it's a new user
4077        // and there are no processes running as the user yet and there's no need
4078        // to make an expensive call to remount processes for the changed permissions.
4079        if (READ_EXTERNAL_STORAGE.equals(name)
4080                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4081            final long token = Binder.clearCallingIdentity();
4082            try {
4083                if (sUserManager.isInitialized(userId)) {
4084                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4085                            MountServiceInternal.class);
4086                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4087                }
4088            } finally {
4089                Binder.restoreCallingIdentity(token);
4090            }
4091        }
4092    }
4093
4094    @Override
4095    public void revokeRuntimePermission(String packageName, String name, int userId) {
4096        if (!sUserManager.exists(userId)) {
4097            Log.e(TAG, "No such user:" + userId);
4098            return;
4099        }
4100
4101        mContext.enforceCallingOrSelfPermission(
4102                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4103                "revokeRuntimePermission");
4104
4105        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4106                true /* requireFullPermission */, true /* checkShell */,
4107                "revokeRuntimePermission");
4108
4109        final int appId;
4110
4111        synchronized (mPackages) {
4112            final PackageParser.Package pkg = mPackages.get(packageName);
4113            if (pkg == null) {
4114                throw new IllegalArgumentException("Unknown package: " + packageName);
4115            }
4116
4117            final BasePermission bp = mSettings.mPermissions.get(name);
4118            if (bp == null) {
4119                throw new IllegalArgumentException("Unknown permission: " + name);
4120            }
4121
4122            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4123
4124            // If a permission review is required for legacy apps we represent
4125            // their permissions as always granted runtime ones since we need
4126            // to keep the review required permission flag per user while an
4127            // install permission's state is shared across all users.
4128            if (Build.PERMISSIONS_REVIEW_REQUIRED
4129                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4130                    && bp.isRuntime()) {
4131                return;
4132            }
4133
4134            SettingBase sb = (SettingBase) pkg.mExtras;
4135            if (sb == null) {
4136                throw new IllegalArgumentException("Unknown package: " + packageName);
4137            }
4138
4139            final PermissionsState permissionsState = sb.getPermissionsState();
4140
4141            final int flags = permissionsState.getPermissionFlags(name, userId);
4142            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4143                throw new SecurityException("Cannot revoke system fixed permission "
4144                        + name + " for package " + packageName);
4145            }
4146
4147            if (bp.isDevelopment()) {
4148                // Development permissions must be handled specially, since they are not
4149                // normal runtime permissions.  For now they apply to all users.
4150                if (permissionsState.revokeInstallPermission(bp) !=
4151                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4152                    scheduleWriteSettingsLocked();
4153                }
4154                return;
4155            }
4156
4157            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4158                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4159                return;
4160            }
4161
4162            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4163
4164            // Critical, after this call app should never have the permission.
4165            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4166
4167            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4168        }
4169
4170        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4171    }
4172
4173    @Override
4174    public void resetRuntimePermissions() {
4175        mContext.enforceCallingOrSelfPermission(
4176                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4177                "revokeRuntimePermission");
4178
4179        int callingUid = Binder.getCallingUid();
4180        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4181            mContext.enforceCallingOrSelfPermission(
4182                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4183                    "resetRuntimePermissions");
4184        }
4185
4186        synchronized (mPackages) {
4187            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4188            for (int userId : UserManagerService.getInstance().getUserIds()) {
4189                final int packageCount = mPackages.size();
4190                for (int i = 0; i < packageCount; i++) {
4191                    PackageParser.Package pkg = mPackages.valueAt(i);
4192                    if (!(pkg.mExtras instanceof PackageSetting)) {
4193                        continue;
4194                    }
4195                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4196                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4197                }
4198            }
4199        }
4200    }
4201
4202    @Override
4203    public int getPermissionFlags(String name, String packageName, int userId) {
4204        if (!sUserManager.exists(userId)) {
4205            return 0;
4206        }
4207
4208        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4209
4210        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4211                true /* requireFullPermission */, false /* checkShell */,
4212                "getPermissionFlags");
4213
4214        synchronized (mPackages) {
4215            final PackageParser.Package pkg = mPackages.get(packageName);
4216            if (pkg == null) {
4217                return 0;
4218            }
4219
4220            final BasePermission bp = mSettings.mPermissions.get(name);
4221            if (bp == null) {
4222                return 0;
4223            }
4224
4225            SettingBase sb = (SettingBase) pkg.mExtras;
4226            if (sb == null) {
4227                return 0;
4228            }
4229
4230            PermissionsState permissionsState = sb.getPermissionsState();
4231            return permissionsState.getPermissionFlags(name, userId);
4232        }
4233    }
4234
4235    @Override
4236    public void updatePermissionFlags(String name, String packageName, int flagMask,
4237            int flagValues, int userId) {
4238        if (!sUserManager.exists(userId)) {
4239            return;
4240        }
4241
4242        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4243
4244        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4245                true /* requireFullPermission */, true /* checkShell */,
4246                "updatePermissionFlags");
4247
4248        // Only the system can change these flags and nothing else.
4249        if (getCallingUid() != Process.SYSTEM_UID) {
4250            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4251            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4252            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4253            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4254            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4255        }
4256
4257        synchronized (mPackages) {
4258            final PackageParser.Package pkg = mPackages.get(packageName);
4259            if (pkg == null) {
4260                throw new IllegalArgumentException("Unknown package: " + packageName);
4261            }
4262
4263            final BasePermission bp = mSettings.mPermissions.get(name);
4264            if (bp == null) {
4265                throw new IllegalArgumentException("Unknown permission: " + name);
4266            }
4267
4268            SettingBase sb = (SettingBase) pkg.mExtras;
4269            if (sb == null) {
4270                throw new IllegalArgumentException("Unknown package: " + packageName);
4271            }
4272
4273            PermissionsState permissionsState = sb.getPermissionsState();
4274
4275            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4276
4277            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4278                // Install and runtime permissions are stored in different places,
4279                // so figure out what permission changed and persist the change.
4280                if (permissionsState.getInstallPermissionState(name) != null) {
4281                    scheduleWriteSettingsLocked();
4282                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4283                        || hadState) {
4284                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4285                }
4286            }
4287        }
4288    }
4289
4290    /**
4291     * Update the permission flags for all packages and runtime permissions of a user in order
4292     * to allow device or profile owner to remove POLICY_FIXED.
4293     */
4294    @Override
4295    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4296        if (!sUserManager.exists(userId)) {
4297            return;
4298        }
4299
4300        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4301
4302        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4303                true /* requireFullPermission */, true /* checkShell */,
4304                "updatePermissionFlagsForAllApps");
4305
4306        // Only the system can change system fixed flags.
4307        if (getCallingUid() != Process.SYSTEM_UID) {
4308            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4309            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4310        }
4311
4312        synchronized (mPackages) {
4313            boolean changed = false;
4314            final int packageCount = mPackages.size();
4315            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4316                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4317                SettingBase sb = (SettingBase) pkg.mExtras;
4318                if (sb == null) {
4319                    continue;
4320                }
4321                PermissionsState permissionsState = sb.getPermissionsState();
4322                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4323                        userId, flagMask, flagValues);
4324            }
4325            if (changed) {
4326                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4327            }
4328        }
4329    }
4330
4331    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4332        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4333                != PackageManager.PERMISSION_GRANTED
4334            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4335                != PackageManager.PERMISSION_GRANTED) {
4336            throw new SecurityException(message + " requires "
4337                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4338                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4339        }
4340    }
4341
4342    @Override
4343    public boolean shouldShowRequestPermissionRationale(String permissionName,
4344            String packageName, int userId) {
4345        if (UserHandle.getCallingUserId() != userId) {
4346            mContext.enforceCallingPermission(
4347                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4348                    "canShowRequestPermissionRationale for user " + userId);
4349        }
4350
4351        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4352        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4353            return false;
4354        }
4355
4356        if (checkPermission(permissionName, packageName, userId)
4357                == PackageManager.PERMISSION_GRANTED) {
4358            return false;
4359        }
4360
4361        final int flags;
4362
4363        final long identity = Binder.clearCallingIdentity();
4364        try {
4365            flags = getPermissionFlags(permissionName,
4366                    packageName, userId);
4367        } finally {
4368            Binder.restoreCallingIdentity(identity);
4369        }
4370
4371        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4372                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4373                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4374
4375        if ((flags & fixedFlags) != 0) {
4376            return false;
4377        }
4378
4379        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4380    }
4381
4382    @Override
4383    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4384        mContext.enforceCallingOrSelfPermission(
4385                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4386                "addOnPermissionsChangeListener");
4387
4388        synchronized (mPackages) {
4389            mOnPermissionChangeListeners.addListenerLocked(listener);
4390        }
4391    }
4392
4393    @Override
4394    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4395        synchronized (mPackages) {
4396            mOnPermissionChangeListeners.removeListenerLocked(listener);
4397        }
4398    }
4399
4400    @Override
4401    public boolean isProtectedBroadcast(String actionName) {
4402        synchronized (mPackages) {
4403            if (mProtectedBroadcasts.contains(actionName)) {
4404                return true;
4405            } else if (actionName != null) {
4406                // TODO: remove these terrible hacks
4407                if (actionName.startsWith("android.net.netmon.lingerExpired")
4408                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4409                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4410                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4411                    return true;
4412                }
4413            }
4414        }
4415        return false;
4416    }
4417
4418    @Override
4419    public int checkSignatures(String pkg1, String pkg2) {
4420        synchronized (mPackages) {
4421            final PackageParser.Package p1 = mPackages.get(pkg1);
4422            final PackageParser.Package p2 = mPackages.get(pkg2);
4423            if (p1 == null || p1.mExtras == null
4424                    || p2 == null || p2.mExtras == null) {
4425                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4426            }
4427            return compareSignatures(p1.mSignatures, p2.mSignatures);
4428        }
4429    }
4430
4431    @Override
4432    public int checkUidSignatures(int uid1, int uid2) {
4433        // Map to base uids.
4434        uid1 = UserHandle.getAppId(uid1);
4435        uid2 = UserHandle.getAppId(uid2);
4436        // reader
4437        synchronized (mPackages) {
4438            Signature[] s1;
4439            Signature[] s2;
4440            Object obj = mSettings.getUserIdLPr(uid1);
4441            if (obj != null) {
4442                if (obj instanceof SharedUserSetting) {
4443                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4444                } else if (obj instanceof PackageSetting) {
4445                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4446                } else {
4447                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4448                }
4449            } else {
4450                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4451            }
4452            obj = mSettings.getUserIdLPr(uid2);
4453            if (obj != null) {
4454                if (obj instanceof SharedUserSetting) {
4455                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4456                } else if (obj instanceof PackageSetting) {
4457                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4458                } else {
4459                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4460                }
4461            } else {
4462                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4463            }
4464            return compareSignatures(s1, s2);
4465        }
4466    }
4467
4468    /**
4469     * This method should typically only be used when granting or revoking
4470     * permissions, since the app may immediately restart after this call.
4471     * <p>
4472     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4473     * guard your work against the app being relaunched.
4474     */
4475    private void killUid(int appId, int userId, String reason) {
4476        final long identity = Binder.clearCallingIdentity();
4477        try {
4478            IActivityManager am = ActivityManagerNative.getDefault();
4479            if (am != null) {
4480                try {
4481                    am.killUid(appId, userId, reason);
4482                } catch (RemoteException e) {
4483                    /* ignore - same process */
4484                }
4485            }
4486        } finally {
4487            Binder.restoreCallingIdentity(identity);
4488        }
4489    }
4490
4491    /**
4492     * Compares two sets of signatures. Returns:
4493     * <br />
4494     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4495     * <br />
4496     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4497     * <br />
4498     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4499     * <br />
4500     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4501     * <br />
4502     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4503     */
4504    static int compareSignatures(Signature[] s1, Signature[] s2) {
4505        if (s1 == null) {
4506            return s2 == null
4507                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4508                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4509        }
4510
4511        if (s2 == null) {
4512            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4513        }
4514
4515        if (s1.length != s2.length) {
4516            return PackageManager.SIGNATURE_NO_MATCH;
4517        }
4518
4519        // Since both signature sets are of size 1, we can compare without HashSets.
4520        if (s1.length == 1) {
4521            return s1[0].equals(s2[0]) ?
4522                    PackageManager.SIGNATURE_MATCH :
4523                    PackageManager.SIGNATURE_NO_MATCH;
4524        }
4525
4526        ArraySet<Signature> set1 = new ArraySet<Signature>();
4527        for (Signature sig : s1) {
4528            set1.add(sig);
4529        }
4530        ArraySet<Signature> set2 = new ArraySet<Signature>();
4531        for (Signature sig : s2) {
4532            set2.add(sig);
4533        }
4534        // Make sure s2 contains all signatures in s1.
4535        if (set1.equals(set2)) {
4536            return PackageManager.SIGNATURE_MATCH;
4537        }
4538        return PackageManager.SIGNATURE_NO_MATCH;
4539    }
4540
4541    /**
4542     * If the database version for this type of package (internal storage or
4543     * external storage) is less than the version where package signatures
4544     * were updated, return true.
4545     */
4546    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4547        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4548        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4549    }
4550
4551    /**
4552     * Used for backward compatibility to make sure any packages with
4553     * certificate chains get upgraded to the new style. {@code existingSigs}
4554     * will be in the old format (since they were stored on disk from before the
4555     * system upgrade) and {@code scannedSigs} will be in the newer format.
4556     */
4557    private int compareSignaturesCompat(PackageSignatures existingSigs,
4558            PackageParser.Package scannedPkg) {
4559        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4560            return PackageManager.SIGNATURE_NO_MATCH;
4561        }
4562
4563        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4564        for (Signature sig : existingSigs.mSignatures) {
4565            existingSet.add(sig);
4566        }
4567        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4568        for (Signature sig : scannedPkg.mSignatures) {
4569            try {
4570                Signature[] chainSignatures = sig.getChainSignatures();
4571                for (Signature chainSig : chainSignatures) {
4572                    scannedCompatSet.add(chainSig);
4573                }
4574            } catch (CertificateEncodingException e) {
4575                scannedCompatSet.add(sig);
4576            }
4577        }
4578        /*
4579         * Make sure the expanded scanned set contains all signatures in the
4580         * existing one.
4581         */
4582        if (scannedCompatSet.equals(existingSet)) {
4583            // Migrate the old signatures to the new scheme.
4584            existingSigs.assignSignatures(scannedPkg.mSignatures);
4585            // The new KeySets will be re-added later in the scanning process.
4586            synchronized (mPackages) {
4587                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4588            }
4589            return PackageManager.SIGNATURE_MATCH;
4590        }
4591        return PackageManager.SIGNATURE_NO_MATCH;
4592    }
4593
4594    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4595        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4596        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4597    }
4598
4599    private int compareSignaturesRecover(PackageSignatures existingSigs,
4600            PackageParser.Package scannedPkg) {
4601        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4602            return PackageManager.SIGNATURE_NO_MATCH;
4603        }
4604
4605        String msg = null;
4606        try {
4607            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4608                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4609                        + scannedPkg.packageName);
4610                return PackageManager.SIGNATURE_MATCH;
4611            }
4612        } catch (CertificateException e) {
4613            msg = e.getMessage();
4614        }
4615
4616        logCriticalInfo(Log.INFO,
4617                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4618        return PackageManager.SIGNATURE_NO_MATCH;
4619    }
4620
4621    @Override
4622    public List<String> getAllPackages() {
4623        synchronized (mPackages) {
4624            return new ArrayList<String>(mPackages.keySet());
4625        }
4626    }
4627
4628    @Override
4629    public String[] getPackagesForUid(int uid) {
4630        uid = UserHandle.getAppId(uid);
4631        // reader
4632        synchronized (mPackages) {
4633            Object obj = mSettings.getUserIdLPr(uid);
4634            if (obj instanceof SharedUserSetting) {
4635                final SharedUserSetting sus = (SharedUserSetting) obj;
4636                final int N = sus.packages.size();
4637                final String[] res = new String[N];
4638                for (int i = 0; i < N; i++) {
4639                    res[i] = sus.packages.valueAt(i).name;
4640                }
4641                return res;
4642            } else if (obj instanceof PackageSetting) {
4643                final PackageSetting ps = (PackageSetting) obj;
4644                return new String[] { ps.name };
4645            }
4646        }
4647        return null;
4648    }
4649
4650    @Override
4651    public String getNameForUid(int uid) {
4652        // reader
4653        synchronized (mPackages) {
4654            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4655            if (obj instanceof SharedUserSetting) {
4656                final SharedUserSetting sus = (SharedUserSetting) obj;
4657                return sus.name + ":" + sus.userId;
4658            } else if (obj instanceof PackageSetting) {
4659                final PackageSetting ps = (PackageSetting) obj;
4660                return ps.name;
4661            }
4662        }
4663        return null;
4664    }
4665
4666    @Override
4667    public int getUidForSharedUser(String sharedUserName) {
4668        if(sharedUserName == null) {
4669            return -1;
4670        }
4671        // reader
4672        synchronized (mPackages) {
4673            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4674            if (suid == null) {
4675                return -1;
4676            }
4677            return suid.userId;
4678        }
4679    }
4680
4681    @Override
4682    public int getFlagsForUid(int uid) {
4683        synchronized (mPackages) {
4684            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4685            if (obj instanceof SharedUserSetting) {
4686                final SharedUserSetting sus = (SharedUserSetting) obj;
4687                return sus.pkgFlags;
4688            } else if (obj instanceof PackageSetting) {
4689                final PackageSetting ps = (PackageSetting) obj;
4690                return ps.pkgFlags;
4691            }
4692        }
4693        return 0;
4694    }
4695
4696    @Override
4697    public int getPrivateFlagsForUid(int uid) {
4698        synchronized (mPackages) {
4699            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4700            if (obj instanceof SharedUserSetting) {
4701                final SharedUserSetting sus = (SharedUserSetting) obj;
4702                return sus.pkgPrivateFlags;
4703            } else if (obj instanceof PackageSetting) {
4704                final PackageSetting ps = (PackageSetting) obj;
4705                return ps.pkgPrivateFlags;
4706            }
4707        }
4708        return 0;
4709    }
4710
4711    @Override
4712    public boolean isUidPrivileged(int uid) {
4713        uid = UserHandle.getAppId(uid);
4714        // reader
4715        synchronized (mPackages) {
4716            Object obj = mSettings.getUserIdLPr(uid);
4717            if (obj instanceof SharedUserSetting) {
4718                final SharedUserSetting sus = (SharedUserSetting) obj;
4719                final Iterator<PackageSetting> it = sus.packages.iterator();
4720                while (it.hasNext()) {
4721                    if (it.next().isPrivileged()) {
4722                        return true;
4723                    }
4724                }
4725            } else if (obj instanceof PackageSetting) {
4726                final PackageSetting ps = (PackageSetting) obj;
4727                return ps.isPrivileged();
4728            }
4729        }
4730        return false;
4731    }
4732
4733    @Override
4734    public String[] getAppOpPermissionPackages(String permissionName) {
4735        synchronized (mPackages) {
4736            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4737            if (pkgs == null) {
4738                return null;
4739            }
4740            return pkgs.toArray(new String[pkgs.size()]);
4741        }
4742    }
4743
4744    @Override
4745    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4746            int flags, int userId) {
4747        try {
4748            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4749
4750            if (!sUserManager.exists(userId)) return null;
4751            flags = updateFlagsForResolve(flags, userId, intent);
4752            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4753                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4754
4755            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4756            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4757                    flags, userId);
4758            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4759
4760            final ResolveInfo bestChoice =
4761                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4762            return bestChoice;
4763        } finally {
4764            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4765        }
4766    }
4767
4768    @Override
4769    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4770            IntentFilter filter, int match, ComponentName activity) {
4771        final int userId = UserHandle.getCallingUserId();
4772        if (DEBUG_PREFERRED) {
4773            Log.v(TAG, "setLastChosenActivity intent=" + intent
4774                + " resolvedType=" + resolvedType
4775                + " flags=" + flags
4776                + " filter=" + filter
4777                + " match=" + match
4778                + " activity=" + activity);
4779            filter.dump(new PrintStreamPrinter(System.out), "    ");
4780        }
4781        intent.setComponent(null);
4782        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4783                userId);
4784        // Find any earlier preferred or last chosen entries and nuke them
4785        findPreferredActivity(intent, resolvedType,
4786                flags, query, 0, false, true, false, userId);
4787        // Add the new activity as the last chosen for this filter
4788        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4789                "Setting last chosen");
4790    }
4791
4792    @Override
4793    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4794        final int userId = UserHandle.getCallingUserId();
4795        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4796        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4797                userId);
4798        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4799                false, false, false, userId);
4800    }
4801
4802    private boolean isEphemeralDisabled() {
4803        // ephemeral apps have been disabled across the board
4804        if (DISABLE_EPHEMERAL_APPS) {
4805            return true;
4806        }
4807        // system isn't up yet; can't read settings, so, assume no ephemeral apps
4808        if (!mSystemReady) {
4809            return true;
4810        }
4811        // we can't get a content resolver until the system is ready; these checks must happen last
4812        final ContentResolver resolver = mContext.getContentResolver();
4813        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
4814            return true;
4815        }
4816        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
4817    }
4818
4819    private boolean isEphemeralAllowed(
4820            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4821            boolean skipPackageCheck) {
4822        // Short circuit and return early if possible.
4823        if (isEphemeralDisabled()) {
4824            return false;
4825        }
4826        final int callingUser = UserHandle.getCallingUserId();
4827        if (callingUser != UserHandle.USER_SYSTEM) {
4828            return false;
4829        }
4830        if (mEphemeralResolverConnection == null) {
4831            return false;
4832        }
4833        if (intent.getComponent() != null) {
4834            return false;
4835        }
4836        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4837            return false;
4838        }
4839        if (!skipPackageCheck && intent.getPackage() != null) {
4840            return false;
4841        }
4842        final boolean isWebUri = hasWebURI(intent);
4843        if (!isWebUri || intent.getData().getHost() == null) {
4844            return false;
4845        }
4846        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4847        synchronized (mPackages) {
4848            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4849            for (int n = 0; n < count; n++) {
4850                ResolveInfo info = resolvedActivities.get(n);
4851                String packageName = info.activityInfo.packageName;
4852                PackageSetting ps = mSettings.mPackages.get(packageName);
4853                if (ps != null) {
4854                    // Try to get the status from User settings first
4855                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4856                    int status = (int) (packedStatus >> 32);
4857                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4858                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4859                        if (DEBUG_EPHEMERAL) {
4860                            Slog.v(TAG, "DENY ephemeral apps;"
4861                                + " pkg: " + packageName + ", status: " + status);
4862                        }
4863                        return false;
4864                    }
4865                }
4866            }
4867        }
4868        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4869        return true;
4870    }
4871
4872    private static EphemeralResolveInfo getEphemeralResolveInfo(
4873            Context context, EphemeralResolverConnection resolverConnection, Intent intent,
4874            String resolvedType, int userId, String packageName) {
4875        final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(),
4876                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4877        final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(),
4878                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4879        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4880                ephemeralPrefixCount);
4881        final int[] shaPrefix = digest.getDigestPrefix();
4882        final byte[][] digestBytes = digest.getDigestBytes();
4883        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4884                resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask);
4885        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4886            // No hash prefix match; there are no ephemeral apps for this domain.
4887            return null;
4888        }
4889
4890        // Go in reverse order so we match the narrowest scope first.
4891        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4892            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4893                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4894                    continue;
4895                }
4896                final List<IntentFilter> filters = ephemeralApplication.getFilters();
4897                // No filters; this should never happen.
4898                if (filters.isEmpty()) {
4899                    continue;
4900                }
4901                if (packageName != null
4902                        && !packageName.equals(ephemeralApplication.getPackageName())) {
4903                    continue;
4904                }
4905                // We have a domain match; resolve the filters to see if anything matches.
4906                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4907                for (int j = filters.size() - 1; j >= 0; --j) {
4908                    final EphemeralResolveIntentInfo intentInfo =
4909                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4910                    ephemeralResolver.addFilter(intentInfo);
4911                }
4912                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4913                        intent, resolvedType, false /*defaultOnly*/, userId);
4914                if (!matchedResolveInfoList.isEmpty()) {
4915                    return matchedResolveInfoList.get(0);
4916                }
4917            }
4918        }
4919        // Hash or filter mis-match; no ephemeral apps for this domain.
4920        return null;
4921    }
4922
4923    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4924            int flags, List<ResolveInfo> query, int userId) {
4925        if (query != null) {
4926            final int N = query.size();
4927            if (N == 1) {
4928                return query.get(0);
4929            } else if (N > 1) {
4930                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4931                // If there is more than one activity with the same priority,
4932                // then let the user decide between them.
4933                ResolveInfo r0 = query.get(0);
4934                ResolveInfo r1 = query.get(1);
4935                if (DEBUG_INTENT_MATCHING || debug) {
4936                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4937                            + r1.activityInfo.name + "=" + r1.priority);
4938                }
4939                // If the first activity has a higher priority, or a different
4940                // default, then it is always desirable to pick it.
4941                if (r0.priority != r1.priority
4942                        || r0.preferredOrder != r1.preferredOrder
4943                        || r0.isDefault != r1.isDefault) {
4944                    return query.get(0);
4945                }
4946                // If we have saved a preference for a preferred activity for
4947                // this Intent, use that.
4948                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4949                        flags, query, r0.priority, true, false, debug, userId);
4950                if (ri != null) {
4951                    return ri;
4952                }
4953                ri = new ResolveInfo(mResolveInfo);
4954                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4955                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
4956                // If all of the options come from the same package, show the application's
4957                // label and icon instead of the generic resolver's.
4958                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
4959                // and then throw away the ResolveInfo itself, meaning that the caller loses
4960                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
4961                // a fallback for this case; we only set the target package's resources on
4962                // the ResolveInfo, not the ActivityInfo.
4963                final String intentPackage = intent.getPackage();
4964                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
4965                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
4966                    ri.resolvePackageName = intentPackage;
4967                    if (userNeedsBadging(userId)) {
4968                        ri.noResourceId = true;
4969                    } else {
4970                        ri.icon = appi.icon;
4971                    }
4972                    ri.iconResourceId = appi.icon;
4973                    ri.labelRes = appi.labelRes;
4974                }
4975                ri.activityInfo.applicationInfo = new ApplicationInfo(
4976                        ri.activityInfo.applicationInfo);
4977                if (userId != 0) {
4978                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4979                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4980                }
4981                // Make sure that the resolver is displayable in car mode
4982                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4983                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4984                return ri;
4985            }
4986        }
4987        return null;
4988    }
4989
4990    /**
4991     * Return true if the given list is not empty and all of its contents have
4992     * an activityInfo with the given package name.
4993     */
4994    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
4995        if (ArrayUtils.isEmpty(list)) {
4996            return false;
4997        }
4998        for (int i = 0, N = list.size(); i < N; i++) {
4999            final ResolveInfo ri = list.get(i);
5000            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5001            if (ai == null || !packageName.equals(ai.packageName)) {
5002                return false;
5003            }
5004        }
5005        return true;
5006    }
5007
5008    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5009            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5010        final int N = query.size();
5011        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5012                .get(userId);
5013        // Get the list of persistent preferred activities that handle the intent
5014        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5015        List<PersistentPreferredActivity> pprefs = ppir != null
5016                ? ppir.queryIntent(intent, resolvedType,
5017                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5018                : null;
5019        if (pprefs != null && pprefs.size() > 0) {
5020            final int M = pprefs.size();
5021            for (int i=0; i<M; i++) {
5022                final PersistentPreferredActivity ppa = pprefs.get(i);
5023                if (DEBUG_PREFERRED || debug) {
5024                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5025                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5026                            + "\n  component=" + ppa.mComponent);
5027                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5028                }
5029                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5030                        flags | MATCH_DISABLED_COMPONENTS, userId);
5031                if (DEBUG_PREFERRED || debug) {
5032                    Slog.v(TAG, "Found persistent preferred activity:");
5033                    if (ai != null) {
5034                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5035                    } else {
5036                        Slog.v(TAG, "  null");
5037                    }
5038                }
5039                if (ai == null) {
5040                    // This previously registered persistent preferred activity
5041                    // component is no longer known. Ignore it and do NOT remove it.
5042                    continue;
5043                }
5044                for (int j=0; j<N; j++) {
5045                    final ResolveInfo ri = query.get(j);
5046                    if (!ri.activityInfo.applicationInfo.packageName
5047                            .equals(ai.applicationInfo.packageName)) {
5048                        continue;
5049                    }
5050                    if (!ri.activityInfo.name.equals(ai.name)) {
5051                        continue;
5052                    }
5053                    //  Found a persistent preference that can handle the intent.
5054                    if (DEBUG_PREFERRED || debug) {
5055                        Slog.v(TAG, "Returning persistent preferred activity: " +
5056                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5057                    }
5058                    return ri;
5059                }
5060            }
5061        }
5062        return null;
5063    }
5064
5065    // TODO: handle preferred activities missing while user has amnesia
5066    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5067            List<ResolveInfo> query, int priority, boolean always,
5068            boolean removeMatches, boolean debug, int userId) {
5069        if (!sUserManager.exists(userId)) return null;
5070        flags = updateFlagsForResolve(flags, userId, intent);
5071        // writer
5072        synchronized (mPackages) {
5073            if (intent.getSelector() != null) {
5074                intent = intent.getSelector();
5075            }
5076            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5077
5078            // Try to find a matching persistent preferred activity.
5079            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5080                    debug, userId);
5081
5082            // If a persistent preferred activity matched, use it.
5083            if (pri != null) {
5084                return pri;
5085            }
5086
5087            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5088            // Get the list of preferred activities that handle the intent
5089            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5090            List<PreferredActivity> prefs = pir != null
5091                    ? pir.queryIntent(intent, resolvedType,
5092                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5093                    : null;
5094            if (prefs != null && prefs.size() > 0) {
5095                boolean changed = false;
5096                try {
5097                    // First figure out how good the original match set is.
5098                    // We will only allow preferred activities that came
5099                    // from the same match quality.
5100                    int match = 0;
5101
5102                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5103
5104                    final int N = query.size();
5105                    for (int j=0; j<N; j++) {
5106                        final ResolveInfo ri = query.get(j);
5107                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5108                                + ": 0x" + Integer.toHexString(match));
5109                        if (ri.match > match) {
5110                            match = ri.match;
5111                        }
5112                    }
5113
5114                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5115                            + Integer.toHexString(match));
5116
5117                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5118                    final int M = prefs.size();
5119                    for (int i=0; i<M; i++) {
5120                        final PreferredActivity pa = prefs.get(i);
5121                        if (DEBUG_PREFERRED || debug) {
5122                            Slog.v(TAG, "Checking PreferredActivity ds="
5123                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5124                                    + "\n  component=" + pa.mPref.mComponent);
5125                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5126                        }
5127                        if (pa.mPref.mMatch != match) {
5128                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5129                                    + Integer.toHexString(pa.mPref.mMatch));
5130                            continue;
5131                        }
5132                        // If it's not an "always" type preferred activity and that's what we're
5133                        // looking for, skip it.
5134                        if (always && !pa.mPref.mAlways) {
5135                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5136                            continue;
5137                        }
5138                        final ActivityInfo ai = getActivityInfo(
5139                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5140                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5141                                userId);
5142                        if (DEBUG_PREFERRED || debug) {
5143                            Slog.v(TAG, "Found preferred activity:");
5144                            if (ai != null) {
5145                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5146                            } else {
5147                                Slog.v(TAG, "  null");
5148                            }
5149                        }
5150                        if (ai == null) {
5151                            // This previously registered preferred activity
5152                            // component is no longer known.  Most likely an update
5153                            // to the app was installed and in the new version this
5154                            // component no longer exists.  Clean it up by removing
5155                            // it from the preferred activities list, and skip it.
5156                            Slog.w(TAG, "Removing dangling preferred activity: "
5157                                    + pa.mPref.mComponent);
5158                            pir.removeFilter(pa);
5159                            changed = true;
5160                            continue;
5161                        }
5162                        for (int j=0; j<N; j++) {
5163                            final ResolveInfo ri = query.get(j);
5164                            if (!ri.activityInfo.applicationInfo.packageName
5165                                    .equals(ai.applicationInfo.packageName)) {
5166                                continue;
5167                            }
5168                            if (!ri.activityInfo.name.equals(ai.name)) {
5169                                continue;
5170                            }
5171
5172                            if (removeMatches) {
5173                                pir.removeFilter(pa);
5174                                changed = true;
5175                                if (DEBUG_PREFERRED) {
5176                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5177                                }
5178                                break;
5179                            }
5180
5181                            // Okay we found a previously set preferred or last chosen app.
5182                            // If the result set is different from when this
5183                            // was created, we need to clear it and re-ask the
5184                            // user their preference, if we're looking for an "always" type entry.
5185                            if (always && !pa.mPref.sameSet(query)) {
5186                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5187                                        + intent + " type " + resolvedType);
5188                                if (DEBUG_PREFERRED) {
5189                                    Slog.v(TAG, "Removing preferred activity since set changed "
5190                                            + pa.mPref.mComponent);
5191                                }
5192                                pir.removeFilter(pa);
5193                                // Re-add the filter as a "last chosen" entry (!always)
5194                                PreferredActivity lastChosen = new PreferredActivity(
5195                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5196                                pir.addFilter(lastChosen);
5197                                changed = true;
5198                                return null;
5199                            }
5200
5201                            // Yay! Either the set matched or we're looking for the last chosen
5202                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5203                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5204                            return ri;
5205                        }
5206                    }
5207                } finally {
5208                    if (changed) {
5209                        if (DEBUG_PREFERRED) {
5210                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5211                        }
5212                        scheduleWritePackageRestrictionsLocked(userId);
5213                    }
5214                }
5215            }
5216        }
5217        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5218        return null;
5219    }
5220
5221    /*
5222     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5223     */
5224    @Override
5225    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5226            int targetUserId) {
5227        mContext.enforceCallingOrSelfPermission(
5228                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5229        List<CrossProfileIntentFilter> matches =
5230                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5231        if (matches != null) {
5232            int size = matches.size();
5233            for (int i = 0; i < size; i++) {
5234                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5235            }
5236        }
5237        if (hasWebURI(intent)) {
5238            // cross-profile app linking works only towards the parent.
5239            final UserInfo parent = getProfileParent(sourceUserId);
5240            synchronized(mPackages) {
5241                int flags = updateFlagsForResolve(0, parent.id, intent);
5242                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5243                        intent, resolvedType, flags, sourceUserId, parent.id);
5244                return xpDomainInfo != null;
5245            }
5246        }
5247        return false;
5248    }
5249
5250    private UserInfo getProfileParent(int userId) {
5251        final long identity = Binder.clearCallingIdentity();
5252        try {
5253            return sUserManager.getProfileParent(userId);
5254        } finally {
5255            Binder.restoreCallingIdentity(identity);
5256        }
5257    }
5258
5259    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5260            String resolvedType, int userId) {
5261        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5262        if (resolver != null) {
5263            return resolver.queryIntent(intent, resolvedType, false, userId);
5264        }
5265        return null;
5266    }
5267
5268    @Override
5269    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5270            String resolvedType, int flags, int userId) {
5271        try {
5272            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5273
5274            return new ParceledListSlice<>(
5275                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5276        } finally {
5277            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5278        }
5279    }
5280
5281    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5282            String resolvedType, int flags, int userId) {
5283        if (!sUserManager.exists(userId)) return Collections.emptyList();
5284        flags = updateFlagsForResolve(flags, userId, intent);
5285        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5286                false /* requireFullPermission */, false /* checkShell */,
5287                "query intent activities");
5288        ComponentName comp = intent.getComponent();
5289        if (comp == null) {
5290            if (intent.getSelector() != null) {
5291                intent = intent.getSelector();
5292                comp = intent.getComponent();
5293            }
5294        }
5295
5296        if (comp != null) {
5297            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5298            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5299            if (ai != null) {
5300                final ResolveInfo ri = new ResolveInfo();
5301                ri.activityInfo = ai;
5302                list.add(ri);
5303            }
5304            return list;
5305        }
5306
5307        // reader
5308        boolean sortResult = false;
5309        boolean addEphemeral = false;
5310        boolean matchEphemeralPackage = false;
5311        List<ResolveInfo> result;
5312        final String pkgName = intent.getPackage();
5313        synchronized (mPackages) {
5314            if (pkgName == null) {
5315                List<CrossProfileIntentFilter> matchingFilters =
5316                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5317                // Check for results that need to skip the current profile.
5318                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5319                        resolvedType, flags, userId);
5320                if (xpResolveInfo != null) {
5321                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5322                    xpResult.add(xpResolveInfo);
5323                    return filterIfNotSystemUser(xpResult, userId);
5324                }
5325
5326                // Check for results in the current profile.
5327                result = filterIfNotSystemUser(mActivities.queryIntent(
5328                        intent, resolvedType, flags, userId), userId);
5329                addEphemeral =
5330                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5331
5332                // Check for cross profile results.
5333                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5334                xpResolveInfo = queryCrossProfileIntents(
5335                        matchingFilters, intent, resolvedType, flags, userId,
5336                        hasNonNegativePriorityResult);
5337                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5338                    boolean isVisibleToUser = filterIfNotSystemUser(
5339                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5340                    if (isVisibleToUser) {
5341                        result.add(xpResolveInfo);
5342                        sortResult = true;
5343                    }
5344                }
5345                if (hasWebURI(intent)) {
5346                    CrossProfileDomainInfo xpDomainInfo = null;
5347                    final UserInfo parent = getProfileParent(userId);
5348                    if (parent != null) {
5349                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5350                                flags, userId, parent.id);
5351                    }
5352                    if (xpDomainInfo != null) {
5353                        if (xpResolveInfo != null) {
5354                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5355                            // in the result.
5356                            result.remove(xpResolveInfo);
5357                        }
5358                        if (result.size() == 0 && !addEphemeral) {
5359                            result.add(xpDomainInfo.resolveInfo);
5360                            return result;
5361                        }
5362                    }
5363                    if (result.size() > 1 || addEphemeral) {
5364                        result = filterCandidatesWithDomainPreferredActivitiesLPr(
5365                                intent, flags, result, xpDomainInfo, userId);
5366                        sortResult = true;
5367                    }
5368                }
5369            } else {
5370                final PackageParser.Package pkg = mPackages.get(pkgName);
5371                if (pkg != null) {
5372                    result = filterIfNotSystemUser(
5373                            mActivities.queryIntentForPackage(
5374                                    intent, resolvedType, flags, pkg.activities, userId),
5375                            userId);
5376                } else {
5377                    // the caller wants to resolve for a particular package; however, there
5378                    // were no installed results, so, try to find an ephemeral result
5379                    addEphemeral = isEphemeralAllowed(
5380                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5381                    matchEphemeralPackage = true;
5382                    result = new ArrayList<ResolveInfo>();
5383                }
5384            }
5385        }
5386        if (addEphemeral) {
5387            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5388            final EphemeralResolveInfo ai = getEphemeralResolveInfo(
5389                    mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5390                    matchEphemeralPackage ? pkgName : null);
5391            if (ai != null) {
5392                if (DEBUG_EPHEMERAL) {
5393                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5394                }
5395                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5396                ephemeralInstaller.ephemeralResolveInfo = ai;
5397                // make sure this resolver is the default
5398                ephemeralInstaller.isDefault = true;
5399                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5400                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5401                // add a non-generic filter
5402                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5403                ephemeralInstaller.filter.addDataPath(
5404                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5405                result.add(ephemeralInstaller);
5406            }
5407            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5408        }
5409        if (sortResult) {
5410            Collections.sort(result, mResolvePrioritySorter);
5411        }
5412        return result;
5413    }
5414
5415    private static class CrossProfileDomainInfo {
5416        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5417        ResolveInfo resolveInfo;
5418        /* Best domain verification status of the activities found in the other profile */
5419        int bestDomainVerificationStatus;
5420    }
5421
5422    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5423            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5424        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5425                sourceUserId)) {
5426            return null;
5427        }
5428        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5429                resolvedType, flags, parentUserId);
5430
5431        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5432            return null;
5433        }
5434        CrossProfileDomainInfo result = null;
5435        int size = resultTargetUser.size();
5436        for (int i = 0; i < size; i++) {
5437            ResolveInfo riTargetUser = resultTargetUser.get(i);
5438            // Intent filter verification is only for filters that specify a host. So don't return
5439            // those that handle all web uris.
5440            if (riTargetUser.handleAllWebDataURI) {
5441                continue;
5442            }
5443            String packageName = riTargetUser.activityInfo.packageName;
5444            PackageSetting ps = mSettings.mPackages.get(packageName);
5445            if (ps == null) {
5446                continue;
5447            }
5448            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5449            int status = (int)(verificationState >> 32);
5450            if (result == null) {
5451                result = new CrossProfileDomainInfo();
5452                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5453                        sourceUserId, parentUserId);
5454                result.bestDomainVerificationStatus = status;
5455            } else {
5456                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5457                        result.bestDomainVerificationStatus);
5458            }
5459        }
5460        // Don't consider matches with status NEVER across profiles.
5461        if (result != null && result.bestDomainVerificationStatus
5462                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5463            return null;
5464        }
5465        return result;
5466    }
5467
5468    /**
5469     * Verification statuses are ordered from the worse to the best, except for
5470     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5471     */
5472    private int bestDomainVerificationStatus(int status1, int status2) {
5473        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5474            return status2;
5475        }
5476        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5477            return status1;
5478        }
5479        return (int) MathUtils.max(status1, status2);
5480    }
5481
5482    private boolean isUserEnabled(int userId) {
5483        long callingId = Binder.clearCallingIdentity();
5484        try {
5485            UserInfo userInfo = sUserManager.getUserInfo(userId);
5486            return userInfo != null && userInfo.isEnabled();
5487        } finally {
5488            Binder.restoreCallingIdentity(callingId);
5489        }
5490    }
5491
5492    /**
5493     * Filter out activities with systemUserOnly flag set, when current user is not System.
5494     *
5495     * @return filtered list
5496     */
5497    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5498        if (userId == UserHandle.USER_SYSTEM) {
5499            return resolveInfos;
5500        }
5501        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5502            ResolveInfo info = resolveInfos.get(i);
5503            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5504                resolveInfos.remove(i);
5505            }
5506        }
5507        return resolveInfos;
5508    }
5509
5510    /**
5511     * @param resolveInfos list of resolve infos in descending priority order
5512     * @return if the list contains a resolve info with non-negative priority
5513     */
5514    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5515        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5516    }
5517
5518    private static boolean hasWebURI(Intent intent) {
5519        if (intent.getData() == null) {
5520            return false;
5521        }
5522        final String scheme = intent.getScheme();
5523        if (TextUtils.isEmpty(scheme)) {
5524            return false;
5525        }
5526        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5527    }
5528
5529    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5530            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5531            int userId) {
5532        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5533
5534        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5535            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5536                    candidates.size());
5537        }
5538
5539        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5540        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5541        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5542        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5543        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5544        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5545
5546        synchronized (mPackages) {
5547            final int count = candidates.size();
5548            // First, try to use linked apps. Partition the candidates into four lists:
5549            // one for the final results, one for the "do not use ever", one for "undefined status"
5550            // and finally one for "browser app type".
5551            for (int n=0; n<count; n++) {
5552                ResolveInfo info = candidates.get(n);
5553                String packageName = info.activityInfo.packageName;
5554                PackageSetting ps = mSettings.mPackages.get(packageName);
5555                if (ps != null) {
5556                    // Add to the special match all list (Browser use case)
5557                    if (info.handleAllWebDataURI) {
5558                        matchAllList.add(info);
5559                        continue;
5560                    }
5561                    // Try to get the status from User settings first
5562                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5563                    int status = (int)(packedStatus >> 32);
5564                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5565                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5566                        if (DEBUG_DOMAIN_VERIFICATION) {
5567                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5568                                    + " : linkgen=" + linkGeneration);
5569                        }
5570                        // Use link-enabled generation as preferredOrder, i.e.
5571                        // prefer newly-enabled over earlier-enabled.
5572                        info.preferredOrder = linkGeneration;
5573                        alwaysList.add(info);
5574                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5575                        if (DEBUG_DOMAIN_VERIFICATION) {
5576                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5577                        }
5578                        neverList.add(info);
5579                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5580                        if (DEBUG_DOMAIN_VERIFICATION) {
5581                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5582                        }
5583                        alwaysAskList.add(info);
5584                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5585                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5586                        if (DEBUG_DOMAIN_VERIFICATION) {
5587                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5588                        }
5589                        undefinedList.add(info);
5590                    }
5591                }
5592            }
5593
5594            // We'll want to include browser possibilities in a few cases
5595            boolean includeBrowser = false;
5596
5597            // First try to add the "always" resolution(s) for the current user, if any
5598            if (alwaysList.size() > 0) {
5599                result.addAll(alwaysList);
5600            } else {
5601                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5602                result.addAll(undefinedList);
5603                // Maybe add one for the other profile.
5604                if (xpDomainInfo != null && (
5605                        xpDomainInfo.bestDomainVerificationStatus
5606                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5607                    result.add(xpDomainInfo.resolveInfo);
5608                }
5609                includeBrowser = true;
5610            }
5611
5612            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5613            // If there were 'always' entries their preferred order has been set, so we also
5614            // back that off to make the alternatives equivalent
5615            if (alwaysAskList.size() > 0) {
5616                for (ResolveInfo i : result) {
5617                    i.preferredOrder = 0;
5618                }
5619                result.addAll(alwaysAskList);
5620                includeBrowser = true;
5621            }
5622
5623            if (includeBrowser) {
5624                // Also add browsers (all of them or only the default one)
5625                if (DEBUG_DOMAIN_VERIFICATION) {
5626                    Slog.v(TAG, "   ...including browsers in candidate set");
5627                }
5628                if ((matchFlags & MATCH_ALL) != 0) {
5629                    result.addAll(matchAllList);
5630                } else {
5631                    // Browser/generic handling case.  If there's a default browser, go straight
5632                    // to that (but only if there is no other higher-priority match).
5633                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5634                    int maxMatchPrio = 0;
5635                    ResolveInfo defaultBrowserMatch = null;
5636                    final int numCandidates = matchAllList.size();
5637                    for (int n = 0; n < numCandidates; n++) {
5638                        ResolveInfo info = matchAllList.get(n);
5639                        // track the highest overall match priority...
5640                        if (info.priority > maxMatchPrio) {
5641                            maxMatchPrio = info.priority;
5642                        }
5643                        // ...and the highest-priority default browser match
5644                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5645                            if (defaultBrowserMatch == null
5646                                    || (defaultBrowserMatch.priority < info.priority)) {
5647                                if (debug) {
5648                                    Slog.v(TAG, "Considering default browser match " + info);
5649                                }
5650                                defaultBrowserMatch = info;
5651                            }
5652                        }
5653                    }
5654                    if (defaultBrowserMatch != null
5655                            && defaultBrowserMatch.priority >= maxMatchPrio
5656                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5657                    {
5658                        if (debug) {
5659                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5660                        }
5661                        result.add(defaultBrowserMatch);
5662                    } else {
5663                        result.addAll(matchAllList);
5664                    }
5665                }
5666
5667                // If there is nothing selected, add all candidates and remove the ones that the user
5668                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5669                if (result.size() == 0) {
5670                    result.addAll(candidates);
5671                    result.removeAll(neverList);
5672                }
5673            }
5674        }
5675        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5676            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5677                    result.size());
5678            for (ResolveInfo info : result) {
5679                Slog.v(TAG, "  + " + info.activityInfo);
5680            }
5681        }
5682        return result;
5683    }
5684
5685    // Returns a packed value as a long:
5686    //
5687    // high 'int'-sized word: link status: undefined/ask/never/always.
5688    // low 'int'-sized word: relative priority among 'always' results.
5689    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5690        long result = ps.getDomainVerificationStatusForUser(userId);
5691        // if none available, get the master status
5692        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5693            if (ps.getIntentFilterVerificationInfo() != null) {
5694                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5695            }
5696        }
5697        return result;
5698    }
5699
5700    private ResolveInfo querySkipCurrentProfileIntents(
5701            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5702            int flags, int sourceUserId) {
5703        if (matchingFilters != null) {
5704            int size = matchingFilters.size();
5705            for (int i = 0; i < size; i ++) {
5706                CrossProfileIntentFilter filter = matchingFilters.get(i);
5707                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5708                    // Checking if there are activities in the target user that can handle the
5709                    // intent.
5710                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5711                            resolvedType, flags, sourceUserId);
5712                    if (resolveInfo != null) {
5713                        return resolveInfo;
5714                    }
5715                }
5716            }
5717        }
5718        return null;
5719    }
5720
5721    // Return matching ResolveInfo in target user if any.
5722    private ResolveInfo queryCrossProfileIntents(
5723            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5724            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5725        if (matchingFilters != null) {
5726            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5727            // match the same intent. For performance reasons, it is better not to
5728            // run queryIntent twice for the same userId
5729            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5730            int size = matchingFilters.size();
5731            for (int i = 0; i < size; i++) {
5732                CrossProfileIntentFilter filter = matchingFilters.get(i);
5733                int targetUserId = filter.getTargetUserId();
5734                boolean skipCurrentProfile =
5735                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5736                boolean skipCurrentProfileIfNoMatchFound =
5737                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5738                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5739                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5740                    // Checking if there are activities in the target user that can handle the
5741                    // intent.
5742                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5743                            resolvedType, flags, sourceUserId);
5744                    if (resolveInfo != null) return resolveInfo;
5745                    alreadyTriedUserIds.put(targetUserId, true);
5746                }
5747            }
5748        }
5749        return null;
5750    }
5751
5752    /**
5753     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5754     * will forward the intent to the filter's target user.
5755     * Otherwise, returns null.
5756     */
5757    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5758            String resolvedType, int flags, int sourceUserId) {
5759        int targetUserId = filter.getTargetUserId();
5760        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5761                resolvedType, flags, targetUserId);
5762        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5763            // If all the matches in the target profile are suspended, return null.
5764            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5765                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5766                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5767                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5768                            targetUserId);
5769                }
5770            }
5771        }
5772        return null;
5773    }
5774
5775    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5776            int sourceUserId, int targetUserId) {
5777        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5778        long ident = Binder.clearCallingIdentity();
5779        boolean targetIsProfile;
5780        try {
5781            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5782        } finally {
5783            Binder.restoreCallingIdentity(ident);
5784        }
5785        String className;
5786        if (targetIsProfile) {
5787            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5788        } else {
5789            className = FORWARD_INTENT_TO_PARENT;
5790        }
5791        ComponentName forwardingActivityComponentName = new ComponentName(
5792                mAndroidApplication.packageName, className);
5793        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5794                sourceUserId);
5795        if (!targetIsProfile) {
5796            forwardingActivityInfo.showUserIcon = targetUserId;
5797            forwardingResolveInfo.noResourceId = true;
5798        }
5799        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5800        forwardingResolveInfo.priority = 0;
5801        forwardingResolveInfo.preferredOrder = 0;
5802        forwardingResolveInfo.match = 0;
5803        forwardingResolveInfo.isDefault = true;
5804        forwardingResolveInfo.filter = filter;
5805        forwardingResolveInfo.targetUserId = targetUserId;
5806        return forwardingResolveInfo;
5807    }
5808
5809    @Override
5810    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5811            Intent[] specifics, String[] specificTypes, Intent intent,
5812            String resolvedType, int flags, int userId) {
5813        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5814                specificTypes, intent, resolvedType, flags, userId));
5815    }
5816
5817    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5818            Intent[] specifics, String[] specificTypes, Intent intent,
5819            String resolvedType, int flags, int userId) {
5820        if (!sUserManager.exists(userId)) return Collections.emptyList();
5821        flags = updateFlagsForResolve(flags, userId, intent);
5822        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5823                false /* requireFullPermission */, false /* checkShell */,
5824                "query intent activity options");
5825        final String resultsAction = intent.getAction();
5826
5827        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5828                | PackageManager.GET_RESOLVED_FILTER, userId);
5829
5830        if (DEBUG_INTENT_MATCHING) {
5831            Log.v(TAG, "Query " + intent + ": " + results);
5832        }
5833
5834        int specificsPos = 0;
5835        int N;
5836
5837        // todo: note that the algorithm used here is O(N^2).  This
5838        // isn't a problem in our current environment, but if we start running
5839        // into situations where we have more than 5 or 10 matches then this
5840        // should probably be changed to something smarter...
5841
5842        // First we go through and resolve each of the specific items
5843        // that were supplied, taking care of removing any corresponding
5844        // duplicate items in the generic resolve list.
5845        if (specifics != null) {
5846            for (int i=0; i<specifics.length; i++) {
5847                final Intent sintent = specifics[i];
5848                if (sintent == null) {
5849                    continue;
5850                }
5851
5852                if (DEBUG_INTENT_MATCHING) {
5853                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5854                }
5855
5856                String action = sintent.getAction();
5857                if (resultsAction != null && resultsAction.equals(action)) {
5858                    // If this action was explicitly requested, then don't
5859                    // remove things that have it.
5860                    action = null;
5861                }
5862
5863                ResolveInfo ri = null;
5864                ActivityInfo ai = null;
5865
5866                ComponentName comp = sintent.getComponent();
5867                if (comp == null) {
5868                    ri = resolveIntent(
5869                        sintent,
5870                        specificTypes != null ? specificTypes[i] : null,
5871                            flags, userId);
5872                    if (ri == null) {
5873                        continue;
5874                    }
5875                    if (ri == mResolveInfo) {
5876                        // ACK!  Must do something better with this.
5877                    }
5878                    ai = ri.activityInfo;
5879                    comp = new ComponentName(ai.applicationInfo.packageName,
5880                            ai.name);
5881                } else {
5882                    ai = getActivityInfo(comp, flags, userId);
5883                    if (ai == null) {
5884                        continue;
5885                    }
5886                }
5887
5888                // Look for any generic query activities that are duplicates
5889                // of this specific one, and remove them from the results.
5890                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5891                N = results.size();
5892                int j;
5893                for (j=specificsPos; j<N; j++) {
5894                    ResolveInfo sri = results.get(j);
5895                    if ((sri.activityInfo.name.equals(comp.getClassName())
5896                            && sri.activityInfo.applicationInfo.packageName.equals(
5897                                    comp.getPackageName()))
5898                        || (action != null && sri.filter.matchAction(action))) {
5899                        results.remove(j);
5900                        if (DEBUG_INTENT_MATCHING) Log.v(
5901                            TAG, "Removing duplicate item from " + j
5902                            + " due to specific " + specificsPos);
5903                        if (ri == null) {
5904                            ri = sri;
5905                        }
5906                        j--;
5907                        N--;
5908                    }
5909                }
5910
5911                // Add this specific item to its proper place.
5912                if (ri == null) {
5913                    ri = new ResolveInfo();
5914                    ri.activityInfo = ai;
5915                }
5916                results.add(specificsPos, ri);
5917                ri.specificIndex = i;
5918                specificsPos++;
5919            }
5920        }
5921
5922        // Now we go through the remaining generic results and remove any
5923        // duplicate actions that are found here.
5924        N = results.size();
5925        for (int i=specificsPos; i<N-1; i++) {
5926            final ResolveInfo rii = results.get(i);
5927            if (rii.filter == null) {
5928                continue;
5929            }
5930
5931            // Iterate over all of the actions of this result's intent
5932            // filter...  typically this should be just one.
5933            final Iterator<String> it = rii.filter.actionsIterator();
5934            if (it == null) {
5935                continue;
5936            }
5937            while (it.hasNext()) {
5938                final String action = it.next();
5939                if (resultsAction != null && resultsAction.equals(action)) {
5940                    // If this action was explicitly requested, then don't
5941                    // remove things that have it.
5942                    continue;
5943                }
5944                for (int j=i+1; j<N; j++) {
5945                    final ResolveInfo rij = results.get(j);
5946                    if (rij.filter != null && rij.filter.hasAction(action)) {
5947                        results.remove(j);
5948                        if (DEBUG_INTENT_MATCHING) Log.v(
5949                            TAG, "Removing duplicate item from " + j
5950                            + " due to action " + action + " at " + i);
5951                        j--;
5952                        N--;
5953                    }
5954                }
5955            }
5956
5957            // If the caller didn't request filter information, drop it now
5958            // so we don't have to marshall/unmarshall it.
5959            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5960                rii.filter = null;
5961            }
5962        }
5963
5964        // Filter out the caller activity if so requested.
5965        if (caller != null) {
5966            N = results.size();
5967            for (int i=0; i<N; i++) {
5968                ActivityInfo ainfo = results.get(i).activityInfo;
5969                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5970                        && caller.getClassName().equals(ainfo.name)) {
5971                    results.remove(i);
5972                    break;
5973                }
5974            }
5975        }
5976
5977        // If the caller didn't request filter information,
5978        // drop them now so we don't have to
5979        // marshall/unmarshall it.
5980        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5981            N = results.size();
5982            for (int i=0; i<N; i++) {
5983                results.get(i).filter = null;
5984            }
5985        }
5986
5987        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5988        return results;
5989    }
5990
5991    @Override
5992    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5993            String resolvedType, int flags, int userId) {
5994        return new ParceledListSlice<>(
5995                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5996    }
5997
5998    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5999            String resolvedType, int flags, int userId) {
6000        if (!sUserManager.exists(userId)) return Collections.emptyList();
6001        flags = updateFlagsForResolve(flags, userId, intent);
6002        ComponentName comp = intent.getComponent();
6003        if (comp == null) {
6004            if (intent.getSelector() != null) {
6005                intent = intent.getSelector();
6006                comp = intent.getComponent();
6007            }
6008        }
6009        if (comp != null) {
6010            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6011            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6012            if (ai != null) {
6013                ResolveInfo ri = new ResolveInfo();
6014                ri.activityInfo = ai;
6015                list.add(ri);
6016            }
6017            return list;
6018        }
6019
6020        // reader
6021        synchronized (mPackages) {
6022            String pkgName = intent.getPackage();
6023            if (pkgName == null) {
6024                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6025            }
6026            final PackageParser.Package pkg = mPackages.get(pkgName);
6027            if (pkg != null) {
6028                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6029                        userId);
6030            }
6031            return Collections.emptyList();
6032        }
6033    }
6034
6035    @Override
6036    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6037        if (!sUserManager.exists(userId)) return null;
6038        flags = updateFlagsForResolve(flags, userId, intent);
6039        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6040        if (query != null) {
6041            if (query.size() >= 1) {
6042                // If there is more than one service with the same priority,
6043                // just arbitrarily pick the first one.
6044                return query.get(0);
6045            }
6046        }
6047        return null;
6048    }
6049
6050    @Override
6051    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6052            String resolvedType, int flags, int userId) {
6053        return new ParceledListSlice<>(
6054                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6055    }
6056
6057    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6058            String resolvedType, int flags, int userId) {
6059        if (!sUserManager.exists(userId)) return Collections.emptyList();
6060        flags = updateFlagsForResolve(flags, userId, intent);
6061        ComponentName comp = intent.getComponent();
6062        if (comp == null) {
6063            if (intent.getSelector() != null) {
6064                intent = intent.getSelector();
6065                comp = intent.getComponent();
6066            }
6067        }
6068        if (comp != null) {
6069            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6070            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6071            if (si != null) {
6072                final ResolveInfo ri = new ResolveInfo();
6073                ri.serviceInfo = si;
6074                list.add(ri);
6075            }
6076            return list;
6077        }
6078
6079        // reader
6080        synchronized (mPackages) {
6081            String pkgName = intent.getPackage();
6082            if (pkgName == null) {
6083                return mServices.queryIntent(intent, resolvedType, flags, userId);
6084            }
6085            final PackageParser.Package pkg = mPackages.get(pkgName);
6086            if (pkg != null) {
6087                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6088                        userId);
6089            }
6090            return Collections.emptyList();
6091        }
6092    }
6093
6094    @Override
6095    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6096            String resolvedType, int flags, int userId) {
6097        return new ParceledListSlice<>(
6098                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6099    }
6100
6101    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6102            Intent intent, String resolvedType, int flags, int userId) {
6103        if (!sUserManager.exists(userId)) return Collections.emptyList();
6104        flags = updateFlagsForResolve(flags, userId, intent);
6105        ComponentName comp = intent.getComponent();
6106        if (comp == null) {
6107            if (intent.getSelector() != null) {
6108                intent = intent.getSelector();
6109                comp = intent.getComponent();
6110            }
6111        }
6112        if (comp != null) {
6113            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6114            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6115            if (pi != null) {
6116                final ResolveInfo ri = new ResolveInfo();
6117                ri.providerInfo = pi;
6118                list.add(ri);
6119            }
6120            return list;
6121        }
6122
6123        // reader
6124        synchronized (mPackages) {
6125            String pkgName = intent.getPackage();
6126            if (pkgName == null) {
6127                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6128            }
6129            final PackageParser.Package pkg = mPackages.get(pkgName);
6130            if (pkg != null) {
6131                return mProviders.queryIntentForPackage(
6132                        intent, resolvedType, flags, pkg.providers, userId);
6133            }
6134            return Collections.emptyList();
6135        }
6136    }
6137
6138    @Override
6139    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6140        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6141        flags = updateFlagsForPackage(flags, userId, null);
6142        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6143        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6144                true /* requireFullPermission */, false /* checkShell */,
6145                "get installed packages");
6146
6147        // writer
6148        synchronized (mPackages) {
6149            ArrayList<PackageInfo> list;
6150            if (listUninstalled) {
6151                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6152                for (PackageSetting ps : mSettings.mPackages.values()) {
6153                    final PackageInfo pi;
6154                    if (ps.pkg != null) {
6155                        pi = generatePackageInfo(ps, flags, userId);
6156                    } else {
6157                        pi = generatePackageInfo(ps, flags, userId);
6158                    }
6159                    if (pi != null) {
6160                        list.add(pi);
6161                    }
6162                }
6163            } else {
6164                list = new ArrayList<PackageInfo>(mPackages.size());
6165                for (PackageParser.Package p : mPackages.values()) {
6166                    final PackageInfo pi =
6167                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6168                    if (pi != null) {
6169                        list.add(pi);
6170                    }
6171                }
6172            }
6173
6174            return new ParceledListSlice<PackageInfo>(list);
6175        }
6176    }
6177
6178    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6179            String[] permissions, boolean[] tmp, int flags, int userId) {
6180        int numMatch = 0;
6181        final PermissionsState permissionsState = ps.getPermissionsState();
6182        for (int i=0; i<permissions.length; i++) {
6183            final String permission = permissions[i];
6184            if (permissionsState.hasPermission(permission, userId)) {
6185                tmp[i] = true;
6186                numMatch++;
6187            } else {
6188                tmp[i] = false;
6189            }
6190        }
6191        if (numMatch == 0) {
6192            return;
6193        }
6194        final PackageInfo pi;
6195        if (ps.pkg != null) {
6196            pi = generatePackageInfo(ps, flags, userId);
6197        } else {
6198            pi = generatePackageInfo(ps, flags, userId);
6199        }
6200        // The above might return null in cases of uninstalled apps or install-state
6201        // skew across users/profiles.
6202        if (pi != null) {
6203            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6204                if (numMatch == permissions.length) {
6205                    pi.requestedPermissions = permissions;
6206                } else {
6207                    pi.requestedPermissions = new String[numMatch];
6208                    numMatch = 0;
6209                    for (int i=0; i<permissions.length; i++) {
6210                        if (tmp[i]) {
6211                            pi.requestedPermissions[numMatch] = permissions[i];
6212                            numMatch++;
6213                        }
6214                    }
6215                }
6216            }
6217            list.add(pi);
6218        }
6219    }
6220
6221    @Override
6222    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6223            String[] permissions, int flags, int userId) {
6224        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6225        flags = updateFlagsForPackage(flags, userId, permissions);
6226        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6227
6228        // writer
6229        synchronized (mPackages) {
6230            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6231            boolean[] tmpBools = new boolean[permissions.length];
6232            if (listUninstalled) {
6233                for (PackageSetting ps : mSettings.mPackages.values()) {
6234                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6235                }
6236            } else {
6237                for (PackageParser.Package pkg : mPackages.values()) {
6238                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6239                    if (ps != null) {
6240                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6241                                userId);
6242                    }
6243                }
6244            }
6245
6246            return new ParceledListSlice<PackageInfo>(list);
6247        }
6248    }
6249
6250    @Override
6251    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6252        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6253        flags = updateFlagsForApplication(flags, userId, null);
6254        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6255
6256        // writer
6257        synchronized (mPackages) {
6258            ArrayList<ApplicationInfo> list;
6259            if (listUninstalled) {
6260                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6261                for (PackageSetting ps : mSettings.mPackages.values()) {
6262                    ApplicationInfo ai;
6263                    if (ps.pkg != null) {
6264                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6265                                ps.readUserState(userId), userId);
6266                    } else {
6267                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6268                    }
6269                    if (ai != null) {
6270                        list.add(ai);
6271                    }
6272                }
6273            } else {
6274                list = new ArrayList<ApplicationInfo>(mPackages.size());
6275                for (PackageParser.Package p : mPackages.values()) {
6276                    if (p.mExtras != null) {
6277                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6278                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6279                        if (ai != null) {
6280                            list.add(ai);
6281                        }
6282                    }
6283                }
6284            }
6285
6286            return new ParceledListSlice<ApplicationInfo>(list);
6287        }
6288    }
6289
6290    @Override
6291    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6292        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6293            return null;
6294        }
6295
6296        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6297                "getEphemeralApplications");
6298        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6299                true /* requireFullPermission */, false /* checkShell */,
6300                "getEphemeralApplications");
6301        synchronized (mPackages) {
6302            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6303                    .getEphemeralApplicationsLPw(userId);
6304            if (ephemeralApps != null) {
6305                return new ParceledListSlice<>(ephemeralApps);
6306            }
6307        }
6308        return null;
6309    }
6310
6311    @Override
6312    public boolean isEphemeralApplication(String packageName, int userId) {
6313        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6314                true /* requireFullPermission */, false /* checkShell */,
6315                "isEphemeral");
6316        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6317            return false;
6318        }
6319
6320        if (!isCallerSameApp(packageName)) {
6321            return false;
6322        }
6323        synchronized (mPackages) {
6324            PackageParser.Package pkg = mPackages.get(packageName);
6325            if (pkg != null) {
6326                return pkg.applicationInfo.isEphemeralApp();
6327            }
6328        }
6329        return false;
6330    }
6331
6332    @Override
6333    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6334        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6335            return null;
6336        }
6337
6338        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6339                true /* requireFullPermission */, false /* checkShell */,
6340                "getCookie");
6341        if (!isCallerSameApp(packageName)) {
6342            return null;
6343        }
6344        synchronized (mPackages) {
6345            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6346                    packageName, userId);
6347        }
6348    }
6349
6350    @Override
6351    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6352        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6353            return true;
6354        }
6355
6356        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6357                true /* requireFullPermission */, true /* checkShell */,
6358                "setCookie");
6359        if (!isCallerSameApp(packageName)) {
6360            return false;
6361        }
6362        synchronized (mPackages) {
6363            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6364                    packageName, cookie, userId);
6365        }
6366    }
6367
6368    @Override
6369    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6370        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6371            return null;
6372        }
6373
6374        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6375                "getEphemeralApplicationIcon");
6376        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6377                true /* requireFullPermission */, false /* checkShell */,
6378                "getEphemeralApplicationIcon");
6379        synchronized (mPackages) {
6380            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6381                    packageName, userId);
6382        }
6383    }
6384
6385    private boolean isCallerSameApp(String packageName) {
6386        PackageParser.Package pkg = mPackages.get(packageName);
6387        return pkg != null
6388                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6389    }
6390
6391    @Override
6392    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6393        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6394    }
6395
6396    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6397        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6398
6399        // reader
6400        synchronized (mPackages) {
6401            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6402            final int userId = UserHandle.getCallingUserId();
6403            while (i.hasNext()) {
6404                final PackageParser.Package p = i.next();
6405                if (p.applicationInfo == null) continue;
6406
6407                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6408                        && !p.applicationInfo.isDirectBootAware();
6409                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6410                        && p.applicationInfo.isDirectBootAware();
6411
6412                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6413                        && (!mSafeMode || isSystemApp(p))
6414                        && (matchesUnaware || matchesAware)) {
6415                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6416                    if (ps != null) {
6417                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6418                                ps.readUserState(userId), userId);
6419                        if (ai != null) {
6420                            finalList.add(ai);
6421                        }
6422                    }
6423                }
6424            }
6425        }
6426
6427        return finalList;
6428    }
6429
6430    @Override
6431    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6432        if (!sUserManager.exists(userId)) return null;
6433        flags = updateFlagsForComponent(flags, userId, name);
6434        // reader
6435        synchronized (mPackages) {
6436            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6437            PackageSetting ps = provider != null
6438                    ? mSettings.mPackages.get(provider.owner.packageName)
6439                    : null;
6440            return ps != null
6441                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6442                    ? PackageParser.generateProviderInfo(provider, flags,
6443                            ps.readUserState(userId), userId)
6444                    : null;
6445        }
6446    }
6447
6448    /**
6449     * @deprecated
6450     */
6451    @Deprecated
6452    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6453        // reader
6454        synchronized (mPackages) {
6455            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6456                    .entrySet().iterator();
6457            final int userId = UserHandle.getCallingUserId();
6458            while (i.hasNext()) {
6459                Map.Entry<String, PackageParser.Provider> entry = i.next();
6460                PackageParser.Provider p = entry.getValue();
6461                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6462
6463                if (ps != null && p.syncable
6464                        && (!mSafeMode || (p.info.applicationInfo.flags
6465                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6466                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6467                            ps.readUserState(userId), userId);
6468                    if (info != null) {
6469                        outNames.add(entry.getKey());
6470                        outInfo.add(info);
6471                    }
6472                }
6473            }
6474        }
6475    }
6476
6477    @Override
6478    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6479            int uid, int flags) {
6480        final int userId = processName != null ? UserHandle.getUserId(uid)
6481                : UserHandle.getCallingUserId();
6482        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6483        flags = updateFlagsForComponent(flags, userId, processName);
6484
6485        ArrayList<ProviderInfo> finalList = null;
6486        // reader
6487        synchronized (mPackages) {
6488            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6489            while (i.hasNext()) {
6490                final PackageParser.Provider p = i.next();
6491                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6492                if (ps != null && p.info.authority != null
6493                        && (processName == null
6494                                || (p.info.processName.equals(processName)
6495                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6496                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6497                    if (finalList == null) {
6498                        finalList = new ArrayList<ProviderInfo>(3);
6499                    }
6500                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6501                            ps.readUserState(userId), userId);
6502                    if (info != null) {
6503                        finalList.add(info);
6504                    }
6505                }
6506            }
6507        }
6508
6509        if (finalList != null) {
6510            Collections.sort(finalList, mProviderInitOrderSorter);
6511            return new ParceledListSlice<ProviderInfo>(finalList);
6512        }
6513
6514        return ParceledListSlice.emptyList();
6515    }
6516
6517    @Override
6518    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6519        // reader
6520        synchronized (mPackages) {
6521            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6522            return PackageParser.generateInstrumentationInfo(i, flags);
6523        }
6524    }
6525
6526    @Override
6527    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6528            String targetPackage, int flags) {
6529        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6530    }
6531
6532    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6533            int flags) {
6534        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6535
6536        // reader
6537        synchronized (mPackages) {
6538            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6539            while (i.hasNext()) {
6540                final PackageParser.Instrumentation p = i.next();
6541                if (targetPackage == null
6542                        || targetPackage.equals(p.info.targetPackage)) {
6543                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6544                            flags);
6545                    if (ii != null) {
6546                        finalList.add(ii);
6547                    }
6548                }
6549            }
6550        }
6551
6552        return finalList;
6553    }
6554
6555    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6556        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6557        if (overlays == null) {
6558            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6559            return;
6560        }
6561        for (PackageParser.Package opkg : overlays.values()) {
6562            // Not much to do if idmap fails: we already logged the error
6563            // and we certainly don't want to abort installation of pkg simply
6564            // because an overlay didn't fit properly. For these reasons,
6565            // ignore the return value of createIdmapForPackagePairLI.
6566            createIdmapForPackagePairLI(pkg, opkg);
6567        }
6568    }
6569
6570    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6571            PackageParser.Package opkg) {
6572        if (!opkg.mTrustedOverlay) {
6573            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6574                    opkg.baseCodePath + ": overlay not trusted");
6575            return false;
6576        }
6577        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6578        if (overlaySet == null) {
6579            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6580                    opkg.baseCodePath + " but target package has no known overlays");
6581            return false;
6582        }
6583        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6584        // TODO: generate idmap for split APKs
6585        try {
6586            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6587        } catch (InstallerException e) {
6588            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6589                    + opkg.baseCodePath);
6590            return false;
6591        }
6592        PackageParser.Package[] overlayArray =
6593            overlaySet.values().toArray(new PackageParser.Package[0]);
6594        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6595            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6596                return p1.mOverlayPriority - p2.mOverlayPriority;
6597            }
6598        };
6599        Arrays.sort(overlayArray, cmp);
6600
6601        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6602        int i = 0;
6603        for (PackageParser.Package p : overlayArray) {
6604            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6605        }
6606        return true;
6607    }
6608
6609    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6610        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6611        try {
6612            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6613        } finally {
6614            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6615        }
6616    }
6617
6618    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6619        final File[] files = dir.listFiles();
6620        if (ArrayUtils.isEmpty(files)) {
6621            Log.d(TAG, "No files in app dir " + dir);
6622            return;
6623        }
6624
6625        if (DEBUG_PACKAGE_SCANNING) {
6626            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6627                    + " flags=0x" + Integer.toHexString(parseFlags));
6628        }
6629
6630        for (File file : files) {
6631            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6632                    && !PackageInstallerService.isStageName(file.getName());
6633            if (!isPackage) {
6634                // Ignore entries which are not packages
6635                continue;
6636            }
6637            try {
6638                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6639                        scanFlags, currentTime, null);
6640            } catch (PackageManagerException e) {
6641                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6642
6643                // Delete invalid userdata apps
6644                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6645                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6646                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6647                    removeCodePathLI(file);
6648                }
6649            }
6650        }
6651    }
6652
6653    private static File getSettingsProblemFile() {
6654        File dataDir = Environment.getDataDirectory();
6655        File systemDir = new File(dataDir, "system");
6656        File fname = new File(systemDir, "uiderrors.txt");
6657        return fname;
6658    }
6659
6660    static void reportSettingsProblem(int priority, String msg) {
6661        logCriticalInfo(priority, msg);
6662    }
6663
6664    static void logCriticalInfo(int priority, String msg) {
6665        Slog.println(priority, TAG, msg);
6666        EventLogTags.writePmCriticalInfo(msg);
6667        try {
6668            File fname = getSettingsProblemFile();
6669            FileOutputStream out = new FileOutputStream(fname, true);
6670            PrintWriter pw = new FastPrintWriter(out);
6671            SimpleDateFormat formatter = new SimpleDateFormat();
6672            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6673            pw.println(dateString + ": " + msg);
6674            pw.close();
6675            FileUtils.setPermissions(
6676                    fname.toString(),
6677                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6678                    -1, -1);
6679        } catch (java.io.IOException e) {
6680        }
6681    }
6682
6683    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6684        if (srcFile.isDirectory()) {
6685            final File baseFile = new File(pkg.baseCodePath);
6686            long maxModifiedTime = baseFile.lastModified();
6687            if (pkg.splitCodePaths != null) {
6688                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6689                    final File splitFile = new File(pkg.splitCodePaths[i]);
6690                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6691                }
6692            }
6693            return maxModifiedTime;
6694        }
6695        return srcFile.lastModified();
6696    }
6697
6698    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6699            final int policyFlags) throws PackageManagerException {
6700        // When upgrading from pre-N MR1, verify the package time stamp using the package
6701        // directory and not the APK file.
6702        final long lastModifiedTime = mIsPreNMR1Upgrade
6703                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6704        if (ps != null
6705                && ps.codePath.equals(srcFile)
6706                && ps.timeStamp == lastModifiedTime
6707                && !isCompatSignatureUpdateNeeded(pkg)
6708                && !isRecoverSignatureUpdateNeeded(pkg)) {
6709            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6710            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6711            ArraySet<PublicKey> signingKs;
6712            synchronized (mPackages) {
6713                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6714            }
6715            if (ps.signatures.mSignatures != null
6716                    && ps.signatures.mSignatures.length != 0
6717                    && signingKs != null) {
6718                // Optimization: reuse the existing cached certificates
6719                // if the package appears to be unchanged.
6720                pkg.mSignatures = ps.signatures.mSignatures;
6721                pkg.mSigningKeys = signingKs;
6722                return;
6723            }
6724
6725            Slog.w(TAG, "PackageSetting for " + ps.name
6726                    + " is missing signatures.  Collecting certs again to recover them.");
6727        } else {
6728            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6729        }
6730
6731        try {
6732            PackageParser.collectCertificates(pkg, policyFlags);
6733        } catch (PackageParserException e) {
6734            throw PackageManagerException.from(e);
6735        }
6736    }
6737
6738    /**
6739     *  Traces a package scan.
6740     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6741     */
6742    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6743            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6744        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6745        try {
6746            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6747        } finally {
6748            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6749        }
6750    }
6751
6752    /**
6753     *  Scans a package and returns the newly parsed package.
6754     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6755     */
6756    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6757            long currentTime, UserHandle user) throws PackageManagerException {
6758        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6759        PackageParser pp = new PackageParser();
6760        pp.setSeparateProcesses(mSeparateProcesses);
6761        pp.setOnlyCoreApps(mOnlyCore);
6762        pp.setDisplayMetrics(mMetrics);
6763
6764        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6765            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6766        }
6767
6768        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6769        final PackageParser.Package pkg;
6770        try {
6771            pkg = pp.parsePackage(scanFile, parseFlags);
6772        } catch (PackageParserException e) {
6773            throw PackageManagerException.from(e);
6774        } finally {
6775            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6776        }
6777
6778        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6779    }
6780
6781    /**
6782     *  Scans a package and returns the newly parsed package.
6783     *  @throws PackageManagerException on a parse error.
6784     */
6785    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6786            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6787            throws PackageManagerException {
6788        // If the package has children and this is the first dive in the function
6789        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6790        // packages (parent and children) would be successfully scanned before the
6791        // actual scan since scanning mutates internal state and we want to atomically
6792        // install the package and its children.
6793        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6794            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6795                scanFlags |= SCAN_CHECK_ONLY;
6796            }
6797        } else {
6798            scanFlags &= ~SCAN_CHECK_ONLY;
6799        }
6800
6801        // Scan the parent
6802        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6803                scanFlags, currentTime, user);
6804
6805        // Scan the children
6806        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6807        for (int i = 0; i < childCount; i++) {
6808            PackageParser.Package childPackage = pkg.childPackages.get(i);
6809            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6810                    currentTime, user);
6811        }
6812
6813
6814        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6815            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6816        }
6817
6818        return scannedPkg;
6819    }
6820
6821    /**
6822     *  Scans a package and returns the newly parsed package.
6823     *  @throws PackageManagerException on a parse error.
6824     */
6825    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6826            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6827            throws PackageManagerException {
6828        PackageSetting ps = null;
6829        PackageSetting updatedPkg;
6830        // reader
6831        synchronized (mPackages) {
6832            // Look to see if we already know about this package.
6833            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6834            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6835                // This package has been renamed to its original name.  Let's
6836                // use that.
6837                ps = mSettings.peekPackageLPr(oldName);
6838            }
6839            // If there was no original package, see one for the real package name.
6840            if (ps == null) {
6841                ps = mSettings.peekPackageLPr(pkg.packageName);
6842            }
6843            // Check to see if this package could be hiding/updating a system
6844            // package.  Must look for it either under the original or real
6845            // package name depending on our state.
6846            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6847            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6848
6849            // If this is a package we don't know about on the system partition, we
6850            // may need to remove disabled child packages on the system partition
6851            // or may need to not add child packages if the parent apk is updated
6852            // on the data partition and no longer defines this child package.
6853            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6854                // If this is a parent package for an updated system app and this system
6855                // app got an OTA update which no longer defines some of the child packages
6856                // we have to prune them from the disabled system packages.
6857                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6858                if (disabledPs != null) {
6859                    final int scannedChildCount = (pkg.childPackages != null)
6860                            ? pkg.childPackages.size() : 0;
6861                    final int disabledChildCount = disabledPs.childPackageNames != null
6862                            ? disabledPs.childPackageNames.size() : 0;
6863                    for (int i = 0; i < disabledChildCount; i++) {
6864                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6865                        boolean disabledPackageAvailable = false;
6866                        for (int j = 0; j < scannedChildCount; j++) {
6867                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6868                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6869                                disabledPackageAvailable = true;
6870                                break;
6871                            }
6872                         }
6873                         if (!disabledPackageAvailable) {
6874                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6875                         }
6876                    }
6877                }
6878            }
6879        }
6880
6881        boolean updatedPkgBetter = false;
6882        // First check if this is a system package that may involve an update
6883        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6884            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6885            // it needs to drop FLAG_PRIVILEGED.
6886            if (locationIsPrivileged(scanFile)) {
6887                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6888            } else {
6889                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6890            }
6891
6892            if (ps != null && !ps.codePath.equals(scanFile)) {
6893                // The path has changed from what was last scanned...  check the
6894                // version of the new path against what we have stored to determine
6895                // what to do.
6896                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6897                if (pkg.mVersionCode <= ps.versionCode) {
6898                    // The system package has been updated and the code path does not match
6899                    // Ignore entry. Skip it.
6900                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6901                            + " ignored: updated version " + ps.versionCode
6902                            + " better than this " + pkg.mVersionCode);
6903                    if (!updatedPkg.codePath.equals(scanFile)) {
6904                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6905                                + ps.name + " changing from " + updatedPkg.codePathString
6906                                + " to " + scanFile);
6907                        updatedPkg.codePath = scanFile;
6908                        updatedPkg.codePathString = scanFile.toString();
6909                        updatedPkg.resourcePath = scanFile;
6910                        updatedPkg.resourcePathString = scanFile.toString();
6911                    }
6912                    updatedPkg.pkg = pkg;
6913                    updatedPkg.versionCode = pkg.mVersionCode;
6914
6915                    // Update the disabled system child packages to point to the package too.
6916                    final int childCount = updatedPkg.childPackageNames != null
6917                            ? updatedPkg.childPackageNames.size() : 0;
6918                    for (int i = 0; i < childCount; i++) {
6919                        String childPackageName = updatedPkg.childPackageNames.get(i);
6920                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6921                                childPackageName);
6922                        if (updatedChildPkg != null) {
6923                            updatedChildPkg.pkg = pkg;
6924                            updatedChildPkg.versionCode = pkg.mVersionCode;
6925                        }
6926                    }
6927
6928                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6929                            + scanFile + " ignored: updated version " + ps.versionCode
6930                            + " better than this " + pkg.mVersionCode);
6931                } else {
6932                    // The current app on the system partition is better than
6933                    // what we have updated to on the data partition; switch
6934                    // back to the system partition version.
6935                    // At this point, its safely assumed that package installation for
6936                    // apps in system partition will go through. If not there won't be a working
6937                    // version of the app
6938                    // writer
6939                    synchronized (mPackages) {
6940                        // Just remove the loaded entries from package lists.
6941                        mPackages.remove(ps.name);
6942                    }
6943
6944                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6945                            + " reverting from " + ps.codePathString
6946                            + ": new version " + pkg.mVersionCode
6947                            + " better than installed " + ps.versionCode);
6948
6949                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6950                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6951                    synchronized (mInstallLock) {
6952                        args.cleanUpResourcesLI();
6953                    }
6954                    synchronized (mPackages) {
6955                        mSettings.enableSystemPackageLPw(ps.name);
6956                    }
6957                    updatedPkgBetter = true;
6958                }
6959            }
6960        }
6961
6962        if (updatedPkg != null) {
6963            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6964            // initially
6965            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6966
6967            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6968            // flag set initially
6969            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6970                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6971            }
6972        }
6973
6974        // Verify certificates against what was last scanned
6975        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6976
6977        /*
6978         * A new system app appeared, but we already had a non-system one of the
6979         * same name installed earlier.
6980         */
6981        boolean shouldHideSystemApp = false;
6982        if (updatedPkg == null && ps != null
6983                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6984            /*
6985             * Check to make sure the signatures match first. If they don't,
6986             * wipe the installed application and its data.
6987             */
6988            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6989                    != PackageManager.SIGNATURE_MATCH) {
6990                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6991                        + " signatures don't match existing userdata copy; removing");
6992                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6993                        "scanPackageInternalLI")) {
6994                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6995                }
6996                ps = null;
6997            } else {
6998                /*
6999                 * If the newly-added system app is an older version than the
7000                 * already installed version, hide it. It will be scanned later
7001                 * and re-added like an update.
7002                 */
7003                if (pkg.mVersionCode <= ps.versionCode) {
7004                    shouldHideSystemApp = true;
7005                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7006                            + " but new version " + pkg.mVersionCode + " better than installed "
7007                            + ps.versionCode + "; hiding system");
7008                } else {
7009                    /*
7010                     * The newly found system app is a newer version that the
7011                     * one previously installed. Simply remove the
7012                     * already-installed application and replace it with our own
7013                     * while keeping the application data.
7014                     */
7015                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7016                            + " reverting from " + ps.codePathString + ": new version "
7017                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7018                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7019                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7020                    synchronized (mInstallLock) {
7021                        args.cleanUpResourcesLI();
7022                    }
7023                }
7024            }
7025        }
7026
7027        // The apk is forward locked (not public) if its code and resources
7028        // are kept in different files. (except for app in either system or
7029        // vendor path).
7030        // TODO grab this value from PackageSettings
7031        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7032            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7033                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7034            }
7035        }
7036
7037        // TODO: extend to support forward-locked splits
7038        String resourcePath = null;
7039        String baseResourcePath = null;
7040        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7041            if (ps != null && ps.resourcePathString != null) {
7042                resourcePath = ps.resourcePathString;
7043                baseResourcePath = ps.resourcePathString;
7044            } else {
7045                // Should not happen at all. Just log an error.
7046                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7047            }
7048        } else {
7049            resourcePath = pkg.codePath;
7050            baseResourcePath = pkg.baseCodePath;
7051        }
7052
7053        // Set application objects path explicitly.
7054        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7055        pkg.setApplicationInfoCodePath(pkg.codePath);
7056        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7057        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7058        pkg.setApplicationInfoResourcePath(resourcePath);
7059        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7060        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7061
7062        // Note that we invoke the following method only if we are about to unpack an application
7063        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7064                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7065
7066        /*
7067         * If the system app should be overridden by a previously installed
7068         * data, hide the system app now and let the /data/app scan pick it up
7069         * again.
7070         */
7071        if (shouldHideSystemApp) {
7072            synchronized (mPackages) {
7073                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7074            }
7075        }
7076
7077        return scannedPkg;
7078    }
7079
7080    private static String fixProcessName(String defProcessName,
7081            String processName, int uid) {
7082        if (processName == null) {
7083            return defProcessName;
7084        }
7085        return processName;
7086    }
7087
7088    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7089            throws PackageManagerException {
7090        if (pkgSetting.signatures.mSignatures != null) {
7091            // Already existing package. Make sure signatures match
7092            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7093                    == PackageManager.SIGNATURE_MATCH;
7094            if (!match) {
7095                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7096                        == PackageManager.SIGNATURE_MATCH;
7097            }
7098            if (!match) {
7099                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7100                        == PackageManager.SIGNATURE_MATCH;
7101            }
7102            if (!match) {
7103                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7104                        + pkg.packageName + " signatures do not match the "
7105                        + "previously installed version; ignoring!");
7106            }
7107        }
7108
7109        // Check for shared user signatures
7110        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7111            // Already existing package. Make sure signatures match
7112            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7113                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7114            if (!match) {
7115                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7116                        == PackageManager.SIGNATURE_MATCH;
7117            }
7118            if (!match) {
7119                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7120                        == PackageManager.SIGNATURE_MATCH;
7121            }
7122            if (!match) {
7123                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7124                        "Package " + pkg.packageName
7125                        + " has no signatures that match those in shared user "
7126                        + pkgSetting.sharedUser.name + "; ignoring!");
7127            }
7128        }
7129    }
7130
7131    /**
7132     * Enforces that only the system UID or root's UID can call a method exposed
7133     * via Binder.
7134     *
7135     * @param message used as message if SecurityException is thrown
7136     * @throws SecurityException if the caller is not system or root
7137     */
7138    private static final void enforceSystemOrRoot(String message) {
7139        final int uid = Binder.getCallingUid();
7140        if (uid != Process.SYSTEM_UID && uid != 0) {
7141            throw new SecurityException(message);
7142        }
7143    }
7144
7145    @Override
7146    public void performFstrimIfNeeded() {
7147        enforceSystemOrRoot("Only the system can request fstrim");
7148
7149        // Before everything else, see whether we need to fstrim.
7150        try {
7151            IMountService ms = PackageHelper.getMountService();
7152            if (ms != null) {
7153                boolean doTrim = false;
7154                final long interval = android.provider.Settings.Global.getLong(
7155                        mContext.getContentResolver(),
7156                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7157                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7158                if (interval > 0) {
7159                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7160                    if (timeSinceLast > interval) {
7161                        doTrim = true;
7162                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7163                                + "; running immediately");
7164                    }
7165                }
7166                if (doTrim) {
7167                    final boolean dexOptDialogShown;
7168                    synchronized (mPackages) {
7169                        dexOptDialogShown = mDexOptDialogShown;
7170                    }
7171                    if (!isFirstBoot() && dexOptDialogShown) {
7172                        try {
7173                            ActivityManagerNative.getDefault().showBootMessage(
7174                                    mContext.getResources().getString(
7175                                            R.string.android_upgrading_fstrim), true);
7176                        } catch (RemoteException e) {
7177                        }
7178                    }
7179                    ms.runMaintenance();
7180                }
7181            } else {
7182                Slog.e(TAG, "Mount service unavailable!");
7183            }
7184        } catch (RemoteException e) {
7185            // Can't happen; MountService is local
7186        }
7187    }
7188
7189    @Override
7190    public void updatePackagesIfNeeded() {
7191        enforceSystemOrRoot("Only the system can request package update");
7192
7193        // We need to re-extract after an OTA.
7194        boolean causeUpgrade = isUpgrade();
7195
7196        // First boot or factory reset.
7197        // Note: we also handle devices that are upgrading to N right now as if it is their
7198        //       first boot, as they do not have profile data.
7199        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7200
7201        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7202        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7203
7204        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7205            return;
7206        }
7207
7208        List<PackageParser.Package> pkgs;
7209        synchronized (mPackages) {
7210            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7211        }
7212
7213        final long startTime = System.nanoTime();
7214        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7215                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7216
7217        final int elapsedTimeSeconds =
7218                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7219
7220        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7221        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7222        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7223        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7224        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7225    }
7226
7227    /**
7228     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7229     * containing statistics about the invocation. The array consists of three elements,
7230     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7231     * and {@code numberOfPackagesFailed}.
7232     */
7233    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7234            String compilerFilter) {
7235
7236        int numberOfPackagesVisited = 0;
7237        int numberOfPackagesOptimized = 0;
7238        int numberOfPackagesSkipped = 0;
7239        int numberOfPackagesFailed = 0;
7240        final int numberOfPackagesToDexopt = pkgs.size();
7241
7242        for (PackageParser.Package pkg : pkgs) {
7243            numberOfPackagesVisited++;
7244
7245            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7246                if (DEBUG_DEXOPT) {
7247                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7248                }
7249                numberOfPackagesSkipped++;
7250                continue;
7251            }
7252
7253            if (DEBUG_DEXOPT) {
7254                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7255                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7256            }
7257
7258            if (showDialog) {
7259                try {
7260                    ActivityManagerNative.getDefault().showBootMessage(
7261                            mContext.getResources().getString(R.string.android_upgrading_apk,
7262                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7263                } catch (RemoteException e) {
7264                }
7265                synchronized (mPackages) {
7266                    mDexOptDialogShown = true;
7267                }
7268            }
7269
7270            // If the OTA updates a system app which was previously preopted to a non-preopted state
7271            // the app might end up being verified at runtime. That's because by default the apps
7272            // are verify-profile but for preopted apps there's no profile.
7273            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7274            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7275            // filter (by default interpret-only).
7276            // Note that at this stage unused apps are already filtered.
7277            if (isSystemApp(pkg) &&
7278                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7279                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7280                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7281            }
7282
7283            // checkProfiles is false to avoid merging profiles during boot which
7284            // might interfere with background compilation (b/28612421).
7285            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7286            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7287            // trade-off worth doing to save boot time work.
7288            int dexOptStatus = performDexOptTraced(pkg.packageName,
7289                    false /* checkProfiles */,
7290                    compilerFilter,
7291                    false /* force */);
7292            switch (dexOptStatus) {
7293                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7294                    numberOfPackagesOptimized++;
7295                    break;
7296                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7297                    numberOfPackagesSkipped++;
7298                    break;
7299                case PackageDexOptimizer.DEX_OPT_FAILED:
7300                    numberOfPackagesFailed++;
7301                    break;
7302                default:
7303                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7304                    break;
7305            }
7306        }
7307
7308        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7309                numberOfPackagesFailed };
7310    }
7311
7312    @Override
7313    public void notifyPackageUse(String packageName, int reason) {
7314        synchronized (mPackages) {
7315            PackageParser.Package p = mPackages.get(packageName);
7316            if (p == null) {
7317                return;
7318            }
7319            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7320        }
7321    }
7322
7323    // TODO: this is not used nor needed. Delete it.
7324    @Override
7325    public boolean performDexOptIfNeeded(String packageName) {
7326        int dexOptStatus = performDexOptTraced(packageName,
7327                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7328        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7329    }
7330
7331    @Override
7332    public boolean performDexOpt(String packageName,
7333            boolean checkProfiles, int compileReason, boolean force) {
7334        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7335                getCompilerFilterForReason(compileReason), force);
7336        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7337    }
7338
7339    @Override
7340    public boolean performDexOptMode(String packageName,
7341            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7342        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7343                targetCompilerFilter, force);
7344        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7345    }
7346
7347    private int performDexOptTraced(String packageName,
7348                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7349        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7350        try {
7351            return performDexOptInternal(packageName, checkProfiles,
7352                    targetCompilerFilter, force);
7353        } finally {
7354            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7355        }
7356    }
7357
7358    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7359    // if the package can now be considered up to date for the given filter.
7360    private int performDexOptInternal(String packageName,
7361                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7362        PackageParser.Package p;
7363        synchronized (mPackages) {
7364            p = mPackages.get(packageName);
7365            if (p == null) {
7366                // Package could not be found. Report failure.
7367                return PackageDexOptimizer.DEX_OPT_FAILED;
7368            }
7369            mPackageUsage.maybeWriteAsync(mPackages);
7370            mCompilerStats.maybeWriteAsync();
7371        }
7372        long callingId = Binder.clearCallingIdentity();
7373        try {
7374            synchronized (mInstallLock) {
7375                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7376                        targetCompilerFilter, force);
7377            }
7378        } finally {
7379            Binder.restoreCallingIdentity(callingId);
7380        }
7381    }
7382
7383    public ArraySet<String> getOptimizablePackages() {
7384        ArraySet<String> pkgs = new ArraySet<String>();
7385        synchronized (mPackages) {
7386            for (PackageParser.Package p : mPackages.values()) {
7387                if (PackageDexOptimizer.canOptimizePackage(p)) {
7388                    pkgs.add(p.packageName);
7389                }
7390            }
7391        }
7392        return pkgs;
7393    }
7394
7395    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7396            boolean checkProfiles, String targetCompilerFilter,
7397            boolean force) {
7398        // Select the dex optimizer based on the force parameter.
7399        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7400        //       allocate an object here.
7401        PackageDexOptimizer pdo = force
7402                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7403                : mPackageDexOptimizer;
7404
7405        // Optimize all dependencies first. Note: we ignore the return value and march on
7406        // on errors.
7407        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7408        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7409        if (!deps.isEmpty()) {
7410            for (PackageParser.Package depPackage : deps) {
7411                // TODO: Analyze and investigate if we (should) profile libraries.
7412                // Currently this will do a full compilation of the library by default.
7413                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7414                        false /* checkProfiles */,
7415                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7416                        getOrCreateCompilerPackageStats(depPackage));
7417            }
7418        }
7419        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7420                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7421    }
7422
7423    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7424        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7425            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7426            Set<String> collectedNames = new HashSet<>();
7427            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7428
7429            retValue.remove(p);
7430
7431            return retValue;
7432        } else {
7433            return Collections.emptyList();
7434        }
7435    }
7436
7437    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7438            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7439        if (!collectedNames.contains(p.packageName)) {
7440            collectedNames.add(p.packageName);
7441            collected.add(p);
7442
7443            if (p.usesLibraries != null) {
7444                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7445            }
7446            if (p.usesOptionalLibraries != null) {
7447                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7448                        collectedNames);
7449            }
7450        }
7451    }
7452
7453    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7454            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7455        for (String libName : libs) {
7456            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7457            if (libPkg != null) {
7458                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7459            }
7460        }
7461    }
7462
7463    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7464        synchronized (mPackages) {
7465            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7466            if (lib != null && lib.apk != null) {
7467                return mPackages.get(lib.apk);
7468            }
7469        }
7470        return null;
7471    }
7472
7473    public void shutdown() {
7474        mPackageUsage.writeNow(mPackages);
7475        mCompilerStats.writeNow();
7476    }
7477
7478    @Override
7479    public void dumpProfiles(String packageName) {
7480        PackageParser.Package pkg;
7481        synchronized (mPackages) {
7482            pkg = mPackages.get(packageName);
7483            if (pkg == null) {
7484                throw new IllegalArgumentException("Unknown package: " + packageName);
7485            }
7486        }
7487        /* Only the shell, root, or the app user should be able to dump profiles. */
7488        int callingUid = Binder.getCallingUid();
7489        if (callingUid != Process.SHELL_UID &&
7490            callingUid != Process.ROOT_UID &&
7491            callingUid != pkg.applicationInfo.uid) {
7492            throw new SecurityException("dumpProfiles");
7493        }
7494
7495        synchronized (mInstallLock) {
7496            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7497            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7498            try {
7499                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7500                String gid = Integer.toString(sharedGid);
7501                String codePaths = TextUtils.join(";", allCodePaths);
7502                mInstaller.dumpProfiles(gid, packageName, codePaths);
7503            } catch (InstallerException e) {
7504                Slog.w(TAG, "Failed to dump profiles", e);
7505            }
7506            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7507        }
7508    }
7509
7510    @Override
7511    public void forceDexOpt(String packageName) {
7512        enforceSystemOrRoot("forceDexOpt");
7513
7514        PackageParser.Package pkg;
7515        synchronized (mPackages) {
7516            pkg = mPackages.get(packageName);
7517            if (pkg == null) {
7518                throw new IllegalArgumentException("Unknown package: " + packageName);
7519            }
7520        }
7521
7522        synchronized (mInstallLock) {
7523            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7524
7525            // Whoever is calling forceDexOpt wants a fully compiled package.
7526            // Don't use profiles since that may cause compilation to be skipped.
7527            final int res = performDexOptInternalWithDependenciesLI(pkg,
7528                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7529                    true /* force */);
7530
7531            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7532            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7533                throw new IllegalStateException("Failed to dexopt: " + res);
7534            }
7535        }
7536    }
7537
7538    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7539        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7540            Slog.w(TAG, "Unable to update from " + oldPkg.name
7541                    + " to " + newPkg.packageName
7542                    + ": old package not in system partition");
7543            return false;
7544        } else if (mPackages.get(oldPkg.name) != null) {
7545            Slog.w(TAG, "Unable to update from " + oldPkg.name
7546                    + " to " + newPkg.packageName
7547                    + ": old package still exists");
7548            return false;
7549        }
7550        return true;
7551    }
7552
7553    void removeCodePathLI(File codePath) {
7554        if (codePath.isDirectory()) {
7555            try {
7556                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7557            } catch (InstallerException e) {
7558                Slog.w(TAG, "Failed to remove code path", e);
7559            }
7560        } else {
7561            codePath.delete();
7562        }
7563    }
7564
7565    private int[] resolveUserIds(int userId) {
7566        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7567    }
7568
7569    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7570        if (pkg == null) {
7571            Slog.wtf(TAG, "Package was null!", new Throwable());
7572            return;
7573        }
7574        clearAppDataLeafLIF(pkg, userId, flags);
7575        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7576        for (int i = 0; i < childCount; i++) {
7577            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7578        }
7579    }
7580
7581    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7582        final PackageSetting ps;
7583        synchronized (mPackages) {
7584            ps = mSettings.mPackages.get(pkg.packageName);
7585        }
7586        for (int realUserId : resolveUserIds(userId)) {
7587            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7588            try {
7589                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7590                        ceDataInode);
7591            } catch (InstallerException e) {
7592                Slog.w(TAG, String.valueOf(e));
7593            }
7594        }
7595    }
7596
7597    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7598        if (pkg == null) {
7599            Slog.wtf(TAG, "Package was null!", new Throwable());
7600            return;
7601        }
7602        destroyAppDataLeafLIF(pkg, userId, flags);
7603        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7604        for (int i = 0; i < childCount; i++) {
7605            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7606        }
7607    }
7608
7609    private void destroyAppDataLeafLIF(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.destroyAppData(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 destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7626        if (pkg == null) {
7627            Slog.wtf(TAG, "Package was null!", new Throwable());
7628            return;
7629        }
7630        destroyAppProfilesLeafLIF(pkg);
7631        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7632        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7633        for (int i = 0; i < childCount; i++) {
7634            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7635            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7636                    true /* removeBaseMarker */);
7637        }
7638    }
7639
7640    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7641            boolean removeBaseMarker) {
7642        if (pkg.isForwardLocked()) {
7643            return;
7644        }
7645
7646        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7647            try {
7648                path = PackageManagerServiceUtils.realpath(new File(path));
7649            } catch (IOException e) {
7650                // TODO: Should we return early here ?
7651                Slog.w(TAG, "Failed to get canonical path", e);
7652                continue;
7653            }
7654
7655            final String useMarker = path.replace('/', '@');
7656            for (int realUserId : resolveUserIds(userId)) {
7657                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7658                if (removeBaseMarker) {
7659                    File foreignUseMark = new File(profileDir, useMarker);
7660                    if (foreignUseMark.exists()) {
7661                        if (!foreignUseMark.delete()) {
7662                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7663                                    + pkg.packageName);
7664                        }
7665                    }
7666                }
7667
7668                File[] markers = profileDir.listFiles();
7669                if (markers != null) {
7670                    final String searchString = "@" + pkg.packageName + "@";
7671                    // We also delete all markers that contain the package name we're
7672                    // uninstalling. These are associated with secondary dex-files belonging
7673                    // to the package. Reconstructing the path of these dex files is messy
7674                    // in general.
7675                    for (File marker : markers) {
7676                        if (marker.getName().indexOf(searchString) > 0) {
7677                            if (!marker.delete()) {
7678                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7679                                    + pkg.packageName);
7680                            }
7681                        }
7682                    }
7683                }
7684            }
7685        }
7686    }
7687
7688    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7689        try {
7690            mInstaller.destroyAppProfiles(pkg.packageName);
7691        } catch (InstallerException e) {
7692            Slog.w(TAG, String.valueOf(e));
7693        }
7694    }
7695
7696    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7697        if (pkg == null) {
7698            Slog.wtf(TAG, "Package was null!", new Throwable());
7699            return;
7700        }
7701        clearAppProfilesLeafLIF(pkg);
7702        // We don't remove the base foreign use marker when clearing profiles because
7703        // we will rename it when the app is updated. Unlike the actual profile contents,
7704        // the foreign use marker is good across installs.
7705        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7706        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7707        for (int i = 0; i < childCount; i++) {
7708            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7709        }
7710    }
7711
7712    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7713        try {
7714            mInstaller.clearAppProfiles(pkg.packageName);
7715        } catch (InstallerException e) {
7716            Slog.w(TAG, String.valueOf(e));
7717        }
7718    }
7719
7720    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7721            long lastUpdateTime) {
7722        // Set parent install/update time
7723        PackageSetting ps = (PackageSetting) pkg.mExtras;
7724        if (ps != null) {
7725            ps.firstInstallTime = firstInstallTime;
7726            ps.lastUpdateTime = lastUpdateTime;
7727        }
7728        // Set children install/update time
7729        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7730        for (int i = 0; i < childCount; i++) {
7731            PackageParser.Package childPkg = pkg.childPackages.get(i);
7732            ps = (PackageSetting) childPkg.mExtras;
7733            if (ps != null) {
7734                ps.firstInstallTime = firstInstallTime;
7735                ps.lastUpdateTime = lastUpdateTime;
7736            }
7737        }
7738    }
7739
7740    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7741            PackageParser.Package changingLib) {
7742        if (file.path != null) {
7743            usesLibraryFiles.add(file.path);
7744            return;
7745        }
7746        PackageParser.Package p = mPackages.get(file.apk);
7747        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7748            // If we are doing this while in the middle of updating a library apk,
7749            // then we need to make sure to use that new apk for determining the
7750            // dependencies here.  (We haven't yet finished committing the new apk
7751            // to the package manager state.)
7752            if (p == null || p.packageName.equals(changingLib.packageName)) {
7753                p = changingLib;
7754            }
7755        }
7756        if (p != null) {
7757            usesLibraryFiles.addAll(p.getAllCodePaths());
7758        }
7759    }
7760
7761    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7762            PackageParser.Package changingLib) throws PackageManagerException {
7763        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7764            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7765            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7766            for (int i=0; i<N; i++) {
7767                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7768                if (file == null) {
7769                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7770                            "Package " + pkg.packageName + " requires unavailable shared library "
7771                            + pkg.usesLibraries.get(i) + "; failing!");
7772                }
7773                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7774            }
7775            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7776            for (int i=0; i<N; i++) {
7777                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7778                if (file == null) {
7779                    Slog.w(TAG, "Package " + pkg.packageName
7780                            + " desires unavailable shared library "
7781                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7782                } else {
7783                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7784                }
7785            }
7786            N = usesLibraryFiles.size();
7787            if (N > 0) {
7788                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7789            } else {
7790                pkg.usesLibraryFiles = null;
7791            }
7792        }
7793    }
7794
7795    private static boolean hasString(List<String> list, List<String> which) {
7796        if (list == null) {
7797            return false;
7798        }
7799        for (int i=list.size()-1; i>=0; i--) {
7800            for (int j=which.size()-1; j>=0; j--) {
7801                if (which.get(j).equals(list.get(i))) {
7802                    return true;
7803                }
7804            }
7805        }
7806        return false;
7807    }
7808
7809    private void updateAllSharedLibrariesLPw() {
7810        for (PackageParser.Package pkg : mPackages.values()) {
7811            try {
7812                updateSharedLibrariesLPw(pkg, null);
7813            } catch (PackageManagerException e) {
7814                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7815            }
7816        }
7817    }
7818
7819    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7820            PackageParser.Package changingPkg) {
7821        ArrayList<PackageParser.Package> res = null;
7822        for (PackageParser.Package pkg : mPackages.values()) {
7823            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7824                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7825                if (res == null) {
7826                    res = new ArrayList<PackageParser.Package>();
7827                }
7828                res.add(pkg);
7829                try {
7830                    updateSharedLibrariesLPw(pkg, changingPkg);
7831                } catch (PackageManagerException e) {
7832                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7833                }
7834            }
7835        }
7836        return res;
7837    }
7838
7839    /**
7840     * Derive the value of the {@code cpuAbiOverride} based on the provided
7841     * value and an optional stored value from the package settings.
7842     */
7843    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7844        String cpuAbiOverride = null;
7845
7846        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7847            cpuAbiOverride = null;
7848        } else if (abiOverride != null) {
7849            cpuAbiOverride = abiOverride;
7850        } else if (settings != null) {
7851            cpuAbiOverride = settings.cpuAbiOverrideString;
7852        }
7853
7854        return cpuAbiOverride;
7855    }
7856
7857    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7858            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7859                    throws PackageManagerException {
7860        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7861        // If the package has children and this is the first dive in the function
7862        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7863        // whether all packages (parent and children) would be successfully scanned
7864        // before the actual scan since scanning mutates internal state and we want
7865        // to atomically install the package and its children.
7866        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7867            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7868                scanFlags |= SCAN_CHECK_ONLY;
7869            }
7870        } else {
7871            scanFlags &= ~SCAN_CHECK_ONLY;
7872        }
7873
7874        final PackageParser.Package scannedPkg;
7875        try {
7876            // Scan the parent
7877            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7878            // Scan the children
7879            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7880            for (int i = 0; i < childCount; i++) {
7881                PackageParser.Package childPkg = pkg.childPackages.get(i);
7882                scanPackageLI(childPkg, policyFlags,
7883                        scanFlags, currentTime, user);
7884            }
7885        } finally {
7886            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7887        }
7888
7889        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7890            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7891        }
7892
7893        return scannedPkg;
7894    }
7895
7896    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7897            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7898        boolean success = false;
7899        try {
7900            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7901                    currentTime, user);
7902            success = true;
7903            return res;
7904        } finally {
7905            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7906                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7907                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7908                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7909                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7910            }
7911        }
7912    }
7913
7914    /**
7915     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7916     */
7917    private static boolean apkHasCode(String fileName) {
7918        StrictJarFile jarFile = null;
7919        try {
7920            jarFile = new StrictJarFile(fileName,
7921                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7922            return jarFile.findEntry("classes.dex") != null;
7923        } catch (IOException ignore) {
7924        } finally {
7925            try {
7926                if (jarFile != null) {
7927                    jarFile.close();
7928                }
7929            } catch (IOException ignore) {}
7930        }
7931        return false;
7932    }
7933
7934    /**
7935     * Enforces code policy for the package. This ensures that if an APK has
7936     * declared hasCode="true" in its manifest that the APK actually contains
7937     * code.
7938     *
7939     * @throws PackageManagerException If bytecode could not be found when it should exist
7940     */
7941    private static void enforceCodePolicy(PackageParser.Package pkg)
7942            throws PackageManagerException {
7943        final boolean shouldHaveCode =
7944                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7945        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7946            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7947                    "Package " + pkg.baseCodePath + " code is missing");
7948        }
7949
7950        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7951            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7952                final boolean splitShouldHaveCode =
7953                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7954                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7955                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7956                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7957                }
7958            }
7959        }
7960    }
7961
7962    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7963            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7964            throws PackageManagerException {
7965        final File scanFile = new File(pkg.codePath);
7966        if (pkg.applicationInfo.getCodePath() == null ||
7967                pkg.applicationInfo.getResourcePath() == null) {
7968            // Bail out. The resource and code paths haven't been set.
7969            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7970                    "Code and resource paths haven't been set correctly");
7971        }
7972
7973        // Apply policy
7974        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7975            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7976            if (pkg.applicationInfo.isDirectBootAware()) {
7977                // we're direct boot aware; set for all components
7978                for (PackageParser.Service s : pkg.services) {
7979                    s.info.encryptionAware = s.info.directBootAware = true;
7980                }
7981                for (PackageParser.Provider p : pkg.providers) {
7982                    p.info.encryptionAware = p.info.directBootAware = true;
7983                }
7984                for (PackageParser.Activity a : pkg.activities) {
7985                    a.info.encryptionAware = a.info.directBootAware = true;
7986                }
7987                for (PackageParser.Activity r : pkg.receivers) {
7988                    r.info.encryptionAware = r.info.directBootAware = true;
7989                }
7990            }
7991        } else {
7992            // Only allow system apps to be flagged as core apps.
7993            pkg.coreApp = false;
7994            // clear flags not applicable to regular apps
7995            pkg.applicationInfo.privateFlags &=
7996                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7997            pkg.applicationInfo.privateFlags &=
7998                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7999        }
8000        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8001
8002        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8003            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8004        }
8005
8006        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8007            enforceCodePolicy(pkg);
8008        }
8009
8010        if (mCustomResolverComponentName != null &&
8011                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8012            setUpCustomResolverActivity(pkg);
8013        }
8014
8015        if (pkg.packageName.equals("android")) {
8016            synchronized (mPackages) {
8017                if (mAndroidApplication != null) {
8018                    Slog.w(TAG, "*************************************************");
8019                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8020                    Slog.w(TAG, " file=" + scanFile);
8021                    Slog.w(TAG, "*************************************************");
8022                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8023                            "Core android package being redefined.  Skipping.");
8024                }
8025
8026                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8027                    // Set up information for our fall-back user intent resolution activity.
8028                    mPlatformPackage = pkg;
8029                    pkg.mVersionCode = mSdkVersion;
8030                    mAndroidApplication = pkg.applicationInfo;
8031
8032                    if (!mResolverReplaced) {
8033                        mResolveActivity.applicationInfo = mAndroidApplication;
8034                        mResolveActivity.name = ResolverActivity.class.getName();
8035                        mResolveActivity.packageName = mAndroidApplication.packageName;
8036                        mResolveActivity.processName = "system:ui";
8037                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8038                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8039                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8040                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8041                        mResolveActivity.exported = true;
8042                        mResolveActivity.enabled = true;
8043                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8044                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8045                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8046                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8047                                | ActivityInfo.CONFIG_ORIENTATION
8048                                | ActivityInfo.CONFIG_KEYBOARD
8049                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8050                        mResolveInfo.activityInfo = mResolveActivity;
8051                        mResolveInfo.priority = 0;
8052                        mResolveInfo.preferredOrder = 0;
8053                        mResolveInfo.match = 0;
8054                        mResolveComponentName = new ComponentName(
8055                                mAndroidApplication.packageName, mResolveActivity.name);
8056                    }
8057                }
8058            }
8059        }
8060
8061        if (DEBUG_PACKAGE_SCANNING) {
8062            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8063                Log.d(TAG, "Scanning package " + pkg.packageName);
8064        }
8065
8066        synchronized (mPackages) {
8067            if (mPackages.containsKey(pkg.packageName)
8068                    || mSharedLibraries.containsKey(pkg.packageName)) {
8069                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8070                        "Application package " + pkg.packageName
8071                                + " already installed.  Skipping duplicate.");
8072            }
8073
8074            // If we're only installing presumed-existing packages, require that the
8075            // scanned APK is both already known and at the path previously established
8076            // for it.  Previously unknown packages we pick up normally, but if we have an
8077            // a priori expectation about this package's install presence, enforce it.
8078            // With a singular exception for new system packages. When an OTA contains
8079            // a new system package, we allow the codepath to change from a system location
8080            // to the user-installed location. If we don't allow this change, any newer,
8081            // user-installed version of the application will be ignored.
8082            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8083                if (mExpectingBetter.containsKey(pkg.packageName)) {
8084                    logCriticalInfo(Log.WARN,
8085                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8086                } else {
8087                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8088                    if (known != null) {
8089                        if (DEBUG_PACKAGE_SCANNING) {
8090                            Log.d(TAG, "Examining " + pkg.codePath
8091                                    + " and requiring known paths " + known.codePathString
8092                                    + " & " + known.resourcePathString);
8093                        }
8094                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8095                                || !pkg.applicationInfo.getResourcePath().equals(
8096                                known.resourcePathString)) {
8097                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8098                                    "Application package " + pkg.packageName
8099                                            + " found at " + pkg.applicationInfo.getCodePath()
8100                                            + " but expected at " + known.codePathString
8101                                            + "; ignoring.");
8102                        }
8103                    }
8104                }
8105            }
8106        }
8107
8108        // Initialize package source and resource directories
8109        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8110        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8111
8112        SharedUserSetting suid = null;
8113        PackageSetting pkgSetting = null;
8114
8115        if (!isSystemApp(pkg)) {
8116            // Only system apps can use these features.
8117            pkg.mOriginalPackages = null;
8118            pkg.mRealPackage = null;
8119            pkg.mAdoptPermissions = null;
8120        }
8121
8122        // Getting the package setting may have a side-effect, so if we
8123        // are only checking if scan would succeed, stash a copy of the
8124        // old setting to restore at the end.
8125        PackageSetting nonMutatedPs = null;
8126
8127        // writer
8128        synchronized (mPackages) {
8129            if (pkg.mSharedUserId != null) {
8130                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8131                if (suid == null) {
8132                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8133                            "Creating application package " + pkg.packageName
8134                            + " for shared user failed");
8135                }
8136                if (DEBUG_PACKAGE_SCANNING) {
8137                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8138                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8139                                + "): packages=" + suid.packages);
8140                }
8141            }
8142
8143            // Check if we are renaming from an original package name.
8144            PackageSetting origPackage = null;
8145            String realName = null;
8146            if (pkg.mOriginalPackages != null) {
8147                // This package may need to be renamed to a previously
8148                // installed name.  Let's check on that...
8149                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8150                if (pkg.mOriginalPackages.contains(renamed)) {
8151                    // This package had originally been installed as the
8152                    // original name, and we have already taken care of
8153                    // transitioning to the new one.  Just update the new
8154                    // one to continue using the old name.
8155                    realName = pkg.mRealPackage;
8156                    if (!pkg.packageName.equals(renamed)) {
8157                        // Callers into this function may have already taken
8158                        // care of renaming the package; only do it here if
8159                        // it is not already done.
8160                        pkg.setPackageName(renamed);
8161                    }
8162
8163                } else {
8164                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8165                        if ((origPackage = mSettings.peekPackageLPr(
8166                                pkg.mOriginalPackages.get(i))) != null) {
8167                            // We do have the package already installed under its
8168                            // original name...  should we use it?
8169                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8170                                // New package is not compatible with original.
8171                                origPackage = null;
8172                                continue;
8173                            } else if (origPackage.sharedUser != null) {
8174                                // Make sure uid is compatible between packages.
8175                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8176                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8177                                            + " to " + pkg.packageName + ": old uid "
8178                                            + origPackage.sharedUser.name
8179                                            + " differs from " + pkg.mSharedUserId);
8180                                    origPackage = null;
8181                                    continue;
8182                                }
8183                                // TODO: Add case when shared user id is added [b/28144775]
8184                            } else {
8185                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8186                                        + pkg.packageName + " to old name " + origPackage.name);
8187                            }
8188                            break;
8189                        }
8190                    }
8191                }
8192            }
8193
8194            if (mTransferedPackages.contains(pkg.packageName)) {
8195                Slog.w(TAG, "Package " + pkg.packageName
8196                        + " was transferred to another, but its .apk remains");
8197            }
8198
8199            // See comments in nonMutatedPs declaration
8200            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8201                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8202                if (foundPs != null) {
8203                    nonMutatedPs = new PackageSetting(foundPs);
8204                }
8205            }
8206
8207            // Just create the setting, don't add it yet. For already existing packages
8208            // the PkgSetting exists already and doesn't have to be created.
8209            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8210                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8211                    pkg.applicationInfo.primaryCpuAbi,
8212                    pkg.applicationInfo.secondaryCpuAbi,
8213                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8214                    user, false);
8215            if (pkgSetting == null) {
8216                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8217                        "Creating application package " + pkg.packageName + " failed");
8218            }
8219
8220            if (pkgSetting.origPackage != null) {
8221                // If we are first transitioning from an original package,
8222                // fix up the new package's name now.  We need to do this after
8223                // looking up the package under its new name, so getPackageLP
8224                // can take care of fiddling things correctly.
8225                pkg.setPackageName(origPackage.name);
8226
8227                // File a report about this.
8228                String msg = "New package " + pkgSetting.realName
8229                        + " renamed to replace old package " + pkgSetting.name;
8230                reportSettingsProblem(Log.WARN, msg);
8231
8232                // Make a note of it.
8233                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8234                    mTransferedPackages.add(origPackage.name);
8235                }
8236
8237                // No longer need to retain this.
8238                pkgSetting.origPackage = null;
8239            }
8240
8241            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8242                // Make a note of it.
8243                mTransferedPackages.add(pkg.packageName);
8244            }
8245
8246            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8247                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8248            }
8249
8250            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8251                // Check all shared libraries and map to their actual file path.
8252                // We only do this here for apps not on a system dir, because those
8253                // are the only ones that can fail an install due to this.  We
8254                // will take care of the system apps by updating all of their
8255                // library paths after the scan is done.
8256                updateSharedLibrariesLPw(pkg, null);
8257            }
8258
8259            if (mFoundPolicyFile) {
8260                SELinuxMMAC.assignSeinfoValue(pkg);
8261            }
8262
8263            pkg.applicationInfo.uid = pkgSetting.appId;
8264            pkg.mExtras = pkgSetting;
8265            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8266                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8267                    // We just determined the app is signed correctly, so bring
8268                    // over the latest parsed certs.
8269                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8270                } else {
8271                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8272                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8273                                "Package " + pkg.packageName + " upgrade keys do not match the "
8274                                + "previously installed version");
8275                    } else {
8276                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8277                        String msg = "System package " + pkg.packageName
8278                            + " signature changed; retaining data.";
8279                        reportSettingsProblem(Log.WARN, msg);
8280                    }
8281                }
8282            } else {
8283                try {
8284                    verifySignaturesLP(pkgSetting, pkg);
8285                    // We just determined the app is signed correctly, so bring
8286                    // over the latest parsed certs.
8287                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8288                } catch (PackageManagerException e) {
8289                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8290                        throw e;
8291                    }
8292                    // The signature has changed, but this package is in the system
8293                    // image...  let's recover!
8294                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8295                    // However...  if this package is part of a shared user, but it
8296                    // doesn't match the signature of the shared user, let's fail.
8297                    // What this means is that you can't change the signatures
8298                    // associated with an overall shared user, which doesn't seem all
8299                    // that unreasonable.
8300                    if (pkgSetting.sharedUser != null) {
8301                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8302                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8303                            throw new PackageManagerException(
8304                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8305                                            "Signature mismatch for shared user: "
8306                                            + pkgSetting.sharedUser);
8307                        }
8308                    }
8309                    // File a report about this.
8310                    String msg = "System package " + pkg.packageName
8311                        + " signature changed; retaining data.";
8312                    reportSettingsProblem(Log.WARN, msg);
8313                }
8314            }
8315            // Verify that this new package doesn't have any content providers
8316            // that conflict with existing packages.  Only do this if the
8317            // package isn't already installed, since we don't want to break
8318            // things that are installed.
8319            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8320                final int N = pkg.providers.size();
8321                int i;
8322                for (i=0; i<N; i++) {
8323                    PackageParser.Provider p = pkg.providers.get(i);
8324                    if (p.info.authority != null) {
8325                        String names[] = p.info.authority.split(";");
8326                        for (int j = 0; j < names.length; j++) {
8327                            if (mProvidersByAuthority.containsKey(names[j])) {
8328                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8329                                final String otherPackageName =
8330                                        ((other != null && other.getComponentName() != null) ?
8331                                                other.getComponentName().getPackageName() : "?");
8332                                throw new PackageManagerException(
8333                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8334                                                "Can't install because provider name " + names[j]
8335                                                + " (in package " + pkg.applicationInfo.packageName
8336                                                + ") is already used by " + otherPackageName);
8337                            }
8338                        }
8339                    }
8340                }
8341            }
8342
8343            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8344                // This package wants to adopt ownership of permissions from
8345                // another package.
8346                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8347                    final String origName = pkg.mAdoptPermissions.get(i);
8348                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8349                    if (orig != null) {
8350                        if (verifyPackageUpdateLPr(orig, pkg)) {
8351                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8352                                    + pkg.packageName);
8353                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8354                        }
8355                    }
8356                }
8357            }
8358        }
8359
8360        final String pkgName = pkg.packageName;
8361
8362        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8363        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8364        pkg.applicationInfo.processName = fixProcessName(
8365                pkg.applicationInfo.packageName,
8366                pkg.applicationInfo.processName,
8367                pkg.applicationInfo.uid);
8368
8369        if (pkg != mPlatformPackage) {
8370            // Get all of our default paths setup
8371            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8372        }
8373
8374        final String path = scanFile.getPath();
8375        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8376
8377        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8378            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8379
8380            // Some system apps still use directory structure for native libraries
8381            // in which case we might end up not detecting abi solely based on apk
8382            // structure. Try to detect abi based on directory structure.
8383            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8384                    pkg.applicationInfo.primaryCpuAbi == null) {
8385                setBundledAppAbisAndRoots(pkg, pkgSetting);
8386                setNativeLibraryPaths(pkg);
8387            }
8388
8389        } else {
8390            if ((scanFlags & SCAN_MOVE) != 0) {
8391                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8392                // but we already have this packages package info in the PackageSetting. We just
8393                // use that and derive the native library path based on the new codepath.
8394                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8395                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8396            }
8397
8398            // Set native library paths again. For moves, the path will be updated based on the
8399            // ABIs we've determined above. For non-moves, the path will be updated based on the
8400            // ABIs we determined during compilation, but the path will depend on the final
8401            // package path (after the rename away from the stage path).
8402            setNativeLibraryPaths(pkg);
8403        }
8404
8405        // This is a special case for the "system" package, where the ABI is
8406        // dictated by the zygote configuration (and init.rc). We should keep track
8407        // of this ABI so that we can deal with "normal" applications that run under
8408        // the same UID correctly.
8409        if (mPlatformPackage == pkg) {
8410            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8411                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8412        }
8413
8414        // If there's a mismatch between the abi-override in the package setting
8415        // and the abiOverride specified for the install. Warn about this because we
8416        // would've already compiled the app without taking the package setting into
8417        // account.
8418        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8419            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8420                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8421                        " for package " + pkg.packageName);
8422            }
8423        }
8424
8425        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8426        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8427        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8428
8429        // Copy the derived override back to the parsed package, so that we can
8430        // update the package settings accordingly.
8431        pkg.cpuAbiOverride = cpuAbiOverride;
8432
8433        if (DEBUG_ABI_SELECTION) {
8434            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8435                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8436                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8437        }
8438
8439        // Push the derived path down into PackageSettings so we know what to
8440        // clean up at uninstall time.
8441        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8442
8443        if (DEBUG_ABI_SELECTION) {
8444            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8445                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8446                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8447        }
8448
8449        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8450            // We don't do this here during boot because we can do it all
8451            // at once after scanning all existing packages.
8452            //
8453            // We also do this *before* we perform dexopt on this package, so that
8454            // we can avoid redundant dexopts, and also to make sure we've got the
8455            // code and package path correct.
8456            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8457                    pkg, true /* boot complete */);
8458        }
8459
8460        if (mFactoryTest && pkg.requestedPermissions.contains(
8461                android.Manifest.permission.FACTORY_TEST)) {
8462            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8463        }
8464
8465        if (isSystemApp(pkg)) {
8466            pkgSetting.isOrphaned = true;
8467        }
8468
8469        ArrayList<PackageParser.Package> clientLibPkgs = null;
8470
8471        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8472            if (nonMutatedPs != null) {
8473                synchronized (mPackages) {
8474                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8475                }
8476            }
8477            return pkg;
8478        }
8479
8480        // Only privileged apps and updated privileged apps can add child packages.
8481        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8482            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8483                throw new PackageManagerException("Only privileged apps and updated "
8484                        + "privileged apps can add child packages. Ignoring package "
8485                        + pkg.packageName);
8486            }
8487            final int childCount = pkg.childPackages.size();
8488            for (int i = 0; i < childCount; i++) {
8489                PackageParser.Package childPkg = pkg.childPackages.get(i);
8490                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8491                        childPkg.packageName)) {
8492                    throw new PackageManagerException("Cannot override a child package of "
8493                            + "another disabled system app. Ignoring package " + pkg.packageName);
8494                }
8495            }
8496        }
8497
8498        // writer
8499        synchronized (mPackages) {
8500            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8501                // Only system apps can add new shared libraries.
8502                if (pkg.libraryNames != null) {
8503                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8504                        String name = pkg.libraryNames.get(i);
8505                        boolean allowed = false;
8506                        if (pkg.isUpdatedSystemApp()) {
8507                            // New library entries can only be added through the
8508                            // system image.  This is important to get rid of a lot
8509                            // of nasty edge cases: for example if we allowed a non-
8510                            // system update of the app to add a library, then uninstalling
8511                            // the update would make the library go away, and assumptions
8512                            // we made such as through app install filtering would now
8513                            // have allowed apps on the device which aren't compatible
8514                            // with it.  Better to just have the restriction here, be
8515                            // conservative, and create many fewer cases that can negatively
8516                            // impact the user experience.
8517                            final PackageSetting sysPs = mSettings
8518                                    .getDisabledSystemPkgLPr(pkg.packageName);
8519                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8520                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8521                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8522                                        allowed = true;
8523                                        break;
8524                                    }
8525                                }
8526                            }
8527                        } else {
8528                            allowed = true;
8529                        }
8530                        if (allowed) {
8531                            if (!mSharedLibraries.containsKey(name)) {
8532                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8533                            } else if (!name.equals(pkg.packageName)) {
8534                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8535                                        + name + " already exists; skipping");
8536                            }
8537                        } else {
8538                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8539                                    + name + " that is not declared on system image; skipping");
8540                        }
8541                    }
8542                    if ((scanFlags & SCAN_BOOTING) == 0) {
8543                        // If we are not booting, we need to update any applications
8544                        // that are clients of our shared library.  If we are booting,
8545                        // this will all be done once the scan is complete.
8546                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8547                    }
8548                }
8549            }
8550        }
8551
8552        if ((scanFlags & SCAN_BOOTING) != 0) {
8553            // No apps can run during boot scan, so they don't need to be frozen
8554        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8555            // Caller asked to not kill app, so it's probably not frozen
8556        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8557            // Caller asked us to ignore frozen check for some reason; they
8558            // probably didn't know the package name
8559        } else {
8560            // We're doing major surgery on this package, so it better be frozen
8561            // right now to keep it from launching
8562            checkPackageFrozen(pkgName);
8563        }
8564
8565        // Also need to kill any apps that are dependent on the library.
8566        if (clientLibPkgs != null) {
8567            for (int i=0; i<clientLibPkgs.size(); i++) {
8568                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8569                killApplication(clientPkg.applicationInfo.packageName,
8570                        clientPkg.applicationInfo.uid, "update lib");
8571            }
8572        }
8573
8574        // Make sure we're not adding any bogus keyset info
8575        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8576        ksms.assertScannedPackageValid(pkg);
8577
8578        // writer
8579        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8580
8581        boolean createIdmapFailed = false;
8582        synchronized (mPackages) {
8583            // We don't expect installation to fail beyond this point
8584
8585            if (pkgSetting.pkg != null) {
8586                // Note that |user| might be null during the initial boot scan. If a codePath
8587                // for an app has changed during a boot scan, it's due to an app update that's
8588                // part of the system partition and marker changes must be applied to all users.
8589                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8590                    (user != null) ? user : UserHandle.ALL);
8591            }
8592
8593            // Add the new setting to mSettings
8594            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8595            // Add the new setting to mPackages
8596            mPackages.put(pkg.applicationInfo.packageName, pkg);
8597            // Make sure we don't accidentally delete its data.
8598            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8599            while (iter.hasNext()) {
8600                PackageCleanItem item = iter.next();
8601                if (pkgName.equals(item.packageName)) {
8602                    iter.remove();
8603                }
8604            }
8605
8606            // Take care of first install / last update times.
8607            if (currentTime != 0) {
8608                if (pkgSetting.firstInstallTime == 0) {
8609                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8610                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8611                    pkgSetting.lastUpdateTime = currentTime;
8612                }
8613            } else if (pkgSetting.firstInstallTime == 0) {
8614                // We need *something*.  Take time time stamp of the file.
8615                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8616            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8617                if (scanFileTime != pkgSetting.timeStamp) {
8618                    // A package on the system image has changed; consider this
8619                    // to be an update.
8620                    pkgSetting.lastUpdateTime = scanFileTime;
8621                }
8622            }
8623
8624            // Add the package's KeySets to the global KeySetManagerService
8625            ksms.addScannedPackageLPw(pkg);
8626
8627            int N = pkg.providers.size();
8628            StringBuilder r = null;
8629            int i;
8630            for (i=0; i<N; i++) {
8631                PackageParser.Provider p = pkg.providers.get(i);
8632                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8633                        p.info.processName, pkg.applicationInfo.uid);
8634                mProviders.addProvider(p);
8635                p.syncable = p.info.isSyncable;
8636                if (p.info.authority != null) {
8637                    String names[] = p.info.authority.split(";");
8638                    p.info.authority = null;
8639                    for (int j = 0; j < names.length; j++) {
8640                        if (j == 1 && p.syncable) {
8641                            // We only want the first authority for a provider to possibly be
8642                            // syncable, so if we already added this provider using a different
8643                            // authority clear the syncable flag. We copy the provider before
8644                            // changing it because the mProviders object contains a reference
8645                            // to a provider that we don't want to change.
8646                            // Only do this for the second authority since the resulting provider
8647                            // object can be the same for all future authorities for this provider.
8648                            p = new PackageParser.Provider(p);
8649                            p.syncable = false;
8650                        }
8651                        if (!mProvidersByAuthority.containsKey(names[j])) {
8652                            mProvidersByAuthority.put(names[j], p);
8653                            if (p.info.authority == null) {
8654                                p.info.authority = names[j];
8655                            } else {
8656                                p.info.authority = p.info.authority + ";" + names[j];
8657                            }
8658                            if (DEBUG_PACKAGE_SCANNING) {
8659                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8660                                    Log.d(TAG, "Registered content provider: " + names[j]
8661                                            + ", className = " + p.info.name + ", isSyncable = "
8662                                            + p.info.isSyncable);
8663                            }
8664                        } else {
8665                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8666                            Slog.w(TAG, "Skipping provider name " + names[j] +
8667                                    " (in package " + pkg.applicationInfo.packageName +
8668                                    "): name already used by "
8669                                    + ((other != null && other.getComponentName() != null)
8670                                            ? other.getComponentName().getPackageName() : "?"));
8671                        }
8672                    }
8673                }
8674                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8675                    if (r == null) {
8676                        r = new StringBuilder(256);
8677                    } else {
8678                        r.append(' ');
8679                    }
8680                    r.append(p.info.name);
8681                }
8682            }
8683            if (r != null) {
8684                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8685            }
8686
8687            N = pkg.services.size();
8688            r = null;
8689            for (i=0; i<N; i++) {
8690                PackageParser.Service s = pkg.services.get(i);
8691                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8692                        s.info.processName, pkg.applicationInfo.uid);
8693                mServices.addService(s);
8694                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8695                    if (r == null) {
8696                        r = new StringBuilder(256);
8697                    } else {
8698                        r.append(' ');
8699                    }
8700                    r.append(s.info.name);
8701                }
8702            }
8703            if (r != null) {
8704                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8705            }
8706
8707            N = pkg.receivers.size();
8708            r = null;
8709            for (i=0; i<N; i++) {
8710                PackageParser.Activity a = pkg.receivers.get(i);
8711                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8712                        a.info.processName, pkg.applicationInfo.uid);
8713                mReceivers.addActivity(a, "receiver");
8714                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8715                    if (r == null) {
8716                        r = new StringBuilder(256);
8717                    } else {
8718                        r.append(' ');
8719                    }
8720                    r.append(a.info.name);
8721                }
8722            }
8723            if (r != null) {
8724                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8725            }
8726
8727            N = pkg.activities.size();
8728            r = null;
8729            for (i=0; i<N; i++) {
8730                PackageParser.Activity a = pkg.activities.get(i);
8731                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8732                        a.info.processName, pkg.applicationInfo.uid);
8733                mActivities.addActivity(a, "activity");
8734                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8735                    if (r == null) {
8736                        r = new StringBuilder(256);
8737                    } else {
8738                        r.append(' ');
8739                    }
8740                    r.append(a.info.name);
8741                }
8742            }
8743            if (r != null) {
8744                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8745            }
8746
8747            N = pkg.permissionGroups.size();
8748            r = null;
8749            for (i=0; i<N; i++) {
8750                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8751                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8752                final String curPackageName = cur == null ? null : cur.info.packageName;
8753                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8754                if (cur == null || isPackageUpdate) {
8755                    mPermissionGroups.put(pg.info.name, pg);
8756                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8757                        if (r == null) {
8758                            r = new StringBuilder(256);
8759                        } else {
8760                            r.append(' ');
8761                        }
8762                        if (isPackageUpdate) {
8763                            r.append("UPD:");
8764                        }
8765                        r.append(pg.info.name);
8766                    }
8767                } else {
8768                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8769                            + pg.info.packageName + " ignored: original from "
8770                            + cur.info.packageName);
8771                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8772                        if (r == null) {
8773                            r = new StringBuilder(256);
8774                        } else {
8775                            r.append(' ');
8776                        }
8777                        r.append("DUP:");
8778                        r.append(pg.info.name);
8779                    }
8780                }
8781            }
8782            if (r != null) {
8783                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8784            }
8785
8786            N = pkg.permissions.size();
8787            r = null;
8788            for (i=0; i<N; i++) {
8789                PackageParser.Permission p = pkg.permissions.get(i);
8790
8791                // Assume by default that we did not install this permission into the system.
8792                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8793
8794                // Now that permission groups have a special meaning, we ignore permission
8795                // groups for legacy apps to prevent unexpected behavior. In particular,
8796                // permissions for one app being granted to someone just becase they happen
8797                // to be in a group defined by another app (before this had no implications).
8798                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8799                    p.group = mPermissionGroups.get(p.info.group);
8800                    // Warn for a permission in an unknown group.
8801                    if (p.info.group != null && p.group == null) {
8802                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8803                                + p.info.packageName + " in an unknown group " + p.info.group);
8804                    }
8805                }
8806
8807                ArrayMap<String, BasePermission> permissionMap =
8808                        p.tree ? mSettings.mPermissionTrees
8809                                : mSettings.mPermissions;
8810                BasePermission bp = permissionMap.get(p.info.name);
8811
8812                // Allow system apps to redefine non-system permissions
8813                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8814                    final boolean currentOwnerIsSystem = (bp.perm != null
8815                            && isSystemApp(bp.perm.owner));
8816                    if (isSystemApp(p.owner)) {
8817                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8818                            // It's a built-in permission and no owner, take ownership now
8819                            bp.packageSetting = pkgSetting;
8820                            bp.perm = p;
8821                            bp.uid = pkg.applicationInfo.uid;
8822                            bp.sourcePackage = p.info.packageName;
8823                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8824                        } else if (!currentOwnerIsSystem) {
8825                            String msg = "New decl " + p.owner + " of permission  "
8826                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8827                            reportSettingsProblem(Log.WARN, msg);
8828                            bp = null;
8829                        }
8830                    }
8831                }
8832
8833                if (bp == null) {
8834                    bp = new BasePermission(p.info.name, p.info.packageName,
8835                            BasePermission.TYPE_NORMAL);
8836                    permissionMap.put(p.info.name, bp);
8837                }
8838
8839                if (bp.perm == null) {
8840                    if (bp.sourcePackage == null
8841                            || bp.sourcePackage.equals(p.info.packageName)) {
8842                        BasePermission tree = findPermissionTreeLP(p.info.name);
8843                        if (tree == null
8844                                || tree.sourcePackage.equals(p.info.packageName)) {
8845                            bp.packageSetting = pkgSetting;
8846                            bp.perm = p;
8847                            bp.uid = pkg.applicationInfo.uid;
8848                            bp.sourcePackage = p.info.packageName;
8849                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8850                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8851                                if (r == null) {
8852                                    r = new StringBuilder(256);
8853                                } else {
8854                                    r.append(' ');
8855                                }
8856                                r.append(p.info.name);
8857                            }
8858                        } else {
8859                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8860                                    + p.info.packageName + " ignored: base tree "
8861                                    + tree.name + " is from package "
8862                                    + tree.sourcePackage);
8863                        }
8864                    } else {
8865                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8866                                + p.info.packageName + " ignored: original from "
8867                                + bp.sourcePackage);
8868                    }
8869                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8870                    if (r == null) {
8871                        r = new StringBuilder(256);
8872                    } else {
8873                        r.append(' ');
8874                    }
8875                    r.append("DUP:");
8876                    r.append(p.info.name);
8877                }
8878                if (bp.perm == p) {
8879                    bp.protectionLevel = p.info.protectionLevel;
8880                }
8881            }
8882
8883            if (r != null) {
8884                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8885            }
8886
8887            N = pkg.instrumentation.size();
8888            r = null;
8889            for (i=0; i<N; i++) {
8890                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8891                a.info.packageName = pkg.applicationInfo.packageName;
8892                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8893                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8894                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8895                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8896                a.info.dataDir = pkg.applicationInfo.dataDir;
8897                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8898                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8899
8900                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8901                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8902                mInstrumentation.put(a.getComponentName(), a);
8903                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8904                    if (r == null) {
8905                        r = new StringBuilder(256);
8906                    } else {
8907                        r.append(' ');
8908                    }
8909                    r.append(a.info.name);
8910                }
8911            }
8912            if (r != null) {
8913                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8914            }
8915
8916            if (pkg.protectedBroadcasts != null) {
8917                N = pkg.protectedBroadcasts.size();
8918                for (i=0; i<N; i++) {
8919                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8920                }
8921            }
8922
8923            pkgSetting.setTimeStamp(scanFileTime);
8924
8925            // Create idmap files for pairs of (packages, overlay packages).
8926            // Note: "android", ie framework-res.apk, is handled by native layers.
8927            if (pkg.mOverlayTarget != null) {
8928                // This is an overlay package.
8929                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8930                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8931                        mOverlays.put(pkg.mOverlayTarget,
8932                                new ArrayMap<String, PackageParser.Package>());
8933                    }
8934                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8935                    map.put(pkg.packageName, pkg);
8936                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8937                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8938                        createIdmapFailed = true;
8939                    }
8940                }
8941            } else if (mOverlays.containsKey(pkg.packageName) &&
8942                    !pkg.packageName.equals("android")) {
8943                // This is a regular package, with one or more known overlay packages.
8944                createIdmapsForPackageLI(pkg);
8945            }
8946        }
8947
8948        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8949
8950        if (createIdmapFailed) {
8951            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8952                    "scanPackageLI failed to createIdmap");
8953        }
8954        return pkg;
8955    }
8956
8957    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
8958            PackageParser.Package update, UserHandle user) {
8959        if (existing.applicationInfo == null || update.applicationInfo == null) {
8960            // This isn't due to an app installation.
8961            return;
8962        }
8963
8964        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
8965        final File newCodePath = new File(update.applicationInfo.getCodePath());
8966
8967        // The codePath hasn't changed, so there's nothing for us to do.
8968        if (Objects.equals(oldCodePath, newCodePath)) {
8969            return;
8970        }
8971
8972        File canonicalNewCodePath;
8973        try {
8974            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
8975        } catch (IOException e) {
8976            Slog.w(TAG, "Failed to get canonical path.", e);
8977            return;
8978        }
8979
8980        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
8981        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
8982        // that the last component of the path (i.e, the name) doesn't need canonicalization
8983        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
8984        // but may change in the future. Hopefully this function won't exist at that point.
8985        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
8986                oldCodePath.getName());
8987
8988        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
8989        // with "@".
8990        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
8991        if (!oldMarkerPrefix.endsWith("@")) {
8992            oldMarkerPrefix += "@";
8993        }
8994        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
8995        if (!newMarkerPrefix.endsWith("@")) {
8996            newMarkerPrefix += "@";
8997        }
8998
8999        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9000        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9001        for (String updatedPath : updatedPaths) {
9002            String updatedPathName = new File(updatedPath).getName();
9003            markerSuffixes.add(updatedPathName.replace('/', '@'));
9004        }
9005
9006        for (int userId : resolveUserIds(user.getIdentifier())) {
9007            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9008
9009            for (String markerSuffix : markerSuffixes) {
9010                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9011                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9012                if (oldForeignUseMark.exists()) {
9013                    try {
9014                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9015                                newForeignUseMark.getAbsolutePath());
9016                    } catch (ErrnoException e) {
9017                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9018                        oldForeignUseMark.delete();
9019                    }
9020                }
9021            }
9022        }
9023    }
9024
9025    /**
9026     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9027     * is derived purely on the basis of the contents of {@code scanFile} and
9028     * {@code cpuAbiOverride}.
9029     *
9030     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9031     */
9032    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9033                                 String cpuAbiOverride, boolean extractLibs)
9034            throws PackageManagerException {
9035        // TODO: We can probably be smarter about this stuff. For installed apps,
9036        // we can calculate this information at install time once and for all. For
9037        // system apps, we can probably assume that this information doesn't change
9038        // after the first boot scan. As things stand, we do lots of unnecessary work.
9039
9040        // Give ourselves some initial paths; we'll come back for another
9041        // pass once we've determined ABI below.
9042        setNativeLibraryPaths(pkg);
9043
9044        // We would never need to extract libs for forward-locked and external packages,
9045        // since the container service will do it for us. We shouldn't attempt to
9046        // extract libs from system app when it was not updated.
9047        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9048                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9049            extractLibs = false;
9050        }
9051
9052        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9053        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9054
9055        NativeLibraryHelper.Handle handle = null;
9056        try {
9057            handle = NativeLibraryHelper.Handle.create(pkg);
9058            // TODO(multiArch): This can be null for apps that didn't go through the
9059            // usual installation process. We can calculate it again, like we
9060            // do during install time.
9061            //
9062            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9063            // unnecessary.
9064            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9065
9066            // Null out the abis so that they can be recalculated.
9067            pkg.applicationInfo.primaryCpuAbi = null;
9068            pkg.applicationInfo.secondaryCpuAbi = null;
9069            if (isMultiArch(pkg.applicationInfo)) {
9070                // Warn if we've set an abiOverride for multi-lib packages..
9071                // By definition, we need to copy both 32 and 64 bit libraries for
9072                // such packages.
9073                if (pkg.cpuAbiOverride != null
9074                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9075                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9076                }
9077
9078                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9079                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9080                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9081                    if (extractLibs) {
9082                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9083                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9084                                useIsaSpecificSubdirs);
9085                    } else {
9086                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9087                    }
9088                }
9089
9090                maybeThrowExceptionForMultiArchCopy(
9091                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9092
9093                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9094                    if (extractLibs) {
9095                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9096                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9097                                useIsaSpecificSubdirs);
9098                    } else {
9099                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9100                    }
9101                }
9102
9103                maybeThrowExceptionForMultiArchCopy(
9104                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9105
9106                if (abi64 >= 0) {
9107                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9108                }
9109
9110                if (abi32 >= 0) {
9111                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9112                    if (abi64 >= 0) {
9113                        if (pkg.use32bitAbi) {
9114                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9115                            pkg.applicationInfo.primaryCpuAbi = abi;
9116                        } else {
9117                            pkg.applicationInfo.secondaryCpuAbi = abi;
9118                        }
9119                    } else {
9120                        pkg.applicationInfo.primaryCpuAbi = abi;
9121                    }
9122                }
9123
9124            } else {
9125                String[] abiList = (cpuAbiOverride != null) ?
9126                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9127
9128                // Enable gross and lame hacks for apps that are built with old
9129                // SDK tools. We must scan their APKs for renderscript bitcode and
9130                // not launch them if it's present. Don't bother checking on devices
9131                // that don't have 64 bit support.
9132                boolean needsRenderScriptOverride = false;
9133                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9134                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9135                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9136                    needsRenderScriptOverride = true;
9137                }
9138
9139                final int copyRet;
9140                if (extractLibs) {
9141                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9142                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9143                } else {
9144                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9145                }
9146
9147                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9148                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9149                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9150                }
9151
9152                if (copyRet >= 0) {
9153                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9154                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9155                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9156                } else if (needsRenderScriptOverride) {
9157                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9158                }
9159            }
9160        } catch (IOException ioe) {
9161            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9162        } finally {
9163            IoUtils.closeQuietly(handle);
9164        }
9165
9166        // Now that we've calculated the ABIs and determined if it's an internal app,
9167        // we will go ahead and populate the nativeLibraryPath.
9168        setNativeLibraryPaths(pkg);
9169    }
9170
9171    /**
9172     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9173     * i.e, so that all packages can be run inside a single process if required.
9174     *
9175     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9176     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9177     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9178     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9179     * updating a package that belongs to a shared user.
9180     *
9181     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9182     * adds unnecessary complexity.
9183     */
9184    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9185            PackageParser.Package scannedPackage, boolean bootComplete) {
9186        String requiredInstructionSet = null;
9187        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9188            requiredInstructionSet = VMRuntime.getInstructionSet(
9189                     scannedPackage.applicationInfo.primaryCpuAbi);
9190        }
9191
9192        PackageSetting requirer = null;
9193        for (PackageSetting ps : packagesForUser) {
9194            // If packagesForUser contains scannedPackage, we skip it. This will happen
9195            // when scannedPackage is an update of an existing package. Without this check,
9196            // we will never be able to change the ABI of any package belonging to a shared
9197            // user, even if it's compatible with other packages.
9198            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9199                if (ps.primaryCpuAbiString == null) {
9200                    continue;
9201                }
9202
9203                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9204                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9205                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9206                    // this but there's not much we can do.
9207                    String errorMessage = "Instruction set mismatch, "
9208                            + ((requirer == null) ? "[caller]" : requirer)
9209                            + " requires " + requiredInstructionSet + " whereas " + ps
9210                            + " requires " + instructionSet;
9211                    Slog.w(TAG, errorMessage);
9212                }
9213
9214                if (requiredInstructionSet == null) {
9215                    requiredInstructionSet = instructionSet;
9216                    requirer = ps;
9217                }
9218            }
9219        }
9220
9221        if (requiredInstructionSet != null) {
9222            String adjustedAbi;
9223            if (requirer != null) {
9224                // requirer != null implies that either scannedPackage was null or that scannedPackage
9225                // did not require an ABI, in which case we have to adjust scannedPackage to match
9226                // the ABI of the set (which is the same as requirer's ABI)
9227                adjustedAbi = requirer.primaryCpuAbiString;
9228                if (scannedPackage != null) {
9229                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9230                }
9231            } else {
9232                // requirer == null implies that we're updating all ABIs in the set to
9233                // match scannedPackage.
9234                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9235            }
9236
9237            for (PackageSetting ps : packagesForUser) {
9238                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9239                    if (ps.primaryCpuAbiString != null) {
9240                        continue;
9241                    }
9242
9243                    ps.primaryCpuAbiString = adjustedAbi;
9244                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9245                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9246                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9247                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9248                                + " (requirer="
9249                                + (requirer == null ? "null" : requirer.pkg.packageName)
9250                                + ", scannedPackage="
9251                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9252                                + ")");
9253                        try {
9254                            mInstaller.rmdex(ps.codePathString,
9255                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9256                        } catch (InstallerException ignored) {
9257                        }
9258                    }
9259                }
9260            }
9261        }
9262    }
9263
9264    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9265        synchronized (mPackages) {
9266            mResolverReplaced = true;
9267            // Set up information for custom user intent resolution activity.
9268            mResolveActivity.applicationInfo = pkg.applicationInfo;
9269            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9270            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9271            mResolveActivity.processName = pkg.applicationInfo.packageName;
9272            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9273            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9274                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9275            mResolveActivity.theme = 0;
9276            mResolveActivity.exported = true;
9277            mResolveActivity.enabled = true;
9278            mResolveInfo.activityInfo = mResolveActivity;
9279            mResolveInfo.priority = 0;
9280            mResolveInfo.preferredOrder = 0;
9281            mResolveInfo.match = 0;
9282            mResolveComponentName = mCustomResolverComponentName;
9283            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9284                    mResolveComponentName);
9285        }
9286    }
9287
9288    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9289        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9290
9291        // Set up information for ephemeral installer activity
9292        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9293        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9294        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9295        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9296        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9297        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9298                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9299        mEphemeralInstallerActivity.theme = 0;
9300        mEphemeralInstallerActivity.exported = true;
9301        mEphemeralInstallerActivity.enabled = true;
9302        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9303        mEphemeralInstallerInfo.priority = 0;
9304        mEphemeralInstallerInfo.preferredOrder = 1;
9305        mEphemeralInstallerInfo.isDefault = true;
9306        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9307                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9308
9309        if (DEBUG_EPHEMERAL) {
9310            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9311        }
9312    }
9313
9314    private static String calculateBundledApkRoot(final String codePathString) {
9315        final File codePath = new File(codePathString);
9316        final File codeRoot;
9317        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9318            codeRoot = Environment.getRootDirectory();
9319        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9320            codeRoot = Environment.getOemDirectory();
9321        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9322            codeRoot = Environment.getVendorDirectory();
9323        } else {
9324            // Unrecognized code path; take its top real segment as the apk root:
9325            // e.g. /something/app/blah.apk => /something
9326            try {
9327                File f = codePath.getCanonicalFile();
9328                File parent = f.getParentFile();    // non-null because codePath is a file
9329                File tmp;
9330                while ((tmp = parent.getParentFile()) != null) {
9331                    f = parent;
9332                    parent = tmp;
9333                }
9334                codeRoot = f;
9335                Slog.w(TAG, "Unrecognized code path "
9336                        + codePath + " - using " + codeRoot);
9337            } catch (IOException e) {
9338                // Can't canonicalize the code path -- shenanigans?
9339                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9340                return Environment.getRootDirectory().getPath();
9341            }
9342        }
9343        return codeRoot.getPath();
9344    }
9345
9346    /**
9347     * Derive and set the location of native libraries for the given package,
9348     * which varies depending on where and how the package was installed.
9349     */
9350    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9351        final ApplicationInfo info = pkg.applicationInfo;
9352        final String codePath = pkg.codePath;
9353        final File codeFile = new File(codePath);
9354        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9355        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9356
9357        info.nativeLibraryRootDir = null;
9358        info.nativeLibraryRootRequiresIsa = false;
9359        info.nativeLibraryDir = null;
9360        info.secondaryNativeLibraryDir = null;
9361
9362        if (isApkFile(codeFile)) {
9363            // Monolithic install
9364            if (bundledApp) {
9365                // If "/system/lib64/apkname" exists, assume that is the per-package
9366                // native library directory to use; otherwise use "/system/lib/apkname".
9367                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9368                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9369                        getPrimaryInstructionSet(info));
9370
9371                // This is a bundled system app so choose the path based on the ABI.
9372                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9373                // is just the default path.
9374                final String apkName = deriveCodePathName(codePath);
9375                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9376                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9377                        apkName).getAbsolutePath();
9378
9379                if (info.secondaryCpuAbi != null) {
9380                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9381                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9382                            secondaryLibDir, apkName).getAbsolutePath();
9383                }
9384            } else if (asecApp) {
9385                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9386                        .getAbsolutePath();
9387            } else {
9388                final String apkName = deriveCodePathName(codePath);
9389                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9390                        .getAbsolutePath();
9391            }
9392
9393            info.nativeLibraryRootRequiresIsa = false;
9394            info.nativeLibraryDir = info.nativeLibraryRootDir;
9395        } else {
9396            // Cluster install
9397            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9398            info.nativeLibraryRootRequiresIsa = true;
9399
9400            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9401                    getPrimaryInstructionSet(info)).getAbsolutePath();
9402
9403            if (info.secondaryCpuAbi != null) {
9404                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9405                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9406            }
9407        }
9408    }
9409
9410    /**
9411     * Calculate the abis and roots for a bundled app. These can uniquely
9412     * be determined from the contents of the system partition, i.e whether
9413     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9414     * of this information, and instead assume that the system was built
9415     * sensibly.
9416     */
9417    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9418                                           PackageSetting pkgSetting) {
9419        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9420
9421        // If "/system/lib64/apkname" exists, assume that is the per-package
9422        // native library directory to use; otherwise use "/system/lib/apkname".
9423        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9424        setBundledAppAbi(pkg, apkRoot, apkName);
9425        // pkgSetting might be null during rescan following uninstall of updates
9426        // to a bundled app, so accommodate that possibility.  The settings in
9427        // that case will be established later from the parsed package.
9428        //
9429        // If the settings aren't null, sync them up with what we've just derived.
9430        // note that apkRoot isn't stored in the package settings.
9431        if (pkgSetting != null) {
9432            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9433            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9434        }
9435    }
9436
9437    /**
9438     * Deduces the ABI of a bundled app and sets the relevant fields on the
9439     * parsed pkg object.
9440     *
9441     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9442     *        under which system libraries are installed.
9443     * @param apkName the name of the installed package.
9444     */
9445    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9446        final File codeFile = new File(pkg.codePath);
9447
9448        final boolean has64BitLibs;
9449        final boolean has32BitLibs;
9450        if (isApkFile(codeFile)) {
9451            // Monolithic install
9452            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9453            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9454        } else {
9455            // Cluster install
9456            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9457            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9458                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9459                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9460                has64BitLibs = (new File(rootDir, isa)).exists();
9461            } else {
9462                has64BitLibs = false;
9463            }
9464            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9465                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9466                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9467                has32BitLibs = (new File(rootDir, isa)).exists();
9468            } else {
9469                has32BitLibs = false;
9470            }
9471        }
9472
9473        if (has64BitLibs && !has32BitLibs) {
9474            // The package has 64 bit libs, but not 32 bit libs. Its primary
9475            // ABI should be 64 bit. We can safely assume here that the bundled
9476            // native libraries correspond to the most preferred ABI in the list.
9477
9478            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9479            pkg.applicationInfo.secondaryCpuAbi = null;
9480        } else if (has32BitLibs && !has64BitLibs) {
9481            // The package has 32 bit libs but not 64 bit libs. Its primary
9482            // ABI should be 32 bit.
9483
9484            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9485            pkg.applicationInfo.secondaryCpuAbi = null;
9486        } else if (has32BitLibs && has64BitLibs) {
9487            // The application has both 64 and 32 bit bundled libraries. We check
9488            // here that the app declares multiArch support, and warn if it doesn't.
9489            //
9490            // We will be lenient here and record both ABIs. The primary will be the
9491            // ABI that's higher on the list, i.e, a device that's configured to prefer
9492            // 64 bit apps will see a 64 bit primary ABI,
9493
9494            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9495                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9496            }
9497
9498            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9499                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9500                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9501            } else {
9502                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9503                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9504            }
9505        } else {
9506            pkg.applicationInfo.primaryCpuAbi = null;
9507            pkg.applicationInfo.secondaryCpuAbi = null;
9508        }
9509    }
9510
9511    private void killApplication(String pkgName, int appId, String reason) {
9512        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9513    }
9514
9515    private void killApplication(String pkgName, int appId, int userId, String reason) {
9516        // Request the ActivityManager to kill the process(only for existing packages)
9517        // so that we do not end up in a confused state while the user is still using the older
9518        // version of the application while the new one gets installed.
9519        final long token = Binder.clearCallingIdentity();
9520        try {
9521            IActivityManager am = ActivityManagerNative.getDefault();
9522            if (am != null) {
9523                try {
9524                    am.killApplication(pkgName, appId, userId, reason);
9525                } catch (RemoteException e) {
9526                }
9527            }
9528        } finally {
9529            Binder.restoreCallingIdentity(token);
9530        }
9531    }
9532
9533    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9534        // Remove the parent package setting
9535        PackageSetting ps = (PackageSetting) pkg.mExtras;
9536        if (ps != null) {
9537            removePackageLI(ps, chatty);
9538        }
9539        // Remove the child package setting
9540        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9541        for (int i = 0; i < childCount; i++) {
9542            PackageParser.Package childPkg = pkg.childPackages.get(i);
9543            ps = (PackageSetting) childPkg.mExtras;
9544            if (ps != null) {
9545                removePackageLI(ps, chatty);
9546            }
9547        }
9548    }
9549
9550    void removePackageLI(PackageSetting ps, boolean chatty) {
9551        if (DEBUG_INSTALL) {
9552            if (chatty)
9553                Log.d(TAG, "Removing package " + ps.name);
9554        }
9555
9556        // writer
9557        synchronized (mPackages) {
9558            mPackages.remove(ps.name);
9559            final PackageParser.Package pkg = ps.pkg;
9560            if (pkg != null) {
9561                cleanPackageDataStructuresLILPw(pkg, chatty);
9562            }
9563        }
9564    }
9565
9566    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9567        if (DEBUG_INSTALL) {
9568            if (chatty)
9569                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9570        }
9571
9572        // writer
9573        synchronized (mPackages) {
9574            // Remove the parent package
9575            mPackages.remove(pkg.applicationInfo.packageName);
9576            cleanPackageDataStructuresLILPw(pkg, chatty);
9577
9578            // Remove the child packages
9579            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9580            for (int i = 0; i < childCount; i++) {
9581                PackageParser.Package childPkg = pkg.childPackages.get(i);
9582                mPackages.remove(childPkg.applicationInfo.packageName);
9583                cleanPackageDataStructuresLILPw(childPkg, chatty);
9584            }
9585        }
9586    }
9587
9588    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9589        int N = pkg.providers.size();
9590        StringBuilder r = null;
9591        int i;
9592        for (i=0; i<N; i++) {
9593            PackageParser.Provider p = pkg.providers.get(i);
9594            mProviders.removeProvider(p);
9595            if (p.info.authority == null) {
9596
9597                /* There was another ContentProvider with this authority when
9598                 * this app was installed so this authority is null,
9599                 * Ignore it as we don't have to unregister the provider.
9600                 */
9601                continue;
9602            }
9603            String names[] = p.info.authority.split(";");
9604            for (int j = 0; j < names.length; j++) {
9605                if (mProvidersByAuthority.get(names[j]) == p) {
9606                    mProvidersByAuthority.remove(names[j]);
9607                    if (DEBUG_REMOVE) {
9608                        if (chatty)
9609                            Log.d(TAG, "Unregistered content provider: " + names[j]
9610                                    + ", className = " + p.info.name + ", isSyncable = "
9611                                    + p.info.isSyncable);
9612                    }
9613                }
9614            }
9615            if (DEBUG_REMOVE && chatty) {
9616                if (r == null) {
9617                    r = new StringBuilder(256);
9618                } else {
9619                    r.append(' ');
9620                }
9621                r.append(p.info.name);
9622            }
9623        }
9624        if (r != null) {
9625            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9626        }
9627
9628        N = pkg.services.size();
9629        r = null;
9630        for (i=0; i<N; i++) {
9631            PackageParser.Service s = pkg.services.get(i);
9632            mServices.removeService(s);
9633            if (chatty) {
9634                if (r == null) {
9635                    r = new StringBuilder(256);
9636                } else {
9637                    r.append(' ');
9638                }
9639                r.append(s.info.name);
9640            }
9641        }
9642        if (r != null) {
9643            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9644        }
9645
9646        N = pkg.receivers.size();
9647        r = null;
9648        for (i=0; i<N; i++) {
9649            PackageParser.Activity a = pkg.receivers.get(i);
9650            mReceivers.removeActivity(a, "receiver");
9651            if (DEBUG_REMOVE && chatty) {
9652                if (r == null) {
9653                    r = new StringBuilder(256);
9654                } else {
9655                    r.append(' ');
9656                }
9657                r.append(a.info.name);
9658            }
9659        }
9660        if (r != null) {
9661            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9662        }
9663
9664        N = pkg.activities.size();
9665        r = null;
9666        for (i=0; i<N; i++) {
9667            PackageParser.Activity a = pkg.activities.get(i);
9668            mActivities.removeActivity(a, "activity");
9669            if (DEBUG_REMOVE && chatty) {
9670                if (r == null) {
9671                    r = new StringBuilder(256);
9672                } else {
9673                    r.append(' ');
9674                }
9675                r.append(a.info.name);
9676            }
9677        }
9678        if (r != null) {
9679            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9680        }
9681
9682        N = pkg.permissions.size();
9683        r = null;
9684        for (i=0; i<N; i++) {
9685            PackageParser.Permission p = pkg.permissions.get(i);
9686            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9687            if (bp == null) {
9688                bp = mSettings.mPermissionTrees.get(p.info.name);
9689            }
9690            if (bp != null && bp.perm == p) {
9691                bp.perm = null;
9692                if (DEBUG_REMOVE && chatty) {
9693                    if (r == null) {
9694                        r = new StringBuilder(256);
9695                    } else {
9696                        r.append(' ');
9697                    }
9698                    r.append(p.info.name);
9699                }
9700            }
9701            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9702                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9703                if (appOpPkgs != null) {
9704                    appOpPkgs.remove(pkg.packageName);
9705                }
9706            }
9707        }
9708        if (r != null) {
9709            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9710        }
9711
9712        N = pkg.requestedPermissions.size();
9713        r = null;
9714        for (i=0; i<N; i++) {
9715            String perm = pkg.requestedPermissions.get(i);
9716            BasePermission bp = mSettings.mPermissions.get(perm);
9717            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9718                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9719                if (appOpPkgs != null) {
9720                    appOpPkgs.remove(pkg.packageName);
9721                    if (appOpPkgs.isEmpty()) {
9722                        mAppOpPermissionPackages.remove(perm);
9723                    }
9724                }
9725            }
9726        }
9727        if (r != null) {
9728            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9729        }
9730
9731        N = pkg.instrumentation.size();
9732        r = null;
9733        for (i=0; i<N; i++) {
9734            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9735            mInstrumentation.remove(a.getComponentName());
9736            if (DEBUG_REMOVE && chatty) {
9737                if (r == null) {
9738                    r = new StringBuilder(256);
9739                } else {
9740                    r.append(' ');
9741                }
9742                r.append(a.info.name);
9743            }
9744        }
9745        if (r != null) {
9746            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9747        }
9748
9749        r = null;
9750        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9751            // Only system apps can hold shared libraries.
9752            if (pkg.libraryNames != null) {
9753                for (i=0; i<pkg.libraryNames.size(); i++) {
9754                    String name = pkg.libraryNames.get(i);
9755                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9756                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9757                        mSharedLibraries.remove(name);
9758                        if (DEBUG_REMOVE && chatty) {
9759                            if (r == null) {
9760                                r = new StringBuilder(256);
9761                            } else {
9762                                r.append(' ');
9763                            }
9764                            r.append(name);
9765                        }
9766                    }
9767                }
9768            }
9769        }
9770        if (r != null) {
9771            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9772        }
9773    }
9774
9775    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9776        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9777            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9778                return true;
9779            }
9780        }
9781        return false;
9782    }
9783
9784    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9785    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9786    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9787
9788    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9789        // Update the parent permissions
9790        updatePermissionsLPw(pkg.packageName, pkg, flags);
9791        // Update the child permissions
9792        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9793        for (int i = 0; i < childCount; i++) {
9794            PackageParser.Package childPkg = pkg.childPackages.get(i);
9795            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9796        }
9797    }
9798
9799    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9800            int flags) {
9801        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9802        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9803    }
9804
9805    private void updatePermissionsLPw(String changingPkg,
9806            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9807        // Make sure there are no dangling permission trees.
9808        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9809        while (it.hasNext()) {
9810            final BasePermission bp = it.next();
9811            if (bp.packageSetting == null) {
9812                // We may not yet have parsed the package, so just see if
9813                // we still know about its settings.
9814                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9815            }
9816            if (bp.packageSetting == null) {
9817                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9818                        + " from package " + bp.sourcePackage);
9819                it.remove();
9820            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9821                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9822                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9823                            + " from package " + bp.sourcePackage);
9824                    flags |= UPDATE_PERMISSIONS_ALL;
9825                    it.remove();
9826                }
9827            }
9828        }
9829
9830        // Make sure all dynamic permissions have been assigned to a package,
9831        // and make sure there are no dangling permissions.
9832        it = mSettings.mPermissions.values().iterator();
9833        while (it.hasNext()) {
9834            final BasePermission bp = it.next();
9835            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9836                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9837                        + bp.name + " pkg=" + bp.sourcePackage
9838                        + " info=" + bp.pendingInfo);
9839                if (bp.packageSetting == null && bp.pendingInfo != null) {
9840                    final BasePermission tree = findPermissionTreeLP(bp.name);
9841                    if (tree != null && tree.perm != null) {
9842                        bp.packageSetting = tree.packageSetting;
9843                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9844                                new PermissionInfo(bp.pendingInfo));
9845                        bp.perm.info.packageName = tree.perm.info.packageName;
9846                        bp.perm.info.name = bp.name;
9847                        bp.uid = tree.uid;
9848                    }
9849                }
9850            }
9851            if (bp.packageSetting == null) {
9852                // We may not yet have parsed the package, so just see if
9853                // we still know about its settings.
9854                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9855            }
9856            if (bp.packageSetting == null) {
9857                Slog.w(TAG, "Removing dangling permission: " + bp.name
9858                        + " from package " + bp.sourcePackage);
9859                it.remove();
9860            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9861                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9862                    Slog.i(TAG, "Removing old permission: " + bp.name
9863                            + " from package " + bp.sourcePackage);
9864                    flags |= UPDATE_PERMISSIONS_ALL;
9865                    it.remove();
9866                }
9867            }
9868        }
9869
9870        // Now update the permissions for all packages, in particular
9871        // replace the granted permissions of the system packages.
9872        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9873            for (PackageParser.Package pkg : mPackages.values()) {
9874                if (pkg != pkgInfo) {
9875                    // Only replace for packages on requested volume
9876                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9877                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9878                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9879                    grantPermissionsLPw(pkg, replace, changingPkg);
9880                }
9881            }
9882        }
9883
9884        if (pkgInfo != null) {
9885            // Only replace for packages on requested volume
9886            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9887            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9888                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9889            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9890        }
9891    }
9892
9893    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9894            String packageOfInterest) {
9895        // IMPORTANT: There are two types of permissions: install and runtime.
9896        // Install time permissions are granted when the app is installed to
9897        // all device users and users added in the future. Runtime permissions
9898        // are granted at runtime explicitly to specific users. Normal and signature
9899        // protected permissions are install time permissions. Dangerous permissions
9900        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9901        // otherwise they are runtime permissions. This function does not manage
9902        // runtime permissions except for the case an app targeting Lollipop MR1
9903        // being upgraded to target a newer SDK, in which case dangerous permissions
9904        // are transformed from install time to runtime ones.
9905
9906        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9907        if (ps == null) {
9908            return;
9909        }
9910
9911        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9912
9913        PermissionsState permissionsState = ps.getPermissionsState();
9914        PermissionsState origPermissions = permissionsState;
9915
9916        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9917
9918        boolean runtimePermissionsRevoked = false;
9919        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9920
9921        boolean changedInstallPermission = false;
9922
9923        if (replace) {
9924            ps.installPermissionsFixed = false;
9925            if (!ps.isSharedUser()) {
9926                origPermissions = new PermissionsState(permissionsState);
9927                permissionsState.reset();
9928            } else {
9929                // We need to know only about runtime permission changes since the
9930                // calling code always writes the install permissions state but
9931                // the runtime ones are written only if changed. The only cases of
9932                // changed runtime permissions here are promotion of an install to
9933                // runtime and revocation of a runtime from a shared user.
9934                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9935                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9936                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9937                    runtimePermissionsRevoked = true;
9938                }
9939            }
9940        }
9941
9942        permissionsState.setGlobalGids(mGlobalGids);
9943
9944        final int N = pkg.requestedPermissions.size();
9945        for (int i=0; i<N; i++) {
9946            final String name = pkg.requestedPermissions.get(i);
9947            final BasePermission bp = mSettings.mPermissions.get(name);
9948
9949            if (DEBUG_INSTALL) {
9950                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9951            }
9952
9953            if (bp == null || bp.packageSetting == null) {
9954                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9955                    Slog.w(TAG, "Unknown permission " + name
9956                            + " in package " + pkg.packageName);
9957                }
9958                continue;
9959            }
9960
9961            final String perm = bp.name;
9962            boolean allowedSig = false;
9963            int grant = GRANT_DENIED;
9964
9965            // Keep track of app op permissions.
9966            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9967                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9968                if (pkgs == null) {
9969                    pkgs = new ArraySet<>();
9970                    mAppOpPermissionPackages.put(bp.name, pkgs);
9971                }
9972                pkgs.add(pkg.packageName);
9973            }
9974
9975            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9976            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9977                    >= Build.VERSION_CODES.M;
9978            switch (level) {
9979                case PermissionInfo.PROTECTION_NORMAL: {
9980                    // For all apps normal permissions are install time ones.
9981                    grant = GRANT_INSTALL;
9982                } break;
9983
9984                case PermissionInfo.PROTECTION_DANGEROUS: {
9985                    // If a permission review is required for legacy apps we represent
9986                    // their permissions as always granted runtime ones since we need
9987                    // to keep the review required permission flag per user while an
9988                    // install permission's state is shared across all users.
9989                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9990                        // For legacy apps dangerous permissions are install time ones.
9991                        grant = GRANT_INSTALL;
9992                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9993                        // For legacy apps that became modern, install becomes runtime.
9994                        grant = GRANT_UPGRADE;
9995                    } else if (mPromoteSystemApps
9996                            && isSystemApp(ps)
9997                            && mExistingSystemPackages.contains(ps.name)) {
9998                        // For legacy system apps, install becomes runtime.
9999                        // We cannot check hasInstallPermission() for system apps since those
10000                        // permissions were granted implicitly and not persisted pre-M.
10001                        grant = GRANT_UPGRADE;
10002                    } else {
10003                        // For modern apps keep runtime permissions unchanged.
10004                        grant = GRANT_RUNTIME;
10005                    }
10006                } break;
10007
10008                case PermissionInfo.PROTECTION_SIGNATURE: {
10009                    // For all apps signature permissions are install time ones.
10010                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10011                    if (allowedSig) {
10012                        grant = GRANT_INSTALL;
10013                    }
10014                } break;
10015            }
10016
10017            if (DEBUG_INSTALL) {
10018                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10019            }
10020
10021            if (grant != GRANT_DENIED) {
10022                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10023                    // If this is an existing, non-system package, then
10024                    // we can't add any new permissions to it.
10025                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10026                        // Except...  if this is a permission that was added
10027                        // to the platform (note: need to only do this when
10028                        // updating the platform).
10029                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10030                            grant = GRANT_DENIED;
10031                        }
10032                    }
10033                }
10034
10035                switch (grant) {
10036                    case GRANT_INSTALL: {
10037                        // Revoke this as runtime permission to handle the case of
10038                        // a runtime permission being downgraded to an install one.
10039                        // Also in permission review mode we keep dangerous permissions
10040                        // for legacy apps
10041                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10042                            if (origPermissions.getRuntimePermissionState(
10043                                    bp.name, userId) != null) {
10044                                // Revoke the runtime permission and clear the flags.
10045                                origPermissions.revokeRuntimePermission(bp, userId);
10046                                origPermissions.updatePermissionFlags(bp, userId,
10047                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10048                                // If we revoked a permission permission, we have to write.
10049                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10050                                        changedRuntimePermissionUserIds, userId);
10051                            }
10052                        }
10053                        // Grant an install permission.
10054                        if (permissionsState.grantInstallPermission(bp) !=
10055                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10056                            changedInstallPermission = true;
10057                        }
10058                    } break;
10059
10060                    case GRANT_RUNTIME: {
10061                        // Grant previously granted runtime permissions.
10062                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10063                            PermissionState permissionState = origPermissions
10064                                    .getRuntimePermissionState(bp.name, userId);
10065                            int flags = permissionState != null
10066                                    ? permissionState.getFlags() : 0;
10067                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10068                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10069                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10070                                    // If we cannot put the permission as it was, we have to write.
10071                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10072                                            changedRuntimePermissionUserIds, userId);
10073                                }
10074                                // If the app supports runtime permissions no need for a review.
10075                                if (Build.PERMISSIONS_REVIEW_REQUIRED
10076                                        && appSupportsRuntimePermissions
10077                                        && (flags & PackageManager
10078                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10079                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10080                                    // Since we changed the flags, we have to write.
10081                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10082                                            changedRuntimePermissionUserIds, userId);
10083                                }
10084                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
10085                                    && !appSupportsRuntimePermissions) {
10086                                // For legacy apps that need a permission review, every new
10087                                // runtime permission is granted but it is pending a review.
10088                                // We also need to review only platform defined runtime
10089                                // permissions as these are the only ones the platform knows
10090                                // how to disable the API to simulate revocation as legacy
10091                                // apps don't expect to run with revoked permissions.
10092                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10093                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10094                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10095                                        // We changed the flags, hence have to write.
10096                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10097                                                changedRuntimePermissionUserIds, userId);
10098                                    }
10099                                }
10100                                if (permissionsState.grantRuntimePermission(bp, userId)
10101                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10102                                    // We changed the permission, hence have to write.
10103                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10104                                            changedRuntimePermissionUserIds, userId);
10105                                }
10106                            }
10107                            // Propagate the permission flags.
10108                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10109                        }
10110                    } break;
10111
10112                    case GRANT_UPGRADE: {
10113                        // Grant runtime permissions for a previously held install permission.
10114                        PermissionState permissionState = origPermissions
10115                                .getInstallPermissionState(bp.name);
10116                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10117
10118                        if (origPermissions.revokeInstallPermission(bp)
10119                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10120                            // We will be transferring the permission flags, so clear them.
10121                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10122                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10123                            changedInstallPermission = true;
10124                        }
10125
10126                        // If the permission is not to be promoted to runtime we ignore it and
10127                        // also its other flags as they are not applicable to install permissions.
10128                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10129                            for (int userId : currentUserIds) {
10130                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10131                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10132                                    // Transfer the permission flags.
10133                                    permissionsState.updatePermissionFlags(bp, userId,
10134                                            flags, flags);
10135                                    // If we granted the permission, we have to write.
10136                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10137                                            changedRuntimePermissionUserIds, userId);
10138                                }
10139                            }
10140                        }
10141                    } break;
10142
10143                    default: {
10144                        if (packageOfInterest == null
10145                                || packageOfInterest.equals(pkg.packageName)) {
10146                            Slog.w(TAG, "Not granting permission " + perm
10147                                    + " to package " + pkg.packageName
10148                                    + " because it was previously installed without");
10149                        }
10150                    } break;
10151                }
10152            } else {
10153                if (permissionsState.revokeInstallPermission(bp) !=
10154                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10155                    // Also drop the permission flags.
10156                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10157                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10158                    changedInstallPermission = true;
10159                    Slog.i(TAG, "Un-granting permission " + perm
10160                            + " from package " + pkg.packageName
10161                            + " (protectionLevel=" + bp.protectionLevel
10162                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10163                            + ")");
10164                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10165                    // Don't print warning for app op permissions, since it is fine for them
10166                    // not to be granted, there is a UI for the user to decide.
10167                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10168                        Slog.w(TAG, "Not granting permission " + perm
10169                                + " to package " + pkg.packageName
10170                                + " (protectionLevel=" + bp.protectionLevel
10171                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10172                                + ")");
10173                    }
10174                }
10175            }
10176        }
10177
10178        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10179                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10180            // This is the first that we have heard about this package, so the
10181            // permissions we have now selected are fixed until explicitly
10182            // changed.
10183            ps.installPermissionsFixed = true;
10184        }
10185
10186        // Persist the runtime permissions state for users with changes. If permissions
10187        // were revoked because no app in the shared user declares them we have to
10188        // write synchronously to avoid losing runtime permissions state.
10189        for (int userId : changedRuntimePermissionUserIds) {
10190            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10191        }
10192
10193        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10194    }
10195
10196    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10197        boolean allowed = false;
10198        final int NP = PackageParser.NEW_PERMISSIONS.length;
10199        for (int ip=0; ip<NP; ip++) {
10200            final PackageParser.NewPermissionInfo npi
10201                    = PackageParser.NEW_PERMISSIONS[ip];
10202            if (npi.name.equals(perm)
10203                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10204                allowed = true;
10205                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10206                        + pkg.packageName);
10207                break;
10208            }
10209        }
10210        return allowed;
10211    }
10212
10213    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10214            BasePermission bp, PermissionsState origPermissions) {
10215        boolean allowed;
10216        allowed = (compareSignatures(
10217                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10218                        == PackageManager.SIGNATURE_MATCH)
10219                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10220                        == PackageManager.SIGNATURE_MATCH);
10221        if (!allowed && (bp.protectionLevel
10222                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10223            if (isSystemApp(pkg)) {
10224                // For updated system applications, a system permission
10225                // is granted only if it had been defined by the original application.
10226                if (pkg.isUpdatedSystemApp()) {
10227                    final PackageSetting sysPs = mSettings
10228                            .getDisabledSystemPkgLPr(pkg.packageName);
10229                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10230                        // If the original was granted this permission, we take
10231                        // that grant decision as read and propagate it to the
10232                        // update.
10233                        if (sysPs.isPrivileged()) {
10234                            allowed = true;
10235                        }
10236                    } else {
10237                        // The system apk may have been updated with an older
10238                        // version of the one on the data partition, but which
10239                        // granted a new system permission that it didn't have
10240                        // before.  In this case we do want to allow the app to
10241                        // now get the new permission if the ancestral apk is
10242                        // privileged to get it.
10243                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10244                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10245                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10246                                    allowed = true;
10247                                    break;
10248                                }
10249                            }
10250                        }
10251                        // Also if a privileged parent package on the system image or any of
10252                        // its children requested a privileged permission, the updated child
10253                        // packages can also get the permission.
10254                        if (pkg.parentPackage != null) {
10255                            final PackageSetting disabledSysParentPs = mSettings
10256                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10257                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10258                                    && disabledSysParentPs.isPrivileged()) {
10259                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10260                                    allowed = true;
10261                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10262                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10263                                    for (int i = 0; i < count; i++) {
10264                                        PackageParser.Package disabledSysChildPkg =
10265                                                disabledSysParentPs.pkg.childPackages.get(i);
10266                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10267                                                perm)) {
10268                                            allowed = true;
10269                                            break;
10270                                        }
10271                                    }
10272                                }
10273                            }
10274                        }
10275                    }
10276                } else {
10277                    allowed = isPrivilegedApp(pkg);
10278                }
10279            }
10280        }
10281        if (!allowed) {
10282            if (!allowed && (bp.protectionLevel
10283                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10284                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10285                // If this was a previously normal/dangerous permission that got moved
10286                // to a system permission as part of the runtime permission redesign, then
10287                // we still want to blindly grant it to old apps.
10288                allowed = true;
10289            }
10290            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10291                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10292                // If this permission is to be granted to the system installer and
10293                // this app is an installer, then it gets the permission.
10294                allowed = true;
10295            }
10296            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10297                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10298                // If this permission is to be granted to the system verifier and
10299                // this app is a verifier, then it gets the permission.
10300                allowed = true;
10301            }
10302            if (!allowed && (bp.protectionLevel
10303                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10304                    && isSystemApp(pkg)) {
10305                // Any pre-installed system app is allowed to get this permission.
10306                allowed = true;
10307            }
10308            if (!allowed && (bp.protectionLevel
10309                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10310                // For development permissions, a development permission
10311                // is granted only if it was already granted.
10312                allowed = origPermissions.hasInstallPermission(perm);
10313            }
10314            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10315                    && pkg.packageName.equals(mSetupWizardPackage)) {
10316                // If this permission is to be granted to the system setup wizard and
10317                // this app is a setup wizard, then it gets the permission.
10318                allowed = true;
10319            }
10320        }
10321        return allowed;
10322    }
10323
10324    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10325        final int permCount = pkg.requestedPermissions.size();
10326        for (int j = 0; j < permCount; j++) {
10327            String requestedPermission = pkg.requestedPermissions.get(j);
10328            if (permission.equals(requestedPermission)) {
10329                return true;
10330            }
10331        }
10332        return false;
10333    }
10334
10335    final class ActivityIntentResolver
10336            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10337        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10338                boolean defaultOnly, int userId) {
10339            if (!sUserManager.exists(userId)) return null;
10340            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10341            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10342        }
10343
10344        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10345                int userId) {
10346            if (!sUserManager.exists(userId)) return null;
10347            mFlags = flags;
10348            return super.queryIntent(intent, resolvedType,
10349                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10350        }
10351
10352        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10353                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10354            if (!sUserManager.exists(userId)) return null;
10355            if (packageActivities == null) {
10356                return null;
10357            }
10358            mFlags = flags;
10359            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10360            final int N = packageActivities.size();
10361            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10362                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10363
10364            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10365            for (int i = 0; i < N; ++i) {
10366                intentFilters = packageActivities.get(i).intents;
10367                if (intentFilters != null && intentFilters.size() > 0) {
10368                    PackageParser.ActivityIntentInfo[] array =
10369                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10370                    intentFilters.toArray(array);
10371                    listCut.add(array);
10372                }
10373            }
10374            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10375        }
10376
10377        /**
10378         * Finds a privileged activity that matches the specified activity names.
10379         */
10380        private PackageParser.Activity findMatchingActivity(
10381                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10382            for (PackageParser.Activity sysActivity : activityList) {
10383                if (sysActivity.info.name.equals(activityInfo.name)) {
10384                    return sysActivity;
10385                }
10386                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10387                    return sysActivity;
10388                }
10389                if (sysActivity.info.targetActivity != null) {
10390                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10391                        return sysActivity;
10392                    }
10393                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10394                        return sysActivity;
10395                    }
10396                }
10397            }
10398            return null;
10399        }
10400
10401        public class IterGenerator<E> {
10402            public Iterator<E> generate(ActivityIntentInfo info) {
10403                return null;
10404            }
10405        }
10406
10407        public class ActionIterGenerator extends IterGenerator<String> {
10408            @Override
10409            public Iterator<String> generate(ActivityIntentInfo info) {
10410                return info.actionsIterator();
10411            }
10412        }
10413
10414        public class CategoriesIterGenerator extends IterGenerator<String> {
10415            @Override
10416            public Iterator<String> generate(ActivityIntentInfo info) {
10417                return info.categoriesIterator();
10418            }
10419        }
10420
10421        public class SchemesIterGenerator extends IterGenerator<String> {
10422            @Override
10423            public Iterator<String> generate(ActivityIntentInfo info) {
10424                return info.schemesIterator();
10425            }
10426        }
10427
10428        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10429            @Override
10430            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10431                return info.authoritiesIterator();
10432            }
10433        }
10434
10435        /**
10436         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10437         * MODIFIED. Do not pass in a list that should not be changed.
10438         */
10439        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10440                IterGenerator<T> generator, Iterator<T> searchIterator) {
10441            // loop through the set of actions; every one must be found in the intent filter
10442            while (searchIterator.hasNext()) {
10443                // we must have at least one filter in the list to consider a match
10444                if (intentList.size() == 0) {
10445                    break;
10446                }
10447
10448                final T searchAction = searchIterator.next();
10449
10450                // loop through the set of intent filters
10451                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10452                while (intentIter.hasNext()) {
10453                    final ActivityIntentInfo intentInfo = intentIter.next();
10454                    boolean selectionFound = false;
10455
10456                    // loop through the intent filter's selection criteria; at least one
10457                    // of them must match the searched criteria
10458                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10459                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10460                        final T intentSelection = intentSelectionIter.next();
10461                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10462                            selectionFound = true;
10463                            break;
10464                        }
10465                    }
10466
10467                    // the selection criteria wasn't found in this filter's set; this filter
10468                    // is not a potential match
10469                    if (!selectionFound) {
10470                        intentIter.remove();
10471                    }
10472                }
10473            }
10474        }
10475
10476        private boolean isProtectedAction(ActivityIntentInfo filter) {
10477            final Iterator<String> actionsIter = filter.actionsIterator();
10478            while (actionsIter != null && actionsIter.hasNext()) {
10479                final String filterAction = actionsIter.next();
10480                if (PROTECTED_ACTIONS.contains(filterAction)) {
10481                    return true;
10482                }
10483            }
10484            return false;
10485        }
10486
10487        /**
10488         * Adjusts the priority of the given intent filter according to policy.
10489         * <p>
10490         * <ul>
10491         * <li>The priority for non privileged applications is capped to '0'</li>
10492         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10493         * <li>The priority for unbundled updates to privileged applications is capped to the
10494         *      priority defined on the system partition</li>
10495         * </ul>
10496         * <p>
10497         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10498         * allowed to obtain any priority on any action.
10499         */
10500        private void adjustPriority(
10501                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10502            // nothing to do; priority is fine as-is
10503            if (intent.getPriority() <= 0) {
10504                return;
10505            }
10506
10507            final ActivityInfo activityInfo = intent.activity.info;
10508            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10509
10510            final boolean privilegedApp =
10511                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10512            if (!privilegedApp) {
10513                // non-privileged applications can never define a priority >0
10514                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10515                        + " package: " + applicationInfo.packageName
10516                        + " activity: " + intent.activity.className
10517                        + " origPrio: " + intent.getPriority());
10518                intent.setPriority(0);
10519                return;
10520            }
10521
10522            if (systemActivities == null) {
10523                // the system package is not disabled; we're parsing the system partition
10524                if (isProtectedAction(intent)) {
10525                    if (mDeferProtectedFilters) {
10526                        // We can't deal with these just yet. No component should ever obtain a
10527                        // >0 priority for a protected actions, with ONE exception -- the setup
10528                        // wizard. The setup wizard, however, cannot be known until we're able to
10529                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10530                        // until all intent filters have been processed. Chicken, meet egg.
10531                        // Let the filter temporarily have a high priority and rectify the
10532                        // priorities after all system packages have been scanned.
10533                        mProtectedFilters.add(intent);
10534                        if (DEBUG_FILTERS) {
10535                            Slog.i(TAG, "Protected action; save for later;"
10536                                    + " package: " + applicationInfo.packageName
10537                                    + " activity: " + intent.activity.className
10538                                    + " origPrio: " + intent.getPriority());
10539                        }
10540                        return;
10541                    } else {
10542                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10543                            Slog.i(TAG, "No setup wizard;"
10544                                + " All protected intents capped to priority 0");
10545                        }
10546                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10547                            if (DEBUG_FILTERS) {
10548                                Slog.i(TAG, "Found setup wizard;"
10549                                    + " allow priority " + intent.getPriority() + ";"
10550                                    + " package: " + intent.activity.info.packageName
10551                                    + " activity: " + intent.activity.className
10552                                    + " priority: " + intent.getPriority());
10553                            }
10554                            // setup wizard gets whatever it wants
10555                            return;
10556                        }
10557                        Slog.w(TAG, "Protected action; cap priority to 0;"
10558                                + " package: " + intent.activity.info.packageName
10559                                + " activity: " + intent.activity.className
10560                                + " origPrio: " + intent.getPriority());
10561                        intent.setPriority(0);
10562                        return;
10563                    }
10564                }
10565                // privileged apps on the system image get whatever priority they request
10566                return;
10567            }
10568
10569            // privileged app unbundled update ... try to find the same activity
10570            final PackageParser.Activity foundActivity =
10571                    findMatchingActivity(systemActivities, activityInfo);
10572            if (foundActivity == null) {
10573                // this is a new activity; it cannot obtain >0 priority
10574                if (DEBUG_FILTERS) {
10575                    Slog.i(TAG, "New activity; cap priority to 0;"
10576                            + " package: " + applicationInfo.packageName
10577                            + " activity: " + intent.activity.className
10578                            + " origPrio: " + intent.getPriority());
10579                }
10580                intent.setPriority(0);
10581                return;
10582            }
10583
10584            // found activity, now check for filter equivalence
10585
10586            // a shallow copy is enough; we modify the list, not its contents
10587            final List<ActivityIntentInfo> intentListCopy =
10588                    new ArrayList<>(foundActivity.intents);
10589            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10590
10591            // find matching action subsets
10592            final Iterator<String> actionsIterator = intent.actionsIterator();
10593            if (actionsIterator != null) {
10594                getIntentListSubset(
10595                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10596                if (intentListCopy.size() == 0) {
10597                    // no more intents to match; we're not equivalent
10598                    if (DEBUG_FILTERS) {
10599                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10600                                + " package: " + applicationInfo.packageName
10601                                + " activity: " + intent.activity.className
10602                                + " origPrio: " + intent.getPriority());
10603                    }
10604                    intent.setPriority(0);
10605                    return;
10606                }
10607            }
10608
10609            // find matching category subsets
10610            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10611            if (categoriesIterator != null) {
10612                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10613                        categoriesIterator);
10614                if (intentListCopy.size() == 0) {
10615                    // no more intents to match; we're not equivalent
10616                    if (DEBUG_FILTERS) {
10617                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10618                                + " package: " + applicationInfo.packageName
10619                                + " activity: " + intent.activity.className
10620                                + " origPrio: " + intent.getPriority());
10621                    }
10622                    intent.setPriority(0);
10623                    return;
10624                }
10625            }
10626
10627            // find matching schemes subsets
10628            final Iterator<String> schemesIterator = intent.schemesIterator();
10629            if (schemesIterator != null) {
10630                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10631                        schemesIterator);
10632                if (intentListCopy.size() == 0) {
10633                    // no more intents to match; we're not equivalent
10634                    if (DEBUG_FILTERS) {
10635                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10636                                + " package: " + applicationInfo.packageName
10637                                + " activity: " + intent.activity.className
10638                                + " origPrio: " + intent.getPriority());
10639                    }
10640                    intent.setPriority(0);
10641                    return;
10642                }
10643            }
10644
10645            // find matching authorities subsets
10646            final Iterator<IntentFilter.AuthorityEntry>
10647                    authoritiesIterator = intent.authoritiesIterator();
10648            if (authoritiesIterator != null) {
10649                getIntentListSubset(intentListCopy,
10650                        new AuthoritiesIterGenerator(),
10651                        authoritiesIterator);
10652                if (intentListCopy.size() == 0) {
10653                    // no more intents to match; we're not equivalent
10654                    if (DEBUG_FILTERS) {
10655                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10656                                + " package: " + applicationInfo.packageName
10657                                + " activity: " + intent.activity.className
10658                                + " origPrio: " + intent.getPriority());
10659                    }
10660                    intent.setPriority(0);
10661                    return;
10662                }
10663            }
10664
10665            // we found matching filter(s); app gets the max priority of all intents
10666            int cappedPriority = 0;
10667            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10668                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10669            }
10670            if (intent.getPriority() > cappedPriority) {
10671                if (DEBUG_FILTERS) {
10672                    Slog.i(TAG, "Found matching filter(s);"
10673                            + " cap priority to " + cappedPriority + ";"
10674                            + " package: " + applicationInfo.packageName
10675                            + " activity: " + intent.activity.className
10676                            + " origPrio: " + intent.getPriority());
10677                }
10678                intent.setPriority(cappedPriority);
10679                return;
10680            }
10681            // all this for nothing; the requested priority was <= what was on the system
10682        }
10683
10684        public final void addActivity(PackageParser.Activity a, String type) {
10685            mActivities.put(a.getComponentName(), a);
10686            if (DEBUG_SHOW_INFO)
10687                Log.v(
10688                TAG, "  " + type + " " +
10689                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10690            if (DEBUG_SHOW_INFO)
10691                Log.v(TAG, "    Class=" + a.info.name);
10692            final int NI = a.intents.size();
10693            for (int j=0; j<NI; j++) {
10694                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10695                if ("activity".equals(type)) {
10696                    final PackageSetting ps =
10697                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10698                    final List<PackageParser.Activity> systemActivities =
10699                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10700                    adjustPriority(systemActivities, intent);
10701                }
10702                if (DEBUG_SHOW_INFO) {
10703                    Log.v(TAG, "    IntentFilter:");
10704                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10705                }
10706                if (!intent.debugCheck()) {
10707                    Log.w(TAG, "==> For Activity " + a.info.name);
10708                }
10709                addFilter(intent);
10710            }
10711        }
10712
10713        public final void removeActivity(PackageParser.Activity a, String type) {
10714            mActivities.remove(a.getComponentName());
10715            if (DEBUG_SHOW_INFO) {
10716                Log.v(TAG, "  " + type + " "
10717                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10718                                : a.info.name) + ":");
10719                Log.v(TAG, "    Class=" + a.info.name);
10720            }
10721            final int NI = a.intents.size();
10722            for (int j=0; j<NI; j++) {
10723                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10724                if (DEBUG_SHOW_INFO) {
10725                    Log.v(TAG, "    IntentFilter:");
10726                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10727                }
10728                removeFilter(intent);
10729            }
10730        }
10731
10732        @Override
10733        protected boolean allowFilterResult(
10734                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10735            ActivityInfo filterAi = filter.activity.info;
10736            for (int i=dest.size()-1; i>=0; i--) {
10737                ActivityInfo destAi = dest.get(i).activityInfo;
10738                if (destAi.name == filterAi.name
10739                        && destAi.packageName == filterAi.packageName) {
10740                    return false;
10741                }
10742            }
10743            return true;
10744        }
10745
10746        @Override
10747        protected ActivityIntentInfo[] newArray(int size) {
10748            return new ActivityIntentInfo[size];
10749        }
10750
10751        @Override
10752        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10753            if (!sUserManager.exists(userId)) return true;
10754            PackageParser.Package p = filter.activity.owner;
10755            if (p != null) {
10756                PackageSetting ps = (PackageSetting)p.mExtras;
10757                if (ps != null) {
10758                    // System apps are never considered stopped for purposes of
10759                    // filtering, because there may be no way for the user to
10760                    // actually re-launch them.
10761                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10762                            && ps.getStopped(userId);
10763                }
10764            }
10765            return false;
10766        }
10767
10768        @Override
10769        protected boolean isPackageForFilter(String packageName,
10770                PackageParser.ActivityIntentInfo info) {
10771            return packageName.equals(info.activity.owner.packageName);
10772        }
10773
10774        @Override
10775        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10776                int match, int userId) {
10777            if (!sUserManager.exists(userId)) return null;
10778            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10779                return null;
10780            }
10781            final PackageParser.Activity activity = info.activity;
10782            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10783            if (ps == null) {
10784                return null;
10785            }
10786            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10787                    ps.readUserState(userId), userId);
10788            if (ai == null) {
10789                return null;
10790            }
10791            final ResolveInfo res = new ResolveInfo();
10792            res.activityInfo = ai;
10793            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10794                res.filter = info;
10795            }
10796            if (info != null) {
10797                res.handleAllWebDataURI = info.handleAllWebDataURI();
10798            }
10799            res.priority = info.getPriority();
10800            res.preferredOrder = activity.owner.mPreferredOrder;
10801            //System.out.println("Result: " + res.activityInfo.className +
10802            //                   " = " + res.priority);
10803            res.match = match;
10804            res.isDefault = info.hasDefault;
10805            res.labelRes = info.labelRes;
10806            res.nonLocalizedLabel = info.nonLocalizedLabel;
10807            if (userNeedsBadging(userId)) {
10808                res.noResourceId = true;
10809            } else {
10810                res.icon = info.icon;
10811            }
10812            res.iconResourceId = info.icon;
10813            res.system = res.activityInfo.applicationInfo.isSystemApp();
10814            return res;
10815        }
10816
10817        @Override
10818        protected void sortResults(List<ResolveInfo> results) {
10819            Collections.sort(results, mResolvePrioritySorter);
10820        }
10821
10822        @Override
10823        protected void dumpFilter(PrintWriter out, String prefix,
10824                PackageParser.ActivityIntentInfo filter) {
10825            out.print(prefix); out.print(
10826                    Integer.toHexString(System.identityHashCode(filter.activity)));
10827                    out.print(' ');
10828                    filter.activity.printComponentShortName(out);
10829                    out.print(" filter ");
10830                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10831        }
10832
10833        @Override
10834        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10835            return filter.activity;
10836        }
10837
10838        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10839            PackageParser.Activity activity = (PackageParser.Activity)label;
10840            out.print(prefix); out.print(
10841                    Integer.toHexString(System.identityHashCode(activity)));
10842                    out.print(' ');
10843                    activity.printComponentShortName(out);
10844            if (count > 1) {
10845                out.print(" ("); out.print(count); out.print(" filters)");
10846            }
10847            out.println();
10848        }
10849
10850        // Keys are String (activity class name), values are Activity.
10851        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10852                = new ArrayMap<ComponentName, PackageParser.Activity>();
10853        private int mFlags;
10854    }
10855
10856    private final class ServiceIntentResolver
10857            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10858        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10859                boolean defaultOnly, int userId) {
10860            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10861            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10862        }
10863
10864        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10865                int userId) {
10866            if (!sUserManager.exists(userId)) return null;
10867            mFlags = flags;
10868            return super.queryIntent(intent, resolvedType,
10869                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10870        }
10871
10872        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10873                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10874            if (!sUserManager.exists(userId)) return null;
10875            if (packageServices == null) {
10876                return null;
10877            }
10878            mFlags = flags;
10879            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10880            final int N = packageServices.size();
10881            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10882                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10883
10884            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10885            for (int i = 0; i < N; ++i) {
10886                intentFilters = packageServices.get(i).intents;
10887                if (intentFilters != null && intentFilters.size() > 0) {
10888                    PackageParser.ServiceIntentInfo[] array =
10889                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10890                    intentFilters.toArray(array);
10891                    listCut.add(array);
10892                }
10893            }
10894            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10895        }
10896
10897        public final void addService(PackageParser.Service s) {
10898            mServices.put(s.getComponentName(), s);
10899            if (DEBUG_SHOW_INFO) {
10900                Log.v(TAG, "  "
10901                        + (s.info.nonLocalizedLabel != null
10902                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10903                Log.v(TAG, "    Class=" + s.info.name);
10904            }
10905            final int NI = s.intents.size();
10906            int j;
10907            for (j=0; j<NI; j++) {
10908                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10909                if (DEBUG_SHOW_INFO) {
10910                    Log.v(TAG, "    IntentFilter:");
10911                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10912                }
10913                if (!intent.debugCheck()) {
10914                    Log.w(TAG, "==> For Service " + s.info.name);
10915                }
10916                addFilter(intent);
10917            }
10918        }
10919
10920        public final void removeService(PackageParser.Service s) {
10921            mServices.remove(s.getComponentName());
10922            if (DEBUG_SHOW_INFO) {
10923                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10924                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10925                Log.v(TAG, "    Class=" + s.info.name);
10926            }
10927            final int NI = s.intents.size();
10928            int j;
10929            for (j=0; j<NI; j++) {
10930                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10931                if (DEBUG_SHOW_INFO) {
10932                    Log.v(TAG, "    IntentFilter:");
10933                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10934                }
10935                removeFilter(intent);
10936            }
10937        }
10938
10939        @Override
10940        protected boolean allowFilterResult(
10941                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10942            ServiceInfo filterSi = filter.service.info;
10943            for (int i=dest.size()-1; i>=0; i--) {
10944                ServiceInfo destAi = dest.get(i).serviceInfo;
10945                if (destAi.name == filterSi.name
10946                        && destAi.packageName == filterSi.packageName) {
10947                    return false;
10948                }
10949            }
10950            return true;
10951        }
10952
10953        @Override
10954        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10955            return new PackageParser.ServiceIntentInfo[size];
10956        }
10957
10958        @Override
10959        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10960            if (!sUserManager.exists(userId)) return true;
10961            PackageParser.Package p = filter.service.owner;
10962            if (p != null) {
10963                PackageSetting ps = (PackageSetting)p.mExtras;
10964                if (ps != null) {
10965                    // System apps are never considered stopped for purposes of
10966                    // filtering, because there may be no way for the user to
10967                    // actually re-launch them.
10968                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10969                            && ps.getStopped(userId);
10970                }
10971            }
10972            return false;
10973        }
10974
10975        @Override
10976        protected boolean isPackageForFilter(String packageName,
10977                PackageParser.ServiceIntentInfo info) {
10978            return packageName.equals(info.service.owner.packageName);
10979        }
10980
10981        @Override
10982        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10983                int match, int userId) {
10984            if (!sUserManager.exists(userId)) return null;
10985            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10986            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10987                return null;
10988            }
10989            final PackageParser.Service service = info.service;
10990            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10991            if (ps == null) {
10992                return null;
10993            }
10994            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10995                    ps.readUserState(userId), userId);
10996            if (si == null) {
10997                return null;
10998            }
10999            final ResolveInfo res = new ResolveInfo();
11000            res.serviceInfo = si;
11001            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11002                res.filter = filter;
11003            }
11004            res.priority = info.getPriority();
11005            res.preferredOrder = service.owner.mPreferredOrder;
11006            res.match = match;
11007            res.isDefault = info.hasDefault;
11008            res.labelRes = info.labelRes;
11009            res.nonLocalizedLabel = info.nonLocalizedLabel;
11010            res.icon = info.icon;
11011            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11012            return res;
11013        }
11014
11015        @Override
11016        protected void sortResults(List<ResolveInfo> results) {
11017            Collections.sort(results, mResolvePrioritySorter);
11018        }
11019
11020        @Override
11021        protected void dumpFilter(PrintWriter out, String prefix,
11022                PackageParser.ServiceIntentInfo filter) {
11023            out.print(prefix); out.print(
11024                    Integer.toHexString(System.identityHashCode(filter.service)));
11025                    out.print(' ');
11026                    filter.service.printComponentShortName(out);
11027                    out.print(" filter ");
11028                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11029        }
11030
11031        @Override
11032        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11033            return filter.service;
11034        }
11035
11036        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11037            PackageParser.Service service = (PackageParser.Service)label;
11038            out.print(prefix); out.print(
11039                    Integer.toHexString(System.identityHashCode(service)));
11040                    out.print(' ');
11041                    service.printComponentShortName(out);
11042            if (count > 1) {
11043                out.print(" ("); out.print(count); out.print(" filters)");
11044            }
11045            out.println();
11046        }
11047
11048//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11049//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11050//            final List<ResolveInfo> retList = Lists.newArrayList();
11051//            while (i.hasNext()) {
11052//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11053//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11054//                    retList.add(resolveInfo);
11055//                }
11056//            }
11057//            return retList;
11058//        }
11059
11060        // Keys are String (activity class name), values are Activity.
11061        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11062                = new ArrayMap<ComponentName, PackageParser.Service>();
11063        private int mFlags;
11064    };
11065
11066    private final class ProviderIntentResolver
11067            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11068        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11069                boolean defaultOnly, int userId) {
11070            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11071            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11072        }
11073
11074        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11075                int userId) {
11076            if (!sUserManager.exists(userId))
11077                return null;
11078            mFlags = flags;
11079            return super.queryIntent(intent, resolvedType,
11080                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11081        }
11082
11083        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11084                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11085            if (!sUserManager.exists(userId))
11086                return null;
11087            if (packageProviders == null) {
11088                return null;
11089            }
11090            mFlags = flags;
11091            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11092            final int N = packageProviders.size();
11093            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11094                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11095
11096            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11097            for (int i = 0; i < N; ++i) {
11098                intentFilters = packageProviders.get(i).intents;
11099                if (intentFilters != null && intentFilters.size() > 0) {
11100                    PackageParser.ProviderIntentInfo[] array =
11101                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11102                    intentFilters.toArray(array);
11103                    listCut.add(array);
11104                }
11105            }
11106            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11107        }
11108
11109        public final void addProvider(PackageParser.Provider p) {
11110            if (mProviders.containsKey(p.getComponentName())) {
11111                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11112                return;
11113            }
11114
11115            mProviders.put(p.getComponentName(), p);
11116            if (DEBUG_SHOW_INFO) {
11117                Log.v(TAG, "  "
11118                        + (p.info.nonLocalizedLabel != null
11119                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11120                Log.v(TAG, "    Class=" + p.info.name);
11121            }
11122            final int NI = p.intents.size();
11123            int j;
11124            for (j = 0; j < NI; j++) {
11125                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11126                if (DEBUG_SHOW_INFO) {
11127                    Log.v(TAG, "    IntentFilter:");
11128                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11129                }
11130                if (!intent.debugCheck()) {
11131                    Log.w(TAG, "==> For Provider " + p.info.name);
11132                }
11133                addFilter(intent);
11134            }
11135        }
11136
11137        public final void removeProvider(PackageParser.Provider p) {
11138            mProviders.remove(p.getComponentName());
11139            if (DEBUG_SHOW_INFO) {
11140                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11141                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11142                Log.v(TAG, "    Class=" + p.info.name);
11143            }
11144            final int NI = p.intents.size();
11145            int j;
11146            for (j = 0; j < NI; j++) {
11147                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11148                if (DEBUG_SHOW_INFO) {
11149                    Log.v(TAG, "    IntentFilter:");
11150                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11151                }
11152                removeFilter(intent);
11153            }
11154        }
11155
11156        @Override
11157        protected boolean allowFilterResult(
11158                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11159            ProviderInfo filterPi = filter.provider.info;
11160            for (int i = dest.size() - 1; i >= 0; i--) {
11161                ProviderInfo destPi = dest.get(i).providerInfo;
11162                if (destPi.name == filterPi.name
11163                        && destPi.packageName == filterPi.packageName) {
11164                    return false;
11165                }
11166            }
11167            return true;
11168        }
11169
11170        @Override
11171        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11172            return new PackageParser.ProviderIntentInfo[size];
11173        }
11174
11175        @Override
11176        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11177            if (!sUserManager.exists(userId))
11178                return true;
11179            PackageParser.Package p = filter.provider.owner;
11180            if (p != null) {
11181                PackageSetting ps = (PackageSetting) p.mExtras;
11182                if (ps != null) {
11183                    // System apps are never considered stopped for purposes of
11184                    // filtering, because there may be no way for the user to
11185                    // actually re-launch them.
11186                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11187                            && ps.getStopped(userId);
11188                }
11189            }
11190            return false;
11191        }
11192
11193        @Override
11194        protected boolean isPackageForFilter(String packageName,
11195                PackageParser.ProviderIntentInfo info) {
11196            return packageName.equals(info.provider.owner.packageName);
11197        }
11198
11199        @Override
11200        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11201                int match, int userId) {
11202            if (!sUserManager.exists(userId))
11203                return null;
11204            final PackageParser.ProviderIntentInfo info = filter;
11205            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11206                return null;
11207            }
11208            final PackageParser.Provider provider = info.provider;
11209            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11210            if (ps == null) {
11211                return null;
11212            }
11213            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11214                    ps.readUserState(userId), userId);
11215            if (pi == null) {
11216                return null;
11217            }
11218            final ResolveInfo res = new ResolveInfo();
11219            res.providerInfo = pi;
11220            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11221                res.filter = filter;
11222            }
11223            res.priority = info.getPriority();
11224            res.preferredOrder = provider.owner.mPreferredOrder;
11225            res.match = match;
11226            res.isDefault = info.hasDefault;
11227            res.labelRes = info.labelRes;
11228            res.nonLocalizedLabel = info.nonLocalizedLabel;
11229            res.icon = info.icon;
11230            res.system = res.providerInfo.applicationInfo.isSystemApp();
11231            return res;
11232        }
11233
11234        @Override
11235        protected void sortResults(List<ResolveInfo> results) {
11236            Collections.sort(results, mResolvePrioritySorter);
11237        }
11238
11239        @Override
11240        protected void dumpFilter(PrintWriter out, String prefix,
11241                PackageParser.ProviderIntentInfo filter) {
11242            out.print(prefix);
11243            out.print(
11244                    Integer.toHexString(System.identityHashCode(filter.provider)));
11245            out.print(' ');
11246            filter.provider.printComponentShortName(out);
11247            out.print(" filter ");
11248            out.println(Integer.toHexString(System.identityHashCode(filter)));
11249        }
11250
11251        @Override
11252        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11253            return filter.provider;
11254        }
11255
11256        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11257            PackageParser.Provider provider = (PackageParser.Provider)label;
11258            out.print(prefix); out.print(
11259                    Integer.toHexString(System.identityHashCode(provider)));
11260                    out.print(' ');
11261                    provider.printComponentShortName(out);
11262            if (count > 1) {
11263                out.print(" ("); out.print(count); out.print(" filters)");
11264            }
11265            out.println();
11266        }
11267
11268        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11269                = new ArrayMap<ComponentName, PackageParser.Provider>();
11270        private int mFlags;
11271    }
11272
11273    private static final class EphemeralIntentResolver
11274            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11275        /**
11276         * The result that has the highest defined order. Ordering applies on a
11277         * per-package basis. Mapping is from package name to Pair of order and
11278         * EphemeralResolveInfo.
11279         * <p>
11280         * NOTE: This is implemented as a field variable for convenience and efficiency.
11281         * By having a field variable, we're able to track filter ordering as soon as
11282         * a non-zero order is defined. Otherwise, multiple loops across the result set
11283         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11284         * this needs to be contained entirely within {@link #filterResults()}.
11285         */
11286        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11287
11288        @Override
11289        protected EphemeralResolveIntentInfo[] newArray(int size) {
11290            return new EphemeralResolveIntentInfo[size];
11291        }
11292
11293        @Override
11294        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11295            return true;
11296        }
11297
11298        @Override
11299        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11300                int userId) {
11301            if (!sUserManager.exists(userId)) {
11302                return null;
11303            }
11304            final String packageName = info.getEphemeralResolveInfo().getPackageName();
11305            final Integer order = info.getOrder();
11306            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11307                    mOrderResult.get(packageName);
11308            // ordering is enabled and this item's order isn't high enough
11309            if (lastOrderResult != null && lastOrderResult.first >= order) {
11310                return null;
11311            }
11312            final EphemeralResolveInfo res = info.getEphemeralResolveInfo();
11313            if (order > 0) {
11314                // non-zero order, enable ordering
11315                mOrderResult.put(packageName, new Pair<>(order, res));
11316            }
11317            return res;
11318        }
11319
11320        @Override
11321        protected void filterResults(List<EphemeralResolveInfo> results) {
11322            // only do work if ordering is enabled [most of the time it won't be]
11323            if (mOrderResult.size() == 0) {
11324                return;
11325            }
11326            int resultSize = results.size();
11327            for (int i = 0; i < resultSize; i++) {
11328                final EphemeralResolveInfo info = results.get(i);
11329                final String packageName = info.getPackageName();
11330                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11331                if (savedInfo == null) {
11332                    // package doesn't having ordering
11333                    continue;
11334                }
11335                if (savedInfo.second == info) {
11336                    // circled back to the highest ordered item; remove from order list
11337                    mOrderResult.remove(savedInfo);
11338                    if (mOrderResult.size() == 0) {
11339                        // no more ordered items
11340                        break;
11341                    }
11342                    continue;
11343                }
11344                // item has a worse order, remove it from the result list
11345                results.remove(i);
11346                resultSize--;
11347                i--;
11348            }
11349        }
11350    }
11351
11352    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11353            new Comparator<ResolveInfo>() {
11354        public int compare(ResolveInfo r1, ResolveInfo r2) {
11355            int v1 = r1.priority;
11356            int v2 = r2.priority;
11357            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11358            if (v1 != v2) {
11359                return (v1 > v2) ? -1 : 1;
11360            }
11361            v1 = r1.preferredOrder;
11362            v2 = r2.preferredOrder;
11363            if (v1 != v2) {
11364                return (v1 > v2) ? -1 : 1;
11365            }
11366            if (r1.isDefault != r2.isDefault) {
11367                return r1.isDefault ? -1 : 1;
11368            }
11369            v1 = r1.match;
11370            v2 = r2.match;
11371            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11372            if (v1 != v2) {
11373                return (v1 > v2) ? -1 : 1;
11374            }
11375            if (r1.system != r2.system) {
11376                return r1.system ? -1 : 1;
11377            }
11378            if (r1.activityInfo != null) {
11379                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11380            }
11381            if (r1.serviceInfo != null) {
11382                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11383            }
11384            if (r1.providerInfo != null) {
11385                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11386            }
11387            return 0;
11388        }
11389    };
11390
11391    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11392            new Comparator<ProviderInfo>() {
11393        public int compare(ProviderInfo p1, ProviderInfo p2) {
11394            final int v1 = p1.initOrder;
11395            final int v2 = p2.initOrder;
11396            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11397        }
11398    };
11399
11400    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11401            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11402            final int[] userIds) {
11403        mHandler.post(new Runnable() {
11404            @Override
11405            public void run() {
11406                try {
11407                    final IActivityManager am = ActivityManagerNative.getDefault();
11408                    if (am == null) return;
11409                    final int[] resolvedUserIds;
11410                    if (userIds == null) {
11411                        resolvedUserIds = am.getRunningUserIds();
11412                    } else {
11413                        resolvedUserIds = userIds;
11414                    }
11415                    for (int id : resolvedUserIds) {
11416                        final Intent intent = new Intent(action,
11417                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11418                        if (extras != null) {
11419                            intent.putExtras(extras);
11420                        }
11421                        if (targetPkg != null) {
11422                            intent.setPackage(targetPkg);
11423                        }
11424                        // Modify the UID when posting to other users
11425                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11426                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11427                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11428                            intent.putExtra(Intent.EXTRA_UID, uid);
11429                        }
11430                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11431                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11432                        if (DEBUG_BROADCASTS) {
11433                            RuntimeException here = new RuntimeException("here");
11434                            here.fillInStackTrace();
11435                            Slog.d(TAG, "Sending to user " + id + ": "
11436                                    + intent.toShortString(false, true, false, false)
11437                                    + " " + intent.getExtras(), here);
11438                        }
11439                        am.broadcastIntent(null, intent, null, finishedReceiver,
11440                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11441                                null, finishedReceiver != null, false, id);
11442                    }
11443                } catch (RemoteException ex) {
11444                }
11445            }
11446        });
11447    }
11448
11449    /**
11450     * Check if the external storage media is available. This is true if there
11451     * is a mounted external storage medium or if the external storage is
11452     * emulated.
11453     */
11454    private boolean isExternalMediaAvailable() {
11455        return mMediaMounted || Environment.isExternalStorageEmulated();
11456    }
11457
11458    @Override
11459    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11460        // writer
11461        synchronized (mPackages) {
11462            if (!isExternalMediaAvailable()) {
11463                // If the external storage is no longer mounted at this point,
11464                // the caller may not have been able to delete all of this
11465                // packages files and can not delete any more.  Bail.
11466                return null;
11467            }
11468            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11469            if (lastPackage != null) {
11470                pkgs.remove(lastPackage);
11471            }
11472            if (pkgs.size() > 0) {
11473                return pkgs.get(0);
11474            }
11475        }
11476        return null;
11477    }
11478
11479    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11480        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11481                userId, andCode ? 1 : 0, packageName);
11482        if (mSystemReady) {
11483            msg.sendToTarget();
11484        } else {
11485            if (mPostSystemReadyMessages == null) {
11486                mPostSystemReadyMessages = new ArrayList<>();
11487            }
11488            mPostSystemReadyMessages.add(msg);
11489        }
11490    }
11491
11492    void startCleaningPackages() {
11493        // reader
11494        if (!isExternalMediaAvailable()) {
11495            return;
11496        }
11497        synchronized (mPackages) {
11498            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11499                return;
11500            }
11501        }
11502        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11503        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11504        IActivityManager am = ActivityManagerNative.getDefault();
11505        if (am != null) {
11506            try {
11507                am.startService(null, intent, null, mContext.getOpPackageName(),
11508                        UserHandle.USER_SYSTEM);
11509            } catch (RemoteException e) {
11510            }
11511        }
11512    }
11513
11514    @Override
11515    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11516            int installFlags, String installerPackageName, int userId) {
11517        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11518
11519        final int callingUid = Binder.getCallingUid();
11520        enforceCrossUserPermission(callingUid, userId,
11521                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11522
11523        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11524            try {
11525                if (observer != null) {
11526                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11527                }
11528            } catch (RemoteException re) {
11529            }
11530            return;
11531        }
11532
11533        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11534            installFlags |= PackageManager.INSTALL_FROM_ADB;
11535
11536        } else {
11537            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11538            // about installerPackageName.
11539
11540            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11541            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11542        }
11543
11544        UserHandle user;
11545        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11546            user = UserHandle.ALL;
11547        } else {
11548            user = new UserHandle(userId);
11549        }
11550
11551        // Only system components can circumvent runtime permissions when installing.
11552        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11553                && mContext.checkCallingOrSelfPermission(Manifest.permission
11554                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11555            throw new SecurityException("You need the "
11556                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11557                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11558        }
11559
11560        final File originFile = new File(originPath);
11561        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11562
11563        final Message msg = mHandler.obtainMessage(INIT_COPY);
11564        final VerificationInfo verificationInfo = new VerificationInfo(
11565                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11566        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11567                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11568                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11569                null /*certificates*/);
11570        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11571        msg.obj = params;
11572
11573        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11574                System.identityHashCode(msg.obj));
11575        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11576                System.identityHashCode(msg.obj));
11577
11578        mHandler.sendMessage(msg);
11579    }
11580
11581    void installStage(String packageName, File stagedDir, String stagedCid,
11582            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11583            String installerPackageName, int installerUid, UserHandle user,
11584            Certificate[][] certificates) {
11585        if (DEBUG_EPHEMERAL) {
11586            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11587                Slog.d(TAG, "Ephemeral install of " + packageName);
11588            }
11589        }
11590        final VerificationInfo verificationInfo = new VerificationInfo(
11591                sessionParams.originatingUri, sessionParams.referrerUri,
11592                sessionParams.originatingUid, installerUid);
11593
11594        final OriginInfo origin;
11595        if (stagedDir != null) {
11596            origin = OriginInfo.fromStagedFile(stagedDir);
11597        } else {
11598            origin = OriginInfo.fromStagedContainer(stagedCid);
11599        }
11600
11601        final Message msg = mHandler.obtainMessage(INIT_COPY);
11602        final InstallParams params = new InstallParams(origin, null, observer,
11603                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11604                verificationInfo, user, sessionParams.abiOverride,
11605                sessionParams.grantedRuntimePermissions, certificates);
11606        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11607        msg.obj = params;
11608
11609        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11610                System.identityHashCode(msg.obj));
11611        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11612                System.identityHashCode(msg.obj));
11613
11614        mHandler.sendMessage(msg);
11615    }
11616
11617    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11618            int userId) {
11619        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11620        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11621    }
11622
11623    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11624            int appId, int userId) {
11625        Bundle extras = new Bundle(1);
11626        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11627
11628        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11629                packageName, extras, 0, null, null, new int[] {userId});
11630        try {
11631            IActivityManager am = ActivityManagerNative.getDefault();
11632            if (isSystem && am.isUserRunning(userId, 0)) {
11633                // The just-installed/enabled app is bundled on the system, so presumed
11634                // to be able to run automatically without needing an explicit launch.
11635                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11636                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11637                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11638                        .setPackage(packageName);
11639                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11640                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11641            }
11642        } catch (RemoteException e) {
11643            // shouldn't happen
11644            Slog.w(TAG, "Unable to bootstrap installed package", e);
11645        }
11646    }
11647
11648    @Override
11649    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11650            int userId) {
11651        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11652        PackageSetting pkgSetting;
11653        final int uid = Binder.getCallingUid();
11654        enforceCrossUserPermission(uid, userId,
11655                true /* requireFullPermission */, true /* checkShell */,
11656                "setApplicationHiddenSetting for user " + userId);
11657
11658        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11659            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11660            return false;
11661        }
11662
11663        long callingId = Binder.clearCallingIdentity();
11664        try {
11665            boolean sendAdded = false;
11666            boolean sendRemoved = false;
11667            // writer
11668            synchronized (mPackages) {
11669                pkgSetting = mSettings.mPackages.get(packageName);
11670                if (pkgSetting == null) {
11671                    return false;
11672                }
11673                // Do not allow "android" is being disabled
11674                if ("android".equals(packageName)) {
11675                    Slog.w(TAG, "Cannot hide package: android");
11676                    return false;
11677                }
11678                // Only allow protected packages to hide themselves.
11679                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11680                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11681                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11682                    return false;
11683                }
11684
11685                if (pkgSetting.getHidden(userId) != hidden) {
11686                    pkgSetting.setHidden(hidden, userId);
11687                    mSettings.writePackageRestrictionsLPr(userId);
11688                    if (hidden) {
11689                        sendRemoved = true;
11690                    } else {
11691                        sendAdded = true;
11692                    }
11693                }
11694            }
11695            if (sendAdded) {
11696                sendPackageAddedForUser(packageName, pkgSetting, userId);
11697                return true;
11698            }
11699            if (sendRemoved) {
11700                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11701                        "hiding pkg");
11702                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11703                return true;
11704            }
11705        } finally {
11706            Binder.restoreCallingIdentity(callingId);
11707        }
11708        return false;
11709    }
11710
11711    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11712            int userId) {
11713        final PackageRemovedInfo info = new PackageRemovedInfo();
11714        info.removedPackage = packageName;
11715        info.removedUsers = new int[] {userId};
11716        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11717        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11718    }
11719
11720    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11721        if (pkgList.length > 0) {
11722            Bundle extras = new Bundle(1);
11723            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11724
11725            sendPackageBroadcast(
11726                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11727                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11728                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11729                    new int[] {userId});
11730        }
11731    }
11732
11733    /**
11734     * Returns true if application is not found or there was an error. Otherwise it returns
11735     * the hidden state of the package for the given user.
11736     */
11737    @Override
11738    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11739        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11740        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11741                true /* requireFullPermission */, false /* checkShell */,
11742                "getApplicationHidden for user " + userId);
11743        PackageSetting pkgSetting;
11744        long callingId = Binder.clearCallingIdentity();
11745        try {
11746            // writer
11747            synchronized (mPackages) {
11748                pkgSetting = mSettings.mPackages.get(packageName);
11749                if (pkgSetting == null) {
11750                    return true;
11751                }
11752                return pkgSetting.getHidden(userId);
11753            }
11754        } finally {
11755            Binder.restoreCallingIdentity(callingId);
11756        }
11757    }
11758
11759    /**
11760     * @hide
11761     */
11762    @Override
11763    public int installExistingPackageAsUser(String packageName, int userId) {
11764        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11765                null);
11766        PackageSetting pkgSetting;
11767        final int uid = Binder.getCallingUid();
11768        enforceCrossUserPermission(uid, userId,
11769                true /* requireFullPermission */, true /* checkShell */,
11770                "installExistingPackage for user " + userId);
11771        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11772            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11773        }
11774
11775        long callingId = Binder.clearCallingIdentity();
11776        try {
11777            boolean installed = false;
11778
11779            // writer
11780            synchronized (mPackages) {
11781                pkgSetting = mSettings.mPackages.get(packageName);
11782                if (pkgSetting == null) {
11783                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11784                }
11785                if (!pkgSetting.getInstalled(userId)) {
11786                    pkgSetting.setInstalled(true, userId);
11787                    pkgSetting.setHidden(false, userId);
11788                    mSettings.writePackageRestrictionsLPr(userId);
11789                    installed = true;
11790                }
11791            }
11792
11793            if (installed) {
11794                if (pkgSetting.pkg != null) {
11795                    synchronized (mInstallLock) {
11796                        // We don't need to freeze for a brand new install
11797                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11798                    }
11799                }
11800                sendPackageAddedForUser(packageName, pkgSetting, userId);
11801            }
11802        } finally {
11803            Binder.restoreCallingIdentity(callingId);
11804        }
11805
11806        return PackageManager.INSTALL_SUCCEEDED;
11807    }
11808
11809    boolean isUserRestricted(int userId, String restrictionKey) {
11810        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11811        if (restrictions.getBoolean(restrictionKey, false)) {
11812            Log.w(TAG, "User is restricted: " + restrictionKey);
11813            return true;
11814        }
11815        return false;
11816    }
11817
11818    @Override
11819    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11820            int userId) {
11821        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11822        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11823                true /* requireFullPermission */, true /* checkShell */,
11824                "setPackagesSuspended for user " + userId);
11825
11826        if (ArrayUtils.isEmpty(packageNames)) {
11827            return packageNames;
11828        }
11829
11830        // List of package names for whom the suspended state has changed.
11831        List<String> changedPackages = new ArrayList<>(packageNames.length);
11832        // List of package names for whom the suspended state is not set as requested in this
11833        // method.
11834        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11835        long callingId = Binder.clearCallingIdentity();
11836        try {
11837            for (int i = 0; i < packageNames.length; i++) {
11838                String packageName = packageNames[i];
11839                boolean changed = false;
11840                final int appId;
11841                synchronized (mPackages) {
11842                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11843                    if (pkgSetting == null) {
11844                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11845                                + "\". Skipping suspending/un-suspending.");
11846                        unactionedPackages.add(packageName);
11847                        continue;
11848                    }
11849                    appId = pkgSetting.appId;
11850                    if (pkgSetting.getSuspended(userId) != suspended) {
11851                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11852                            unactionedPackages.add(packageName);
11853                            continue;
11854                        }
11855                        pkgSetting.setSuspended(suspended, userId);
11856                        mSettings.writePackageRestrictionsLPr(userId);
11857                        changed = true;
11858                        changedPackages.add(packageName);
11859                    }
11860                }
11861
11862                if (changed && suspended) {
11863                    killApplication(packageName, UserHandle.getUid(userId, appId),
11864                            "suspending package");
11865                }
11866            }
11867        } finally {
11868            Binder.restoreCallingIdentity(callingId);
11869        }
11870
11871        if (!changedPackages.isEmpty()) {
11872            sendPackagesSuspendedForUser(changedPackages.toArray(
11873                    new String[changedPackages.size()]), userId, suspended);
11874        }
11875
11876        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11877    }
11878
11879    @Override
11880    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11881        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11882                true /* requireFullPermission */, false /* checkShell */,
11883                "isPackageSuspendedForUser for user " + userId);
11884        synchronized (mPackages) {
11885            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11886            if (pkgSetting == null) {
11887                throw new IllegalArgumentException("Unknown target package: " + packageName);
11888            }
11889            return pkgSetting.getSuspended(userId);
11890        }
11891    }
11892
11893    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11894        if (isPackageDeviceAdmin(packageName, userId)) {
11895            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11896                    + "\": has an active device admin");
11897            return false;
11898        }
11899
11900        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11901        if (packageName.equals(activeLauncherPackageName)) {
11902            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11903                    + "\": contains the active launcher");
11904            return false;
11905        }
11906
11907        if (packageName.equals(mRequiredInstallerPackage)) {
11908            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11909                    + "\": required for package installation");
11910            return false;
11911        }
11912
11913        if (packageName.equals(mRequiredUninstallerPackage)) {
11914            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11915                    + "\": required for package uninstallation");
11916            return false;
11917        }
11918
11919        if (packageName.equals(mRequiredVerifierPackage)) {
11920            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11921                    + "\": required for package verification");
11922            return false;
11923        }
11924
11925        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11926            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11927                    + "\": is the default dialer");
11928            return false;
11929        }
11930
11931        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11932            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11933                    + "\": protected package");
11934            return false;
11935        }
11936
11937        return true;
11938    }
11939
11940    private String getActiveLauncherPackageName(int userId) {
11941        Intent intent = new Intent(Intent.ACTION_MAIN);
11942        intent.addCategory(Intent.CATEGORY_HOME);
11943        ResolveInfo resolveInfo = resolveIntent(
11944                intent,
11945                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11946                PackageManager.MATCH_DEFAULT_ONLY,
11947                userId);
11948
11949        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11950    }
11951
11952    private String getDefaultDialerPackageName(int userId) {
11953        synchronized (mPackages) {
11954            return mSettings.getDefaultDialerPackageNameLPw(userId);
11955        }
11956    }
11957
11958    @Override
11959    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11960        mContext.enforceCallingOrSelfPermission(
11961                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11962                "Only package verification agents can verify applications");
11963
11964        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11965        final PackageVerificationResponse response = new PackageVerificationResponse(
11966                verificationCode, Binder.getCallingUid());
11967        msg.arg1 = id;
11968        msg.obj = response;
11969        mHandler.sendMessage(msg);
11970    }
11971
11972    @Override
11973    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11974            long millisecondsToDelay) {
11975        mContext.enforceCallingOrSelfPermission(
11976                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11977                "Only package verification agents can extend verification timeouts");
11978
11979        final PackageVerificationState state = mPendingVerification.get(id);
11980        final PackageVerificationResponse response = new PackageVerificationResponse(
11981                verificationCodeAtTimeout, Binder.getCallingUid());
11982
11983        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11984            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11985        }
11986        if (millisecondsToDelay < 0) {
11987            millisecondsToDelay = 0;
11988        }
11989        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11990                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11991            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11992        }
11993
11994        if ((state != null) && !state.timeoutExtended()) {
11995            state.extendTimeout();
11996
11997            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11998            msg.arg1 = id;
11999            msg.obj = response;
12000            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12001        }
12002    }
12003
12004    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12005            int verificationCode, UserHandle user) {
12006        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12007        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12008        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12009        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12010        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12011
12012        mContext.sendBroadcastAsUser(intent, user,
12013                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12014    }
12015
12016    private ComponentName matchComponentForVerifier(String packageName,
12017            List<ResolveInfo> receivers) {
12018        ActivityInfo targetReceiver = null;
12019
12020        final int NR = receivers.size();
12021        for (int i = 0; i < NR; i++) {
12022            final ResolveInfo info = receivers.get(i);
12023            if (info.activityInfo == null) {
12024                continue;
12025            }
12026
12027            if (packageName.equals(info.activityInfo.packageName)) {
12028                targetReceiver = info.activityInfo;
12029                break;
12030            }
12031        }
12032
12033        if (targetReceiver == null) {
12034            return null;
12035        }
12036
12037        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12038    }
12039
12040    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12041            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12042        if (pkgInfo.verifiers.length == 0) {
12043            return null;
12044        }
12045
12046        final int N = pkgInfo.verifiers.length;
12047        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12048        for (int i = 0; i < N; i++) {
12049            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12050
12051            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12052                    receivers);
12053            if (comp == null) {
12054                continue;
12055            }
12056
12057            final int verifierUid = getUidForVerifier(verifierInfo);
12058            if (verifierUid == -1) {
12059                continue;
12060            }
12061
12062            if (DEBUG_VERIFY) {
12063                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12064                        + " with the correct signature");
12065            }
12066            sufficientVerifiers.add(comp);
12067            verificationState.addSufficientVerifier(verifierUid);
12068        }
12069
12070        return sufficientVerifiers;
12071    }
12072
12073    private int getUidForVerifier(VerifierInfo verifierInfo) {
12074        synchronized (mPackages) {
12075            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12076            if (pkg == null) {
12077                return -1;
12078            } else if (pkg.mSignatures.length != 1) {
12079                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12080                        + " has more than one signature; ignoring");
12081                return -1;
12082            }
12083
12084            /*
12085             * If the public key of the package's signature does not match
12086             * our expected public key, then this is a different package and
12087             * we should skip.
12088             */
12089
12090            final byte[] expectedPublicKey;
12091            try {
12092                final Signature verifierSig = pkg.mSignatures[0];
12093                final PublicKey publicKey = verifierSig.getPublicKey();
12094                expectedPublicKey = publicKey.getEncoded();
12095            } catch (CertificateException e) {
12096                return -1;
12097            }
12098
12099            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12100
12101            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12102                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12103                        + " does not have the expected public key; ignoring");
12104                return -1;
12105            }
12106
12107            return pkg.applicationInfo.uid;
12108        }
12109    }
12110
12111    @Override
12112    public void finishPackageInstall(int token, boolean didLaunch) {
12113        enforceSystemOrRoot("Only the system is allowed to finish installs");
12114
12115        if (DEBUG_INSTALL) {
12116            Slog.v(TAG, "BM finishing package install for " + token);
12117        }
12118        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12119
12120        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12121        mHandler.sendMessage(msg);
12122    }
12123
12124    /**
12125     * Get the verification agent timeout.
12126     *
12127     * @return verification timeout in milliseconds
12128     */
12129    private long getVerificationTimeout() {
12130        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12131                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12132                DEFAULT_VERIFICATION_TIMEOUT);
12133    }
12134
12135    /**
12136     * Get the default verification agent response code.
12137     *
12138     * @return default verification response code
12139     */
12140    private int getDefaultVerificationResponse() {
12141        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12142                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12143                DEFAULT_VERIFICATION_RESPONSE);
12144    }
12145
12146    /**
12147     * Check whether or not package verification has been enabled.
12148     *
12149     * @return true if verification should be performed
12150     */
12151    private boolean isVerificationEnabled(int userId, int installFlags) {
12152        if (!DEFAULT_VERIFY_ENABLE) {
12153            return false;
12154        }
12155        // Ephemeral apps don't get the full verification treatment
12156        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12157            if (DEBUG_EPHEMERAL) {
12158                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12159            }
12160            return false;
12161        }
12162
12163        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12164
12165        // Check if installing from ADB
12166        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12167            // Do not run verification in a test harness environment
12168            if (ActivityManager.isRunningInTestHarness()) {
12169                return false;
12170            }
12171            if (ensureVerifyAppsEnabled) {
12172                return true;
12173            }
12174            // Check if the developer does not want package verification for ADB installs
12175            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12176                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12177                return false;
12178            }
12179        }
12180
12181        if (ensureVerifyAppsEnabled) {
12182            return true;
12183        }
12184
12185        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12186                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12187    }
12188
12189    @Override
12190    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12191            throws RemoteException {
12192        mContext.enforceCallingOrSelfPermission(
12193                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12194                "Only intentfilter verification agents can verify applications");
12195
12196        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12197        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12198                Binder.getCallingUid(), verificationCode, failedDomains);
12199        msg.arg1 = id;
12200        msg.obj = response;
12201        mHandler.sendMessage(msg);
12202    }
12203
12204    @Override
12205    public int getIntentVerificationStatus(String packageName, int userId) {
12206        synchronized (mPackages) {
12207            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12208        }
12209    }
12210
12211    @Override
12212    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12213        mContext.enforceCallingOrSelfPermission(
12214                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12215
12216        boolean result = false;
12217        synchronized (mPackages) {
12218            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12219        }
12220        if (result) {
12221            scheduleWritePackageRestrictionsLocked(userId);
12222        }
12223        return result;
12224    }
12225
12226    @Override
12227    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12228            String packageName) {
12229        synchronized (mPackages) {
12230            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12231        }
12232    }
12233
12234    @Override
12235    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12236        if (TextUtils.isEmpty(packageName)) {
12237            return ParceledListSlice.emptyList();
12238        }
12239        synchronized (mPackages) {
12240            PackageParser.Package pkg = mPackages.get(packageName);
12241            if (pkg == null || pkg.activities == null) {
12242                return ParceledListSlice.emptyList();
12243            }
12244            final int count = pkg.activities.size();
12245            ArrayList<IntentFilter> result = new ArrayList<>();
12246            for (int n=0; n<count; n++) {
12247                PackageParser.Activity activity = pkg.activities.get(n);
12248                if (activity.intents != null && activity.intents.size() > 0) {
12249                    result.addAll(activity.intents);
12250                }
12251            }
12252            return new ParceledListSlice<>(result);
12253        }
12254    }
12255
12256    @Override
12257    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12258        mContext.enforceCallingOrSelfPermission(
12259                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12260
12261        synchronized (mPackages) {
12262            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12263            if (packageName != null) {
12264                result |= updateIntentVerificationStatus(packageName,
12265                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12266                        userId);
12267                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12268                        packageName, userId);
12269            }
12270            return result;
12271        }
12272    }
12273
12274    @Override
12275    public String getDefaultBrowserPackageName(int userId) {
12276        synchronized (mPackages) {
12277            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12278        }
12279    }
12280
12281    /**
12282     * Get the "allow unknown sources" setting.
12283     *
12284     * @return the current "allow unknown sources" setting
12285     */
12286    private int getUnknownSourcesSettings() {
12287        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12288                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12289                -1);
12290    }
12291
12292    @Override
12293    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12294        final int uid = Binder.getCallingUid();
12295        // writer
12296        synchronized (mPackages) {
12297            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12298            if (targetPackageSetting == null) {
12299                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12300            }
12301
12302            PackageSetting installerPackageSetting;
12303            if (installerPackageName != null) {
12304                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12305                if (installerPackageSetting == null) {
12306                    throw new IllegalArgumentException("Unknown installer package: "
12307                            + installerPackageName);
12308                }
12309            } else {
12310                installerPackageSetting = null;
12311            }
12312
12313            Signature[] callerSignature;
12314            Object obj = mSettings.getUserIdLPr(uid);
12315            if (obj != null) {
12316                if (obj instanceof SharedUserSetting) {
12317                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12318                } else if (obj instanceof PackageSetting) {
12319                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12320                } else {
12321                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12322                }
12323            } else {
12324                throw new SecurityException("Unknown calling UID: " + uid);
12325            }
12326
12327            // Verify: can't set installerPackageName to a package that is
12328            // not signed with the same cert as the caller.
12329            if (installerPackageSetting != null) {
12330                if (compareSignatures(callerSignature,
12331                        installerPackageSetting.signatures.mSignatures)
12332                        != PackageManager.SIGNATURE_MATCH) {
12333                    throw new SecurityException(
12334                            "Caller does not have same cert as new installer package "
12335                            + installerPackageName);
12336                }
12337            }
12338
12339            // Verify: if target already has an installer package, it must
12340            // be signed with the same cert as the caller.
12341            if (targetPackageSetting.installerPackageName != null) {
12342                PackageSetting setting = mSettings.mPackages.get(
12343                        targetPackageSetting.installerPackageName);
12344                // If the currently set package isn't valid, then it's always
12345                // okay to change it.
12346                if (setting != null) {
12347                    if (compareSignatures(callerSignature,
12348                            setting.signatures.mSignatures)
12349                            != PackageManager.SIGNATURE_MATCH) {
12350                        throw new SecurityException(
12351                                "Caller does not have same cert as old installer package "
12352                                + targetPackageSetting.installerPackageName);
12353                    }
12354                }
12355            }
12356
12357            // Okay!
12358            targetPackageSetting.installerPackageName = installerPackageName;
12359            if (installerPackageName != null) {
12360                mSettings.mInstallerPackages.add(installerPackageName);
12361            }
12362            scheduleWriteSettingsLocked();
12363        }
12364    }
12365
12366    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12367        // Queue up an async operation since the package installation may take a little while.
12368        mHandler.post(new Runnable() {
12369            public void run() {
12370                mHandler.removeCallbacks(this);
12371                 // Result object to be returned
12372                PackageInstalledInfo res = new PackageInstalledInfo();
12373                res.setReturnCode(currentStatus);
12374                res.uid = -1;
12375                res.pkg = null;
12376                res.removedInfo = null;
12377                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12378                    args.doPreInstall(res.returnCode);
12379                    synchronized (mInstallLock) {
12380                        installPackageTracedLI(args, res);
12381                    }
12382                    args.doPostInstall(res.returnCode, res.uid);
12383                }
12384
12385                // A restore should be performed at this point if (a) the install
12386                // succeeded, (b) the operation is not an update, and (c) the new
12387                // package has not opted out of backup participation.
12388                final boolean update = res.removedInfo != null
12389                        && res.removedInfo.removedPackage != null;
12390                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12391                boolean doRestore = !update
12392                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12393
12394                // Set up the post-install work request bookkeeping.  This will be used
12395                // and cleaned up by the post-install event handling regardless of whether
12396                // there's a restore pass performed.  Token values are >= 1.
12397                int token;
12398                if (mNextInstallToken < 0) mNextInstallToken = 1;
12399                token = mNextInstallToken++;
12400
12401                PostInstallData data = new PostInstallData(args, res);
12402                mRunningInstalls.put(token, data);
12403                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12404
12405                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12406                    // Pass responsibility to the Backup Manager.  It will perform a
12407                    // restore if appropriate, then pass responsibility back to the
12408                    // Package Manager to run the post-install observer callbacks
12409                    // and broadcasts.
12410                    IBackupManager bm = IBackupManager.Stub.asInterface(
12411                            ServiceManager.getService(Context.BACKUP_SERVICE));
12412                    if (bm != null) {
12413                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12414                                + " to BM for possible restore");
12415                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12416                        try {
12417                            // TODO: http://b/22388012
12418                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12419                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12420                            } else {
12421                                doRestore = false;
12422                            }
12423                        } catch (RemoteException e) {
12424                            // can't happen; the backup manager is local
12425                        } catch (Exception e) {
12426                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12427                            doRestore = false;
12428                        }
12429                    } else {
12430                        Slog.e(TAG, "Backup Manager not found!");
12431                        doRestore = false;
12432                    }
12433                }
12434
12435                if (!doRestore) {
12436                    // No restore possible, or the Backup Manager was mysteriously not
12437                    // available -- just fire the post-install work request directly.
12438                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12439
12440                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12441
12442                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12443                    mHandler.sendMessage(msg);
12444                }
12445            }
12446        });
12447    }
12448
12449    /**
12450     * Callback from PackageSettings whenever an app is first transitioned out of the
12451     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12452     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12453     * here whether the app is the target of an ongoing install, and only send the
12454     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12455     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12456     * handling.
12457     */
12458    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12459        // Serialize this with the rest of the install-process message chain.  In the
12460        // restore-at-install case, this Runnable will necessarily run before the
12461        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12462        // are coherent.  In the non-restore case, the app has already completed install
12463        // and been launched through some other means, so it is not in a problematic
12464        // state for observers to see the FIRST_LAUNCH signal.
12465        mHandler.post(new Runnable() {
12466            @Override
12467            public void run() {
12468                for (int i = 0; i < mRunningInstalls.size(); i++) {
12469                    final PostInstallData data = mRunningInstalls.valueAt(i);
12470                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12471                        continue;
12472                    }
12473                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12474                        // right package; but is it for the right user?
12475                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12476                            if (userId == data.res.newUsers[uIndex]) {
12477                                if (DEBUG_BACKUP) {
12478                                    Slog.i(TAG, "Package " + pkgName
12479                                            + " being restored so deferring FIRST_LAUNCH");
12480                                }
12481                                return;
12482                            }
12483                        }
12484                    }
12485                }
12486                // didn't find it, so not being restored
12487                if (DEBUG_BACKUP) {
12488                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12489                }
12490                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12491            }
12492        });
12493    }
12494
12495    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12496        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12497                installerPkg, null, userIds);
12498    }
12499
12500    private abstract class HandlerParams {
12501        private static final int MAX_RETRIES = 4;
12502
12503        /**
12504         * Number of times startCopy() has been attempted and had a non-fatal
12505         * error.
12506         */
12507        private int mRetries = 0;
12508
12509        /** User handle for the user requesting the information or installation. */
12510        private final UserHandle mUser;
12511        String traceMethod;
12512        int traceCookie;
12513
12514        HandlerParams(UserHandle user) {
12515            mUser = user;
12516        }
12517
12518        UserHandle getUser() {
12519            return mUser;
12520        }
12521
12522        HandlerParams setTraceMethod(String traceMethod) {
12523            this.traceMethod = traceMethod;
12524            return this;
12525        }
12526
12527        HandlerParams setTraceCookie(int traceCookie) {
12528            this.traceCookie = traceCookie;
12529            return this;
12530        }
12531
12532        final boolean startCopy() {
12533            boolean res;
12534            try {
12535                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12536
12537                if (++mRetries > MAX_RETRIES) {
12538                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12539                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12540                    handleServiceError();
12541                    return false;
12542                } else {
12543                    handleStartCopy();
12544                    res = true;
12545                }
12546            } catch (RemoteException e) {
12547                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12548                mHandler.sendEmptyMessage(MCS_RECONNECT);
12549                res = false;
12550            }
12551            handleReturnCode();
12552            return res;
12553        }
12554
12555        final void serviceError() {
12556            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12557            handleServiceError();
12558            handleReturnCode();
12559        }
12560
12561        abstract void handleStartCopy() throws RemoteException;
12562        abstract void handleServiceError();
12563        abstract void handleReturnCode();
12564    }
12565
12566    class MeasureParams extends HandlerParams {
12567        private final PackageStats mStats;
12568        private boolean mSuccess;
12569
12570        private final IPackageStatsObserver mObserver;
12571
12572        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12573            super(new UserHandle(stats.userHandle));
12574            mObserver = observer;
12575            mStats = stats;
12576        }
12577
12578        @Override
12579        public String toString() {
12580            return "MeasureParams{"
12581                + Integer.toHexString(System.identityHashCode(this))
12582                + " " + mStats.packageName + "}";
12583        }
12584
12585        @Override
12586        void handleStartCopy() throws RemoteException {
12587            synchronized (mInstallLock) {
12588                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12589            }
12590
12591            if (mSuccess) {
12592                boolean mounted = false;
12593                try {
12594                    final String status = Environment.getExternalStorageState();
12595                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12596                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12597                } catch (Exception e) {
12598                }
12599
12600                if (mounted) {
12601                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12602
12603                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12604                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12605
12606                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12607                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12608
12609                    // Always subtract cache size, since it's a subdirectory
12610                    mStats.externalDataSize -= mStats.externalCacheSize;
12611
12612                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12613                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12614
12615                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12616                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12617                }
12618            }
12619        }
12620
12621        @Override
12622        void handleReturnCode() {
12623            if (mObserver != null) {
12624                try {
12625                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12626                } catch (RemoteException e) {
12627                    Slog.i(TAG, "Observer no longer exists.");
12628                }
12629            }
12630        }
12631
12632        @Override
12633        void handleServiceError() {
12634            Slog.e(TAG, "Could not measure application " + mStats.packageName
12635                            + " external storage");
12636        }
12637    }
12638
12639    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12640            throws RemoteException {
12641        long result = 0;
12642        for (File path : paths) {
12643            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12644        }
12645        return result;
12646    }
12647
12648    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12649        for (File path : paths) {
12650            try {
12651                mcs.clearDirectory(path.getAbsolutePath());
12652            } catch (RemoteException e) {
12653            }
12654        }
12655    }
12656
12657    static class OriginInfo {
12658        /**
12659         * Location where install is coming from, before it has been
12660         * copied/renamed into place. This could be a single monolithic APK
12661         * file, or a cluster directory. This location may be untrusted.
12662         */
12663        final File file;
12664        final String cid;
12665
12666        /**
12667         * Flag indicating that {@link #file} or {@link #cid} has already been
12668         * staged, meaning downstream users don't need to defensively copy the
12669         * contents.
12670         */
12671        final boolean staged;
12672
12673        /**
12674         * Flag indicating that {@link #file} or {@link #cid} is an already
12675         * installed app that is being moved.
12676         */
12677        final boolean existing;
12678
12679        final String resolvedPath;
12680        final File resolvedFile;
12681
12682        static OriginInfo fromNothing() {
12683            return new OriginInfo(null, null, false, false);
12684        }
12685
12686        static OriginInfo fromUntrustedFile(File file) {
12687            return new OriginInfo(file, null, false, false);
12688        }
12689
12690        static OriginInfo fromExistingFile(File file) {
12691            return new OriginInfo(file, null, false, true);
12692        }
12693
12694        static OriginInfo fromStagedFile(File file) {
12695            return new OriginInfo(file, null, true, false);
12696        }
12697
12698        static OriginInfo fromStagedContainer(String cid) {
12699            return new OriginInfo(null, cid, true, false);
12700        }
12701
12702        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12703            this.file = file;
12704            this.cid = cid;
12705            this.staged = staged;
12706            this.existing = existing;
12707
12708            if (cid != null) {
12709                resolvedPath = PackageHelper.getSdDir(cid);
12710                resolvedFile = new File(resolvedPath);
12711            } else if (file != null) {
12712                resolvedPath = file.getAbsolutePath();
12713                resolvedFile = file;
12714            } else {
12715                resolvedPath = null;
12716                resolvedFile = null;
12717            }
12718        }
12719    }
12720
12721    static class MoveInfo {
12722        final int moveId;
12723        final String fromUuid;
12724        final String toUuid;
12725        final String packageName;
12726        final String dataAppName;
12727        final int appId;
12728        final String seinfo;
12729        final int targetSdkVersion;
12730
12731        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12732                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12733            this.moveId = moveId;
12734            this.fromUuid = fromUuid;
12735            this.toUuid = toUuid;
12736            this.packageName = packageName;
12737            this.dataAppName = dataAppName;
12738            this.appId = appId;
12739            this.seinfo = seinfo;
12740            this.targetSdkVersion = targetSdkVersion;
12741        }
12742    }
12743
12744    static class VerificationInfo {
12745        /** A constant used to indicate that a uid value is not present. */
12746        public static final int NO_UID = -1;
12747
12748        /** URI referencing where the package was downloaded from. */
12749        final Uri originatingUri;
12750
12751        /** HTTP referrer URI associated with the originatingURI. */
12752        final Uri referrer;
12753
12754        /** UID of the application that the install request originated from. */
12755        final int originatingUid;
12756
12757        /** UID of application requesting the install */
12758        final int installerUid;
12759
12760        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12761            this.originatingUri = originatingUri;
12762            this.referrer = referrer;
12763            this.originatingUid = originatingUid;
12764            this.installerUid = installerUid;
12765        }
12766    }
12767
12768    class InstallParams extends HandlerParams {
12769        final OriginInfo origin;
12770        final MoveInfo move;
12771        final IPackageInstallObserver2 observer;
12772        int installFlags;
12773        final String installerPackageName;
12774        final String volumeUuid;
12775        private InstallArgs mArgs;
12776        private int mRet;
12777        final String packageAbiOverride;
12778        final String[] grantedRuntimePermissions;
12779        final VerificationInfo verificationInfo;
12780        final Certificate[][] certificates;
12781
12782        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12783                int installFlags, String installerPackageName, String volumeUuid,
12784                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12785                String[] grantedPermissions, Certificate[][] certificates) {
12786            super(user);
12787            this.origin = origin;
12788            this.move = move;
12789            this.observer = observer;
12790            this.installFlags = installFlags;
12791            this.installerPackageName = installerPackageName;
12792            this.volumeUuid = volumeUuid;
12793            this.verificationInfo = verificationInfo;
12794            this.packageAbiOverride = packageAbiOverride;
12795            this.grantedRuntimePermissions = grantedPermissions;
12796            this.certificates = certificates;
12797        }
12798
12799        @Override
12800        public String toString() {
12801            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12802                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12803        }
12804
12805        private int installLocationPolicy(PackageInfoLite pkgLite) {
12806            String packageName = pkgLite.packageName;
12807            int installLocation = pkgLite.installLocation;
12808            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12809            // reader
12810            synchronized (mPackages) {
12811                // Currently installed package which the new package is attempting to replace or
12812                // null if no such package is installed.
12813                PackageParser.Package installedPkg = mPackages.get(packageName);
12814                // Package which currently owns the data which the new package will own if installed.
12815                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12816                // will be null whereas dataOwnerPkg will contain information about the package
12817                // which was uninstalled while keeping its data.
12818                PackageParser.Package dataOwnerPkg = installedPkg;
12819                if (dataOwnerPkg  == null) {
12820                    PackageSetting ps = mSettings.mPackages.get(packageName);
12821                    if (ps != null) {
12822                        dataOwnerPkg = ps.pkg;
12823                    }
12824                }
12825
12826                if (dataOwnerPkg != null) {
12827                    // If installed, the package will get access to data left on the device by its
12828                    // predecessor. As a security measure, this is permited only if this is not a
12829                    // version downgrade or if the predecessor package is marked as debuggable and
12830                    // a downgrade is explicitly requested.
12831                    //
12832                    // On debuggable platform builds, downgrades are permitted even for
12833                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12834                    // not offer security guarantees and thus it's OK to disable some security
12835                    // mechanisms to make debugging/testing easier on those builds. However, even on
12836                    // debuggable builds downgrades of packages are permitted only if requested via
12837                    // installFlags. This is because we aim to keep the behavior of debuggable
12838                    // platform builds as close as possible to the behavior of non-debuggable
12839                    // platform builds.
12840                    final boolean downgradeRequested =
12841                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12842                    final boolean packageDebuggable =
12843                                (dataOwnerPkg.applicationInfo.flags
12844                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12845                    final boolean downgradePermitted =
12846                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12847                    if (!downgradePermitted) {
12848                        try {
12849                            checkDowngrade(dataOwnerPkg, pkgLite);
12850                        } catch (PackageManagerException e) {
12851                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12852                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12853                        }
12854                    }
12855                }
12856
12857                if (installedPkg != null) {
12858                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12859                        // Check for updated system application.
12860                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12861                            if (onSd) {
12862                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12863                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12864                            }
12865                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12866                        } else {
12867                            if (onSd) {
12868                                // Install flag overrides everything.
12869                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12870                            }
12871                            // If current upgrade specifies particular preference
12872                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12873                                // Application explicitly specified internal.
12874                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12875                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12876                                // App explictly prefers external. Let policy decide
12877                            } else {
12878                                // Prefer previous location
12879                                if (isExternal(installedPkg)) {
12880                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12881                                }
12882                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12883                            }
12884                        }
12885                    } else {
12886                        // Invalid install. Return error code
12887                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12888                    }
12889                }
12890            }
12891            // All the special cases have been taken care of.
12892            // Return result based on recommended install location.
12893            if (onSd) {
12894                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12895            }
12896            return pkgLite.recommendedInstallLocation;
12897        }
12898
12899        /*
12900         * Invoke remote method to get package information and install
12901         * location values. Override install location based on default
12902         * policy if needed and then create install arguments based
12903         * on the install location.
12904         */
12905        public void handleStartCopy() throws RemoteException {
12906            int ret = PackageManager.INSTALL_SUCCEEDED;
12907
12908            // If we're already staged, we've firmly committed to an install location
12909            if (origin.staged) {
12910                if (origin.file != null) {
12911                    installFlags |= PackageManager.INSTALL_INTERNAL;
12912                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12913                } else if (origin.cid != null) {
12914                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12915                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12916                } else {
12917                    throw new IllegalStateException("Invalid stage location");
12918                }
12919            }
12920
12921            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12922            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12923            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12924            PackageInfoLite pkgLite = null;
12925
12926            if (onInt && onSd) {
12927                // Check if both bits are set.
12928                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12929                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12930            } else if (onSd && ephemeral) {
12931                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12932                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12933            } else {
12934                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12935                        packageAbiOverride);
12936
12937                if (DEBUG_EPHEMERAL && ephemeral) {
12938                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12939                }
12940
12941                /*
12942                 * If we have too little free space, try to free cache
12943                 * before giving up.
12944                 */
12945                if (!origin.staged && pkgLite.recommendedInstallLocation
12946                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12947                    // TODO: focus freeing disk space on the target device
12948                    final StorageManager storage = StorageManager.from(mContext);
12949                    final long lowThreshold = storage.getStorageLowBytes(
12950                            Environment.getDataDirectory());
12951
12952                    final long sizeBytes = mContainerService.calculateInstalledSize(
12953                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12954
12955                    try {
12956                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12957                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12958                                installFlags, packageAbiOverride);
12959                    } catch (InstallerException e) {
12960                        Slog.w(TAG, "Failed to free cache", e);
12961                    }
12962
12963                    /*
12964                     * The cache free must have deleted the file we
12965                     * downloaded to install.
12966                     *
12967                     * TODO: fix the "freeCache" call to not delete
12968                     *       the file we care about.
12969                     */
12970                    if (pkgLite.recommendedInstallLocation
12971                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12972                        pkgLite.recommendedInstallLocation
12973                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12974                    }
12975                }
12976            }
12977
12978            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12979                int loc = pkgLite.recommendedInstallLocation;
12980                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12981                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12982                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12983                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12984                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12985                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12986                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12987                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12988                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12989                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12990                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12991                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12992                } else {
12993                    // Override with defaults if needed.
12994                    loc = installLocationPolicy(pkgLite);
12995                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12996                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12997                    } else if (!onSd && !onInt) {
12998                        // Override install location with flags
12999                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13000                            // Set the flag to install on external media.
13001                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13002                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13003                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13004                            if (DEBUG_EPHEMERAL) {
13005                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13006                            }
13007                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13008                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13009                                    |PackageManager.INSTALL_INTERNAL);
13010                        } else {
13011                            // Make sure the flag for installing on external
13012                            // media is unset
13013                            installFlags |= PackageManager.INSTALL_INTERNAL;
13014                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13015                        }
13016                    }
13017                }
13018            }
13019
13020            final InstallArgs args = createInstallArgs(this);
13021            mArgs = args;
13022
13023            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13024                // TODO: http://b/22976637
13025                // Apps installed for "all" users use the device owner to verify the app
13026                UserHandle verifierUser = getUser();
13027                if (verifierUser == UserHandle.ALL) {
13028                    verifierUser = UserHandle.SYSTEM;
13029                }
13030
13031                /*
13032                 * Determine if we have any installed package verifiers. If we
13033                 * do, then we'll defer to them to verify the packages.
13034                 */
13035                final int requiredUid = mRequiredVerifierPackage == null ? -1
13036                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13037                                verifierUser.getIdentifier());
13038                if (!origin.existing && requiredUid != -1
13039                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13040                    final Intent verification = new Intent(
13041                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13042                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13043                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13044                            PACKAGE_MIME_TYPE);
13045                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13046
13047                    // Query all live verifiers based on current user state
13048                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13049                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13050
13051                    if (DEBUG_VERIFY) {
13052                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13053                                + verification.toString() + " with " + pkgLite.verifiers.length
13054                                + " optional verifiers");
13055                    }
13056
13057                    final int verificationId = mPendingVerificationToken++;
13058
13059                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13060
13061                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13062                            installerPackageName);
13063
13064                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13065                            installFlags);
13066
13067                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13068                            pkgLite.packageName);
13069
13070                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13071                            pkgLite.versionCode);
13072
13073                    if (verificationInfo != null) {
13074                        if (verificationInfo.originatingUri != null) {
13075                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13076                                    verificationInfo.originatingUri);
13077                        }
13078                        if (verificationInfo.referrer != null) {
13079                            verification.putExtra(Intent.EXTRA_REFERRER,
13080                                    verificationInfo.referrer);
13081                        }
13082                        if (verificationInfo.originatingUid >= 0) {
13083                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13084                                    verificationInfo.originatingUid);
13085                        }
13086                        if (verificationInfo.installerUid >= 0) {
13087                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13088                                    verificationInfo.installerUid);
13089                        }
13090                    }
13091
13092                    final PackageVerificationState verificationState = new PackageVerificationState(
13093                            requiredUid, args);
13094
13095                    mPendingVerification.append(verificationId, verificationState);
13096
13097                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13098                            receivers, verificationState);
13099
13100                    /*
13101                     * If any sufficient verifiers were listed in the package
13102                     * manifest, attempt to ask them.
13103                     */
13104                    if (sufficientVerifiers != null) {
13105                        final int N = sufficientVerifiers.size();
13106                        if (N == 0) {
13107                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13108                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13109                        } else {
13110                            for (int i = 0; i < N; i++) {
13111                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13112
13113                                final Intent sufficientIntent = new Intent(verification);
13114                                sufficientIntent.setComponent(verifierComponent);
13115                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13116                            }
13117                        }
13118                    }
13119
13120                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13121                            mRequiredVerifierPackage, receivers);
13122                    if (ret == PackageManager.INSTALL_SUCCEEDED
13123                            && mRequiredVerifierPackage != null) {
13124                        Trace.asyncTraceBegin(
13125                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13126                        /*
13127                         * Send the intent to the required verification agent,
13128                         * but only start the verification timeout after the
13129                         * target BroadcastReceivers have run.
13130                         */
13131                        verification.setComponent(requiredVerifierComponent);
13132                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13133                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13134                                new BroadcastReceiver() {
13135                                    @Override
13136                                    public void onReceive(Context context, Intent intent) {
13137                                        final Message msg = mHandler
13138                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13139                                        msg.arg1 = verificationId;
13140                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13141                                    }
13142                                }, null, 0, null, null);
13143
13144                        /*
13145                         * We don't want the copy to proceed until verification
13146                         * succeeds, so null out this field.
13147                         */
13148                        mArgs = null;
13149                    }
13150                } else {
13151                    /*
13152                     * No package verification is enabled, so immediately start
13153                     * the remote call to initiate copy using temporary file.
13154                     */
13155                    ret = args.copyApk(mContainerService, true);
13156                }
13157            }
13158
13159            mRet = ret;
13160        }
13161
13162        @Override
13163        void handleReturnCode() {
13164            // If mArgs is null, then MCS couldn't be reached. When it
13165            // reconnects, it will try again to install. At that point, this
13166            // will succeed.
13167            if (mArgs != null) {
13168                processPendingInstall(mArgs, mRet);
13169            }
13170        }
13171
13172        @Override
13173        void handleServiceError() {
13174            mArgs = createInstallArgs(this);
13175            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13176        }
13177
13178        public boolean isForwardLocked() {
13179            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13180        }
13181    }
13182
13183    /**
13184     * Used during creation of InstallArgs
13185     *
13186     * @param installFlags package installation flags
13187     * @return true if should be installed on external storage
13188     */
13189    private static boolean installOnExternalAsec(int installFlags) {
13190        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13191            return false;
13192        }
13193        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13194            return true;
13195        }
13196        return false;
13197    }
13198
13199    /**
13200     * Used during creation of InstallArgs
13201     *
13202     * @param installFlags package installation flags
13203     * @return true if should be installed as forward locked
13204     */
13205    private static boolean installForwardLocked(int installFlags) {
13206        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13207    }
13208
13209    private InstallArgs createInstallArgs(InstallParams params) {
13210        if (params.move != null) {
13211            return new MoveInstallArgs(params);
13212        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13213            return new AsecInstallArgs(params);
13214        } else {
13215            return new FileInstallArgs(params);
13216        }
13217    }
13218
13219    /**
13220     * Create args that describe an existing installed package. Typically used
13221     * when cleaning up old installs, or used as a move source.
13222     */
13223    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13224            String resourcePath, String[] instructionSets) {
13225        final boolean isInAsec;
13226        if (installOnExternalAsec(installFlags)) {
13227            /* Apps on SD card are always in ASEC containers. */
13228            isInAsec = true;
13229        } else if (installForwardLocked(installFlags)
13230                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13231            /*
13232             * Forward-locked apps are only in ASEC containers if they're the
13233             * new style
13234             */
13235            isInAsec = true;
13236        } else {
13237            isInAsec = false;
13238        }
13239
13240        if (isInAsec) {
13241            return new AsecInstallArgs(codePath, instructionSets,
13242                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13243        } else {
13244            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13245        }
13246    }
13247
13248    static abstract class InstallArgs {
13249        /** @see InstallParams#origin */
13250        final OriginInfo origin;
13251        /** @see InstallParams#move */
13252        final MoveInfo move;
13253
13254        final IPackageInstallObserver2 observer;
13255        // Always refers to PackageManager flags only
13256        final int installFlags;
13257        final String installerPackageName;
13258        final String volumeUuid;
13259        final UserHandle user;
13260        final String abiOverride;
13261        final String[] installGrantPermissions;
13262        /** If non-null, drop an async trace when the install completes */
13263        final String traceMethod;
13264        final int traceCookie;
13265        final Certificate[][] certificates;
13266
13267        // The list of instruction sets supported by this app. This is currently
13268        // only used during the rmdex() phase to clean up resources. We can get rid of this
13269        // if we move dex files under the common app path.
13270        /* nullable */ String[] instructionSets;
13271
13272        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13273                int installFlags, String installerPackageName, String volumeUuid,
13274                UserHandle user, String[] instructionSets,
13275                String abiOverride, String[] installGrantPermissions,
13276                String traceMethod, int traceCookie, Certificate[][] certificates) {
13277            this.origin = origin;
13278            this.move = move;
13279            this.installFlags = installFlags;
13280            this.observer = observer;
13281            this.installerPackageName = installerPackageName;
13282            this.volumeUuid = volumeUuid;
13283            this.user = user;
13284            this.instructionSets = instructionSets;
13285            this.abiOverride = abiOverride;
13286            this.installGrantPermissions = installGrantPermissions;
13287            this.traceMethod = traceMethod;
13288            this.traceCookie = traceCookie;
13289            this.certificates = certificates;
13290        }
13291
13292        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13293        abstract int doPreInstall(int status);
13294
13295        /**
13296         * Rename package into final resting place. All paths on the given
13297         * scanned package should be updated to reflect the rename.
13298         */
13299        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13300        abstract int doPostInstall(int status, int uid);
13301
13302        /** @see PackageSettingBase#codePathString */
13303        abstract String getCodePath();
13304        /** @see PackageSettingBase#resourcePathString */
13305        abstract String getResourcePath();
13306
13307        // Need installer lock especially for dex file removal.
13308        abstract void cleanUpResourcesLI();
13309        abstract boolean doPostDeleteLI(boolean delete);
13310
13311        /**
13312         * Called before the source arguments are copied. This is used mostly
13313         * for MoveParams when it needs to read the source file to put it in the
13314         * destination.
13315         */
13316        int doPreCopy() {
13317            return PackageManager.INSTALL_SUCCEEDED;
13318        }
13319
13320        /**
13321         * Called after the source arguments are copied. This is used mostly for
13322         * MoveParams when it needs to read the source file to put it in the
13323         * destination.
13324         */
13325        int doPostCopy(int uid) {
13326            return PackageManager.INSTALL_SUCCEEDED;
13327        }
13328
13329        protected boolean isFwdLocked() {
13330            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13331        }
13332
13333        protected boolean isExternalAsec() {
13334            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13335        }
13336
13337        protected boolean isEphemeral() {
13338            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13339        }
13340
13341        UserHandle getUser() {
13342            return user;
13343        }
13344    }
13345
13346    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13347        if (!allCodePaths.isEmpty()) {
13348            if (instructionSets == null) {
13349                throw new IllegalStateException("instructionSet == null");
13350            }
13351            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13352            for (String codePath : allCodePaths) {
13353                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13354                    try {
13355                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13356                    } catch (InstallerException ignored) {
13357                    }
13358                }
13359            }
13360        }
13361    }
13362
13363    /**
13364     * Logic to handle installation of non-ASEC applications, including copying
13365     * and renaming logic.
13366     */
13367    class FileInstallArgs extends InstallArgs {
13368        private File codeFile;
13369        private File resourceFile;
13370
13371        // Example topology:
13372        // /data/app/com.example/base.apk
13373        // /data/app/com.example/split_foo.apk
13374        // /data/app/com.example/lib/arm/libfoo.so
13375        // /data/app/com.example/lib/arm64/libfoo.so
13376        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13377
13378        /** New install */
13379        FileInstallArgs(InstallParams params) {
13380            super(params.origin, params.move, params.observer, params.installFlags,
13381                    params.installerPackageName, params.volumeUuid,
13382                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13383                    params.grantedRuntimePermissions,
13384                    params.traceMethod, params.traceCookie, params.certificates);
13385            if (isFwdLocked()) {
13386                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13387            }
13388        }
13389
13390        /** Existing install */
13391        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13392            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13393                    null, null, null, 0, null /*certificates*/);
13394            this.codeFile = (codePath != null) ? new File(codePath) : null;
13395            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13396        }
13397
13398        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13399            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13400            try {
13401                return doCopyApk(imcs, temp);
13402            } finally {
13403                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13404            }
13405        }
13406
13407        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13408            if (origin.staged) {
13409                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13410                codeFile = origin.file;
13411                resourceFile = origin.file;
13412                return PackageManager.INSTALL_SUCCEEDED;
13413            }
13414
13415            try {
13416                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13417                final File tempDir =
13418                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13419                codeFile = tempDir;
13420                resourceFile = tempDir;
13421            } catch (IOException e) {
13422                Slog.w(TAG, "Failed to create copy file: " + e);
13423                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13424            }
13425
13426            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13427                @Override
13428                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13429                    if (!FileUtils.isValidExtFilename(name)) {
13430                        throw new IllegalArgumentException("Invalid filename: " + name);
13431                    }
13432                    try {
13433                        final File file = new File(codeFile, name);
13434                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13435                                O_RDWR | O_CREAT, 0644);
13436                        Os.chmod(file.getAbsolutePath(), 0644);
13437                        return new ParcelFileDescriptor(fd);
13438                    } catch (ErrnoException e) {
13439                        throw new RemoteException("Failed to open: " + e.getMessage());
13440                    }
13441                }
13442            };
13443
13444            int ret = PackageManager.INSTALL_SUCCEEDED;
13445            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13446            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13447                Slog.e(TAG, "Failed to copy package");
13448                return ret;
13449            }
13450
13451            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13452            NativeLibraryHelper.Handle handle = null;
13453            try {
13454                handle = NativeLibraryHelper.Handle.create(codeFile);
13455                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13456                        abiOverride);
13457            } catch (IOException e) {
13458                Slog.e(TAG, "Copying native libraries failed", e);
13459                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13460            } finally {
13461                IoUtils.closeQuietly(handle);
13462            }
13463
13464            return ret;
13465        }
13466
13467        int doPreInstall(int status) {
13468            if (status != PackageManager.INSTALL_SUCCEEDED) {
13469                cleanUp();
13470            }
13471            return status;
13472        }
13473
13474        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13475            if (status != PackageManager.INSTALL_SUCCEEDED) {
13476                cleanUp();
13477                return false;
13478            }
13479
13480            final File targetDir = codeFile.getParentFile();
13481            final File beforeCodeFile = codeFile;
13482            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13483
13484            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13485            try {
13486                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13487            } catch (ErrnoException e) {
13488                Slog.w(TAG, "Failed to rename", e);
13489                return false;
13490            }
13491
13492            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13493                Slog.w(TAG, "Failed to restorecon");
13494                return false;
13495            }
13496
13497            // Reflect the rename internally
13498            codeFile = afterCodeFile;
13499            resourceFile = afterCodeFile;
13500
13501            // Reflect the rename in scanned details
13502            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13503            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13504                    afterCodeFile, pkg.baseCodePath));
13505            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13506                    afterCodeFile, pkg.splitCodePaths));
13507
13508            // Reflect the rename in app info
13509            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13510            pkg.setApplicationInfoCodePath(pkg.codePath);
13511            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13512            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13513            pkg.setApplicationInfoResourcePath(pkg.codePath);
13514            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13515            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13516
13517            return true;
13518        }
13519
13520        int doPostInstall(int status, int uid) {
13521            if (status != PackageManager.INSTALL_SUCCEEDED) {
13522                cleanUp();
13523            }
13524            return status;
13525        }
13526
13527        @Override
13528        String getCodePath() {
13529            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13530        }
13531
13532        @Override
13533        String getResourcePath() {
13534            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13535        }
13536
13537        private boolean cleanUp() {
13538            if (codeFile == null || !codeFile.exists()) {
13539                return false;
13540            }
13541
13542            removeCodePathLI(codeFile);
13543
13544            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13545                resourceFile.delete();
13546            }
13547
13548            return true;
13549        }
13550
13551        void cleanUpResourcesLI() {
13552            // Try enumerating all code paths before deleting
13553            List<String> allCodePaths = Collections.EMPTY_LIST;
13554            if (codeFile != null && codeFile.exists()) {
13555                try {
13556                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13557                    allCodePaths = pkg.getAllCodePaths();
13558                } catch (PackageParserException e) {
13559                    // Ignored; we tried our best
13560                }
13561            }
13562
13563            cleanUp();
13564            removeDexFiles(allCodePaths, instructionSets);
13565        }
13566
13567        boolean doPostDeleteLI(boolean delete) {
13568            // XXX err, shouldn't we respect the delete flag?
13569            cleanUpResourcesLI();
13570            return true;
13571        }
13572    }
13573
13574    private boolean isAsecExternal(String cid) {
13575        final String asecPath = PackageHelper.getSdFilesystem(cid);
13576        return !asecPath.startsWith(mAsecInternalPath);
13577    }
13578
13579    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13580            PackageManagerException {
13581        if (copyRet < 0) {
13582            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13583                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13584                throw new PackageManagerException(copyRet, message);
13585            }
13586        }
13587    }
13588
13589    /**
13590     * Extract the MountService "container ID" from the full code path of an
13591     * .apk.
13592     */
13593    static String cidFromCodePath(String fullCodePath) {
13594        int eidx = fullCodePath.lastIndexOf("/");
13595        String subStr1 = fullCodePath.substring(0, eidx);
13596        int sidx = subStr1.lastIndexOf("/");
13597        return subStr1.substring(sidx+1, eidx);
13598    }
13599
13600    /**
13601     * Logic to handle installation of ASEC applications, including copying and
13602     * renaming logic.
13603     */
13604    class AsecInstallArgs extends InstallArgs {
13605        static final String RES_FILE_NAME = "pkg.apk";
13606        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13607
13608        String cid;
13609        String packagePath;
13610        String resourcePath;
13611
13612        /** New install */
13613        AsecInstallArgs(InstallParams params) {
13614            super(params.origin, params.move, params.observer, params.installFlags,
13615                    params.installerPackageName, params.volumeUuid,
13616                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13617                    params.grantedRuntimePermissions,
13618                    params.traceMethod, params.traceCookie, params.certificates);
13619        }
13620
13621        /** Existing install */
13622        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13623                        boolean isExternal, boolean isForwardLocked) {
13624            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13625              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13626                    instructionSets, null, null, null, 0, null /*certificates*/);
13627            // Hackily pretend we're still looking at a full code path
13628            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13629                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13630            }
13631
13632            // Extract cid from fullCodePath
13633            int eidx = fullCodePath.lastIndexOf("/");
13634            String subStr1 = fullCodePath.substring(0, eidx);
13635            int sidx = subStr1.lastIndexOf("/");
13636            cid = subStr1.substring(sidx+1, eidx);
13637            setMountPath(subStr1);
13638        }
13639
13640        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13641            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13642              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13643                    instructionSets, null, null, null, 0, null /*certificates*/);
13644            this.cid = cid;
13645            setMountPath(PackageHelper.getSdDir(cid));
13646        }
13647
13648        void createCopyFile() {
13649            cid = mInstallerService.allocateExternalStageCidLegacy();
13650        }
13651
13652        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13653            if (origin.staged && origin.cid != null) {
13654                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13655                cid = origin.cid;
13656                setMountPath(PackageHelper.getSdDir(cid));
13657                return PackageManager.INSTALL_SUCCEEDED;
13658            }
13659
13660            if (temp) {
13661                createCopyFile();
13662            } else {
13663                /*
13664                 * Pre-emptively destroy the container since it's destroyed if
13665                 * copying fails due to it existing anyway.
13666                 */
13667                PackageHelper.destroySdDir(cid);
13668            }
13669
13670            final String newMountPath = imcs.copyPackageToContainer(
13671                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13672                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13673
13674            if (newMountPath != null) {
13675                setMountPath(newMountPath);
13676                return PackageManager.INSTALL_SUCCEEDED;
13677            } else {
13678                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13679            }
13680        }
13681
13682        @Override
13683        String getCodePath() {
13684            return packagePath;
13685        }
13686
13687        @Override
13688        String getResourcePath() {
13689            return resourcePath;
13690        }
13691
13692        int doPreInstall(int status) {
13693            if (status != PackageManager.INSTALL_SUCCEEDED) {
13694                // Destroy container
13695                PackageHelper.destroySdDir(cid);
13696            } else {
13697                boolean mounted = PackageHelper.isContainerMounted(cid);
13698                if (!mounted) {
13699                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13700                            Process.SYSTEM_UID);
13701                    if (newMountPath != null) {
13702                        setMountPath(newMountPath);
13703                    } else {
13704                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13705                    }
13706                }
13707            }
13708            return status;
13709        }
13710
13711        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13712            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13713            String newMountPath = null;
13714            if (PackageHelper.isContainerMounted(cid)) {
13715                // Unmount the container
13716                if (!PackageHelper.unMountSdDir(cid)) {
13717                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13718                    return false;
13719                }
13720            }
13721            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13722                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13723                        " which might be stale. Will try to clean up.");
13724                // Clean up the stale container and proceed to recreate.
13725                if (!PackageHelper.destroySdDir(newCacheId)) {
13726                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13727                    return false;
13728                }
13729                // Successfully cleaned up stale container. Try to rename again.
13730                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13731                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13732                            + " inspite of cleaning it up.");
13733                    return false;
13734                }
13735            }
13736            if (!PackageHelper.isContainerMounted(newCacheId)) {
13737                Slog.w(TAG, "Mounting container " + newCacheId);
13738                newMountPath = PackageHelper.mountSdDir(newCacheId,
13739                        getEncryptKey(), Process.SYSTEM_UID);
13740            } else {
13741                newMountPath = PackageHelper.getSdDir(newCacheId);
13742            }
13743            if (newMountPath == null) {
13744                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13745                return false;
13746            }
13747            Log.i(TAG, "Succesfully renamed " + cid +
13748                    " to " + newCacheId +
13749                    " at new path: " + newMountPath);
13750            cid = newCacheId;
13751
13752            final File beforeCodeFile = new File(packagePath);
13753            setMountPath(newMountPath);
13754            final File afterCodeFile = new File(packagePath);
13755
13756            // Reflect the rename in scanned details
13757            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13758            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13759                    afterCodeFile, pkg.baseCodePath));
13760            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13761                    afterCodeFile, pkg.splitCodePaths));
13762
13763            // Reflect the rename in app info
13764            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13765            pkg.setApplicationInfoCodePath(pkg.codePath);
13766            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13767            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13768            pkg.setApplicationInfoResourcePath(pkg.codePath);
13769            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13770            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13771
13772            return true;
13773        }
13774
13775        private void setMountPath(String mountPath) {
13776            final File mountFile = new File(mountPath);
13777
13778            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13779            if (monolithicFile.exists()) {
13780                packagePath = monolithicFile.getAbsolutePath();
13781                if (isFwdLocked()) {
13782                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13783                } else {
13784                    resourcePath = packagePath;
13785                }
13786            } else {
13787                packagePath = mountFile.getAbsolutePath();
13788                resourcePath = packagePath;
13789            }
13790        }
13791
13792        int doPostInstall(int status, int uid) {
13793            if (status != PackageManager.INSTALL_SUCCEEDED) {
13794                cleanUp();
13795            } else {
13796                final int groupOwner;
13797                final String protectedFile;
13798                if (isFwdLocked()) {
13799                    groupOwner = UserHandle.getSharedAppGid(uid);
13800                    protectedFile = RES_FILE_NAME;
13801                } else {
13802                    groupOwner = -1;
13803                    protectedFile = null;
13804                }
13805
13806                if (uid < Process.FIRST_APPLICATION_UID
13807                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13808                    Slog.e(TAG, "Failed to finalize " + cid);
13809                    PackageHelper.destroySdDir(cid);
13810                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13811                }
13812
13813                boolean mounted = PackageHelper.isContainerMounted(cid);
13814                if (!mounted) {
13815                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13816                }
13817            }
13818            return status;
13819        }
13820
13821        private void cleanUp() {
13822            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13823
13824            // Destroy secure container
13825            PackageHelper.destroySdDir(cid);
13826        }
13827
13828        private List<String> getAllCodePaths() {
13829            final File codeFile = new File(getCodePath());
13830            if (codeFile != null && codeFile.exists()) {
13831                try {
13832                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13833                    return pkg.getAllCodePaths();
13834                } catch (PackageParserException e) {
13835                    // Ignored; we tried our best
13836                }
13837            }
13838            return Collections.EMPTY_LIST;
13839        }
13840
13841        void cleanUpResourcesLI() {
13842            // Enumerate all code paths before deleting
13843            cleanUpResourcesLI(getAllCodePaths());
13844        }
13845
13846        private void cleanUpResourcesLI(List<String> allCodePaths) {
13847            cleanUp();
13848            removeDexFiles(allCodePaths, instructionSets);
13849        }
13850
13851        String getPackageName() {
13852            return getAsecPackageName(cid);
13853        }
13854
13855        boolean doPostDeleteLI(boolean delete) {
13856            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13857            final List<String> allCodePaths = getAllCodePaths();
13858            boolean mounted = PackageHelper.isContainerMounted(cid);
13859            if (mounted) {
13860                // Unmount first
13861                if (PackageHelper.unMountSdDir(cid)) {
13862                    mounted = false;
13863                }
13864            }
13865            if (!mounted && delete) {
13866                cleanUpResourcesLI(allCodePaths);
13867            }
13868            return !mounted;
13869        }
13870
13871        @Override
13872        int doPreCopy() {
13873            if (isFwdLocked()) {
13874                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13875                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13876                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13877                }
13878            }
13879
13880            return PackageManager.INSTALL_SUCCEEDED;
13881        }
13882
13883        @Override
13884        int doPostCopy(int uid) {
13885            if (isFwdLocked()) {
13886                if (uid < Process.FIRST_APPLICATION_UID
13887                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13888                                RES_FILE_NAME)) {
13889                    Slog.e(TAG, "Failed to finalize " + cid);
13890                    PackageHelper.destroySdDir(cid);
13891                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13892                }
13893            }
13894
13895            return PackageManager.INSTALL_SUCCEEDED;
13896        }
13897    }
13898
13899    /**
13900     * Logic to handle movement of existing installed applications.
13901     */
13902    class MoveInstallArgs extends InstallArgs {
13903        private File codeFile;
13904        private File resourceFile;
13905
13906        /** New install */
13907        MoveInstallArgs(InstallParams params) {
13908            super(params.origin, params.move, params.observer, params.installFlags,
13909                    params.installerPackageName, params.volumeUuid,
13910                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13911                    params.grantedRuntimePermissions,
13912                    params.traceMethod, params.traceCookie, params.certificates);
13913        }
13914
13915        int copyApk(IMediaContainerService imcs, boolean temp) {
13916            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13917                    + move.fromUuid + " to " + move.toUuid);
13918            synchronized (mInstaller) {
13919                try {
13920                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13921                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13922                } catch (InstallerException e) {
13923                    Slog.w(TAG, "Failed to move app", e);
13924                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13925                }
13926            }
13927
13928            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13929            resourceFile = codeFile;
13930            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13931
13932            return PackageManager.INSTALL_SUCCEEDED;
13933        }
13934
13935        int doPreInstall(int status) {
13936            if (status != PackageManager.INSTALL_SUCCEEDED) {
13937                cleanUp(move.toUuid);
13938            }
13939            return status;
13940        }
13941
13942        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13943            if (status != PackageManager.INSTALL_SUCCEEDED) {
13944                cleanUp(move.toUuid);
13945                return false;
13946            }
13947
13948            // Reflect the move in app info
13949            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13950            pkg.setApplicationInfoCodePath(pkg.codePath);
13951            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13952            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13953            pkg.setApplicationInfoResourcePath(pkg.codePath);
13954            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13955            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13956
13957            return true;
13958        }
13959
13960        int doPostInstall(int status, int uid) {
13961            if (status == PackageManager.INSTALL_SUCCEEDED) {
13962                cleanUp(move.fromUuid);
13963            } else {
13964                cleanUp(move.toUuid);
13965            }
13966            return status;
13967        }
13968
13969        @Override
13970        String getCodePath() {
13971            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13972        }
13973
13974        @Override
13975        String getResourcePath() {
13976            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13977        }
13978
13979        private boolean cleanUp(String volumeUuid) {
13980            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13981                    move.dataAppName);
13982            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13983            final int[] userIds = sUserManager.getUserIds();
13984            synchronized (mInstallLock) {
13985                // Clean up both app data and code
13986                // All package moves are frozen until finished
13987                for (int userId : userIds) {
13988                    try {
13989                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13990                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13991                    } catch (InstallerException e) {
13992                        Slog.w(TAG, String.valueOf(e));
13993                    }
13994                }
13995                removeCodePathLI(codeFile);
13996            }
13997            return true;
13998        }
13999
14000        void cleanUpResourcesLI() {
14001            throw new UnsupportedOperationException();
14002        }
14003
14004        boolean doPostDeleteLI(boolean delete) {
14005            throw new UnsupportedOperationException();
14006        }
14007    }
14008
14009    static String getAsecPackageName(String packageCid) {
14010        int idx = packageCid.lastIndexOf("-");
14011        if (idx == -1) {
14012            return packageCid;
14013        }
14014        return packageCid.substring(0, idx);
14015    }
14016
14017    // Utility method used to create code paths based on package name and available index.
14018    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14019        String idxStr = "";
14020        int idx = 1;
14021        // Fall back to default value of idx=1 if prefix is not
14022        // part of oldCodePath
14023        if (oldCodePath != null) {
14024            String subStr = oldCodePath;
14025            // Drop the suffix right away
14026            if (suffix != null && subStr.endsWith(suffix)) {
14027                subStr = subStr.substring(0, subStr.length() - suffix.length());
14028            }
14029            // If oldCodePath already contains prefix find out the
14030            // ending index to either increment or decrement.
14031            int sidx = subStr.lastIndexOf(prefix);
14032            if (sidx != -1) {
14033                subStr = subStr.substring(sidx + prefix.length());
14034                if (subStr != null) {
14035                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14036                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14037                    }
14038                    try {
14039                        idx = Integer.parseInt(subStr);
14040                        if (idx <= 1) {
14041                            idx++;
14042                        } else {
14043                            idx--;
14044                        }
14045                    } catch(NumberFormatException e) {
14046                    }
14047                }
14048            }
14049        }
14050        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14051        return prefix + idxStr;
14052    }
14053
14054    private File getNextCodePath(File targetDir, String packageName) {
14055        int suffix = 1;
14056        File result;
14057        do {
14058            result = new File(targetDir, packageName + "-" + suffix);
14059            suffix++;
14060        } while (result.exists());
14061        return result;
14062    }
14063
14064    // Utility method that returns the relative package path with respect
14065    // to the installation directory. Like say for /data/data/com.test-1.apk
14066    // string com.test-1 is returned.
14067    static String deriveCodePathName(String codePath) {
14068        if (codePath == null) {
14069            return null;
14070        }
14071        final File codeFile = new File(codePath);
14072        final String name = codeFile.getName();
14073        if (codeFile.isDirectory()) {
14074            return name;
14075        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14076            final int lastDot = name.lastIndexOf('.');
14077            return name.substring(0, lastDot);
14078        } else {
14079            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14080            return null;
14081        }
14082    }
14083
14084    static class PackageInstalledInfo {
14085        String name;
14086        int uid;
14087        // The set of users that originally had this package installed.
14088        int[] origUsers;
14089        // The set of users that now have this package installed.
14090        int[] newUsers;
14091        PackageParser.Package pkg;
14092        int returnCode;
14093        String returnMsg;
14094        PackageRemovedInfo removedInfo;
14095        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14096
14097        public void setError(int code, String msg) {
14098            setReturnCode(code);
14099            setReturnMessage(msg);
14100            Slog.w(TAG, msg);
14101        }
14102
14103        public void setError(String msg, PackageParserException e) {
14104            setReturnCode(e.error);
14105            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14106            Slog.w(TAG, msg, e);
14107        }
14108
14109        public void setError(String msg, PackageManagerException e) {
14110            returnCode = e.error;
14111            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14112            Slog.w(TAG, msg, e);
14113        }
14114
14115        public void setReturnCode(int returnCode) {
14116            this.returnCode = returnCode;
14117            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14118            for (int i = 0; i < childCount; i++) {
14119                addedChildPackages.valueAt(i).returnCode = returnCode;
14120            }
14121        }
14122
14123        private void setReturnMessage(String returnMsg) {
14124            this.returnMsg = returnMsg;
14125            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14126            for (int i = 0; i < childCount; i++) {
14127                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14128            }
14129        }
14130
14131        // In some error cases we want to convey more info back to the observer
14132        String origPackage;
14133        String origPermission;
14134    }
14135
14136    /*
14137     * Install a non-existing package.
14138     */
14139    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14140            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14141            PackageInstalledInfo res) {
14142        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14143
14144        // Remember this for later, in case we need to rollback this install
14145        String pkgName = pkg.packageName;
14146
14147        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14148
14149        synchronized(mPackages) {
14150            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14151                // A package with the same name is already installed, though
14152                // it has been renamed to an older name.  The package we
14153                // are trying to install should be installed as an update to
14154                // the existing one, but that has not been requested, so bail.
14155                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14156                        + " without first uninstalling package running as "
14157                        + mSettings.mRenamedPackages.get(pkgName));
14158                return;
14159            }
14160            if (mPackages.containsKey(pkgName)) {
14161                // Don't allow installation over an existing package with the same name.
14162                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14163                        + " without first uninstalling.");
14164                return;
14165            }
14166        }
14167
14168        try {
14169            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14170                    System.currentTimeMillis(), user);
14171
14172            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14173
14174            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14175                prepareAppDataAfterInstallLIF(newPackage);
14176
14177            } else {
14178                // Remove package from internal structures, but keep around any
14179                // data that might have already existed
14180                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14181                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14182            }
14183        } catch (PackageManagerException e) {
14184            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14185        }
14186
14187        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14188    }
14189
14190    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14191        // Can't rotate keys during boot or if sharedUser.
14192        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14193                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14194            return false;
14195        }
14196        // app is using upgradeKeySets; make sure all are valid
14197        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14198        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14199        for (int i = 0; i < upgradeKeySets.length; i++) {
14200            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14201                Slog.wtf(TAG, "Package "
14202                         + (oldPs.name != null ? oldPs.name : "<null>")
14203                         + " contains upgrade-key-set reference to unknown key-set: "
14204                         + upgradeKeySets[i]
14205                         + " reverting to signatures check.");
14206                return false;
14207            }
14208        }
14209        return true;
14210    }
14211
14212    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14213        // Upgrade keysets are being used.  Determine if new package has a superset of the
14214        // required keys.
14215        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14216        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14217        for (int i = 0; i < upgradeKeySets.length; i++) {
14218            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14219            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14220                return true;
14221            }
14222        }
14223        return false;
14224    }
14225
14226    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14227        try (DigestInputStream digestStream =
14228                new DigestInputStream(new FileInputStream(file), digest)) {
14229            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14230        }
14231    }
14232
14233    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14234            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14235        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14236
14237        final PackageParser.Package oldPackage;
14238        final String pkgName = pkg.packageName;
14239        final int[] allUsers;
14240        final int[] installedUsers;
14241
14242        synchronized(mPackages) {
14243            oldPackage = mPackages.get(pkgName);
14244            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14245
14246            // don't allow upgrade to target a release SDK from a pre-release SDK
14247            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14248                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14249            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14250                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14251            if (oldTargetsPreRelease
14252                    && !newTargetsPreRelease
14253                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14254                Slog.w(TAG, "Can't install package targeting released sdk");
14255                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14256                return;
14257            }
14258
14259            // don't allow an upgrade from full to ephemeral
14260            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14261            if (isEphemeral && !oldIsEphemeral) {
14262                // can't downgrade from full to ephemeral
14263                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14264                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14265                return;
14266            }
14267
14268            // verify signatures are valid
14269            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14270            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14271                if (!checkUpgradeKeySetLP(ps, pkg)) {
14272                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14273                            "New package not signed by keys specified by upgrade-keysets: "
14274                                    + pkgName);
14275                    return;
14276                }
14277            } else {
14278                // default to original signature matching
14279                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14280                        != PackageManager.SIGNATURE_MATCH) {
14281                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14282                            "New package has a different signature: " + pkgName);
14283                    return;
14284                }
14285            }
14286
14287            // don't allow a system upgrade unless the upgrade hash matches
14288            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14289                byte[] digestBytes = null;
14290                try {
14291                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14292                    updateDigest(digest, new File(pkg.baseCodePath));
14293                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14294                        for (String path : pkg.splitCodePaths) {
14295                            updateDigest(digest, new File(path));
14296                        }
14297                    }
14298                    digestBytes = digest.digest();
14299                } catch (NoSuchAlgorithmException | IOException e) {
14300                    res.setError(INSTALL_FAILED_INVALID_APK,
14301                            "Could not compute hash: " + pkgName);
14302                    return;
14303                }
14304                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14305                    res.setError(INSTALL_FAILED_INVALID_APK,
14306                            "New package fails restrict-update check: " + pkgName);
14307                    return;
14308                }
14309                // retain upgrade restriction
14310                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14311            }
14312
14313            // Check for shared user id changes
14314            String invalidPackageName =
14315                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14316            if (invalidPackageName != null) {
14317                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14318                        "Package " + invalidPackageName + " tried to change user "
14319                                + oldPackage.mSharedUserId);
14320                return;
14321            }
14322
14323            // In case of rollback, remember per-user/profile install state
14324            allUsers = sUserManager.getUserIds();
14325            installedUsers = ps.queryInstalledUsers(allUsers, true);
14326        }
14327
14328        // Update what is removed
14329        res.removedInfo = new PackageRemovedInfo();
14330        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14331        res.removedInfo.removedPackage = oldPackage.packageName;
14332        res.removedInfo.isUpdate = true;
14333        res.removedInfo.origUsers = installedUsers;
14334        final int childCount = (oldPackage.childPackages != null)
14335                ? oldPackage.childPackages.size() : 0;
14336        for (int i = 0; i < childCount; i++) {
14337            boolean childPackageUpdated = false;
14338            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14339            if (res.addedChildPackages != null) {
14340                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14341                if (childRes != null) {
14342                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14343                    childRes.removedInfo.removedPackage = childPkg.packageName;
14344                    childRes.removedInfo.isUpdate = true;
14345                    childPackageUpdated = true;
14346                }
14347            }
14348            if (!childPackageUpdated) {
14349                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14350                childRemovedRes.removedPackage = childPkg.packageName;
14351                childRemovedRes.isUpdate = false;
14352                childRemovedRes.dataRemoved = true;
14353                synchronized (mPackages) {
14354                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14355                    if (childPs != null) {
14356                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14357                    }
14358                }
14359                if (res.removedInfo.removedChildPackages == null) {
14360                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14361                }
14362                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14363            }
14364        }
14365
14366        boolean sysPkg = (isSystemApp(oldPackage));
14367        if (sysPkg) {
14368            // Set the system/privileged flags as needed
14369            final boolean privileged =
14370                    (oldPackage.applicationInfo.privateFlags
14371                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14372            final int systemPolicyFlags = policyFlags
14373                    | PackageParser.PARSE_IS_SYSTEM
14374                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14375
14376            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14377                    user, allUsers, installerPackageName, res);
14378        } else {
14379            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14380                    user, allUsers, installerPackageName, res);
14381        }
14382    }
14383
14384    public List<String> getPreviousCodePaths(String packageName) {
14385        final PackageSetting ps = mSettings.mPackages.get(packageName);
14386        final List<String> result = new ArrayList<String>();
14387        if (ps != null && ps.oldCodePaths != null) {
14388            result.addAll(ps.oldCodePaths);
14389        }
14390        return result;
14391    }
14392
14393    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14394            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14395            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14396        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14397                + deletedPackage);
14398
14399        String pkgName = deletedPackage.packageName;
14400        boolean deletedPkg = true;
14401        boolean addedPkg = false;
14402        boolean updatedSettings = false;
14403        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14404        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14405                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14406
14407        final long origUpdateTime = (pkg.mExtras != null)
14408                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14409
14410        // First delete the existing package while retaining the data directory
14411        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14412                res.removedInfo, true, pkg)) {
14413            // If the existing package wasn't successfully deleted
14414            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14415            deletedPkg = false;
14416        } else {
14417            // Successfully deleted the old package; proceed with replace.
14418
14419            // If deleted package lived in a container, give users a chance to
14420            // relinquish resources before killing.
14421            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14422                if (DEBUG_INSTALL) {
14423                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14424                }
14425                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14426                final ArrayList<String> pkgList = new ArrayList<String>(1);
14427                pkgList.add(deletedPackage.applicationInfo.packageName);
14428                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14429            }
14430
14431            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14432                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14433            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14434
14435            try {
14436                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14437                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14438                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14439
14440                // Update the in-memory copy of the previous code paths.
14441                PackageSetting ps = mSettings.mPackages.get(pkgName);
14442                if (!killApp) {
14443                    if (ps.oldCodePaths == null) {
14444                        ps.oldCodePaths = new ArraySet<>();
14445                    }
14446                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14447                    if (deletedPackage.splitCodePaths != null) {
14448                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14449                    }
14450                } else {
14451                    ps.oldCodePaths = null;
14452                }
14453                if (ps.childPackageNames != null) {
14454                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14455                        final String childPkgName = ps.childPackageNames.get(i);
14456                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14457                        childPs.oldCodePaths = ps.oldCodePaths;
14458                    }
14459                }
14460                prepareAppDataAfterInstallLIF(newPackage);
14461                addedPkg = true;
14462            } catch (PackageManagerException e) {
14463                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14464            }
14465        }
14466
14467        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14468            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14469
14470            // Revert all internal state mutations and added folders for the failed install
14471            if (addedPkg) {
14472                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14473                        res.removedInfo, true, null);
14474            }
14475
14476            // Restore the old package
14477            if (deletedPkg) {
14478                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14479                File restoreFile = new File(deletedPackage.codePath);
14480                // Parse old package
14481                boolean oldExternal = isExternal(deletedPackage);
14482                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14483                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14484                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14485                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14486                try {
14487                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14488                            null);
14489                } catch (PackageManagerException e) {
14490                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14491                            + e.getMessage());
14492                    return;
14493                }
14494
14495                synchronized (mPackages) {
14496                    // Ensure the installer package name up to date
14497                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14498
14499                    // Update permissions for restored package
14500                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14501
14502                    mSettings.writeLPr();
14503                }
14504
14505                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14506            }
14507        } else {
14508            synchronized (mPackages) {
14509                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14510                if (ps != null) {
14511                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14512                    if (res.removedInfo.removedChildPackages != null) {
14513                        final int childCount = res.removedInfo.removedChildPackages.size();
14514                        // Iterate in reverse as we may modify the collection
14515                        for (int i = childCount - 1; i >= 0; i--) {
14516                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14517                            if (res.addedChildPackages.containsKey(childPackageName)) {
14518                                res.removedInfo.removedChildPackages.removeAt(i);
14519                            } else {
14520                                PackageRemovedInfo childInfo = res.removedInfo
14521                                        .removedChildPackages.valueAt(i);
14522                                childInfo.removedForAllUsers = mPackages.get(
14523                                        childInfo.removedPackage) == null;
14524                            }
14525                        }
14526                    }
14527                }
14528            }
14529        }
14530    }
14531
14532    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14533            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14534            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14535        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14536                + ", old=" + deletedPackage);
14537
14538        final boolean disabledSystem;
14539
14540        // Remove existing system package
14541        removePackageLI(deletedPackage, true);
14542
14543        synchronized (mPackages) {
14544            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14545        }
14546        if (!disabledSystem) {
14547            // We didn't need to disable the .apk as a current system package,
14548            // which means we are replacing another update that is already
14549            // installed.  We need to make sure to delete the older one's .apk.
14550            res.removedInfo.args = createInstallArgsForExisting(0,
14551                    deletedPackage.applicationInfo.getCodePath(),
14552                    deletedPackage.applicationInfo.getResourcePath(),
14553                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14554        } else {
14555            res.removedInfo.args = null;
14556        }
14557
14558        // Successfully disabled the old package. Now proceed with re-installation
14559        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14560                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14561        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14562
14563        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14564        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14565                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14566
14567        PackageParser.Package newPackage = null;
14568        try {
14569            // Add the package to the internal data structures
14570            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14571
14572            // Set the update and install times
14573            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14574            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14575                    System.currentTimeMillis());
14576
14577            // Update the package dynamic state if succeeded
14578            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14579                // Now that the install succeeded make sure we remove data
14580                // directories for any child package the update removed.
14581                final int deletedChildCount = (deletedPackage.childPackages != null)
14582                        ? deletedPackage.childPackages.size() : 0;
14583                final int newChildCount = (newPackage.childPackages != null)
14584                        ? newPackage.childPackages.size() : 0;
14585                for (int i = 0; i < deletedChildCount; i++) {
14586                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14587                    boolean childPackageDeleted = true;
14588                    for (int j = 0; j < newChildCount; j++) {
14589                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14590                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14591                            childPackageDeleted = false;
14592                            break;
14593                        }
14594                    }
14595                    if (childPackageDeleted) {
14596                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14597                                deletedChildPkg.packageName);
14598                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14599                            PackageRemovedInfo removedChildRes = res.removedInfo
14600                                    .removedChildPackages.get(deletedChildPkg.packageName);
14601                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14602                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14603                        }
14604                    }
14605                }
14606
14607                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14608                prepareAppDataAfterInstallLIF(newPackage);
14609            }
14610        } catch (PackageManagerException e) {
14611            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14612            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14613        }
14614
14615        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14616            // Re installation failed. Restore old information
14617            // Remove new pkg information
14618            if (newPackage != null) {
14619                removeInstalledPackageLI(newPackage, true);
14620            }
14621            // Add back the old system package
14622            try {
14623                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14624            } catch (PackageManagerException e) {
14625                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14626            }
14627
14628            synchronized (mPackages) {
14629                if (disabledSystem) {
14630                    enableSystemPackageLPw(deletedPackage);
14631                }
14632
14633                // Ensure the installer package name up to date
14634                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14635
14636                // Update permissions for restored package
14637                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14638
14639                mSettings.writeLPr();
14640            }
14641
14642            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14643                    + " after failed upgrade");
14644        }
14645    }
14646
14647    /**
14648     * Checks whether the parent or any of the child packages have a change shared
14649     * user. For a package to be a valid update the shred users of the parent and
14650     * the children should match. We may later support changing child shared users.
14651     * @param oldPkg The updated package.
14652     * @param newPkg The update package.
14653     * @return The shared user that change between the versions.
14654     */
14655    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14656            PackageParser.Package newPkg) {
14657        // Check parent shared user
14658        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14659            return newPkg.packageName;
14660        }
14661        // Check child shared users
14662        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14663        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14664        for (int i = 0; i < newChildCount; i++) {
14665            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14666            // If this child was present, did it have the same shared user?
14667            for (int j = 0; j < oldChildCount; j++) {
14668                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14669                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14670                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14671                    return newChildPkg.packageName;
14672                }
14673            }
14674        }
14675        return null;
14676    }
14677
14678    private void removeNativeBinariesLI(PackageSetting ps) {
14679        // Remove the lib path for the parent package
14680        if (ps != null) {
14681            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14682            // Remove the lib path for the child packages
14683            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14684            for (int i = 0; i < childCount; i++) {
14685                PackageSetting childPs = null;
14686                synchronized (mPackages) {
14687                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14688                }
14689                if (childPs != null) {
14690                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14691                            .legacyNativeLibraryPathString);
14692                }
14693            }
14694        }
14695    }
14696
14697    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14698        // Enable the parent package
14699        mSettings.enableSystemPackageLPw(pkg.packageName);
14700        // Enable the child packages
14701        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14702        for (int i = 0; i < childCount; i++) {
14703            PackageParser.Package childPkg = pkg.childPackages.get(i);
14704            mSettings.enableSystemPackageLPw(childPkg.packageName);
14705        }
14706    }
14707
14708    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14709            PackageParser.Package newPkg) {
14710        // Disable the parent package (parent always replaced)
14711        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14712        // Disable the child packages
14713        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14714        for (int i = 0; i < childCount; i++) {
14715            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14716            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14717            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14718        }
14719        return disabled;
14720    }
14721
14722    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14723            String installerPackageName) {
14724        // Enable the parent package
14725        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14726        // Enable the child packages
14727        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14728        for (int i = 0; i < childCount; i++) {
14729            PackageParser.Package childPkg = pkg.childPackages.get(i);
14730            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14731        }
14732    }
14733
14734    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14735        // Collect all used permissions in the UID
14736        ArraySet<String> usedPermissions = new ArraySet<>();
14737        final int packageCount = su.packages.size();
14738        for (int i = 0; i < packageCount; i++) {
14739            PackageSetting ps = su.packages.valueAt(i);
14740            if (ps.pkg == null) {
14741                continue;
14742            }
14743            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14744            for (int j = 0; j < requestedPermCount; j++) {
14745                String permission = ps.pkg.requestedPermissions.get(j);
14746                BasePermission bp = mSettings.mPermissions.get(permission);
14747                if (bp != null) {
14748                    usedPermissions.add(permission);
14749                }
14750            }
14751        }
14752
14753        PermissionsState permissionsState = su.getPermissionsState();
14754        // Prune install permissions
14755        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14756        final int installPermCount = installPermStates.size();
14757        for (int i = installPermCount - 1; i >= 0;  i--) {
14758            PermissionState permissionState = installPermStates.get(i);
14759            if (!usedPermissions.contains(permissionState.getName())) {
14760                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14761                if (bp != null) {
14762                    permissionsState.revokeInstallPermission(bp);
14763                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14764                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14765                }
14766            }
14767        }
14768
14769        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14770
14771        // Prune runtime permissions
14772        for (int userId : allUserIds) {
14773            List<PermissionState> runtimePermStates = permissionsState
14774                    .getRuntimePermissionStates(userId);
14775            final int runtimePermCount = runtimePermStates.size();
14776            for (int i = runtimePermCount - 1; i >= 0; i--) {
14777                PermissionState permissionState = runtimePermStates.get(i);
14778                if (!usedPermissions.contains(permissionState.getName())) {
14779                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14780                    if (bp != null) {
14781                        permissionsState.revokeRuntimePermission(bp, userId);
14782                        permissionsState.updatePermissionFlags(bp, userId,
14783                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14784                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14785                                runtimePermissionChangedUserIds, userId);
14786                    }
14787                }
14788            }
14789        }
14790
14791        return runtimePermissionChangedUserIds;
14792    }
14793
14794    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14795            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14796        // Update the parent package setting
14797        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14798                res, user);
14799        // Update the child packages setting
14800        final int childCount = (newPackage.childPackages != null)
14801                ? newPackage.childPackages.size() : 0;
14802        for (int i = 0; i < childCount; i++) {
14803            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14804            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14805            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14806                    childRes.origUsers, childRes, user);
14807        }
14808    }
14809
14810    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14811            String installerPackageName, int[] allUsers, int[] installedForUsers,
14812            PackageInstalledInfo res, UserHandle user) {
14813        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14814
14815        String pkgName = newPackage.packageName;
14816        synchronized (mPackages) {
14817            //write settings. the installStatus will be incomplete at this stage.
14818            //note that the new package setting would have already been
14819            //added to mPackages. It hasn't been persisted yet.
14820            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14821            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14822            mSettings.writeLPr();
14823            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14824        }
14825
14826        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14827        synchronized (mPackages) {
14828            updatePermissionsLPw(newPackage.packageName, newPackage,
14829                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14830                            ? UPDATE_PERMISSIONS_ALL : 0));
14831            // For system-bundled packages, we assume that installing an upgraded version
14832            // of the package implies that the user actually wants to run that new code,
14833            // so we enable the package.
14834            PackageSetting ps = mSettings.mPackages.get(pkgName);
14835            final int userId = user.getIdentifier();
14836            if (ps != null) {
14837                if (isSystemApp(newPackage)) {
14838                    if (DEBUG_INSTALL) {
14839                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14840                    }
14841                    // Enable system package for requested users
14842                    if (res.origUsers != null) {
14843                        for (int origUserId : res.origUsers) {
14844                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14845                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14846                                        origUserId, installerPackageName);
14847                            }
14848                        }
14849                    }
14850                    // Also convey the prior install/uninstall state
14851                    if (allUsers != null && installedForUsers != null) {
14852                        for (int currentUserId : allUsers) {
14853                            final boolean installed = ArrayUtils.contains(
14854                                    installedForUsers, currentUserId);
14855                            if (DEBUG_INSTALL) {
14856                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14857                            }
14858                            ps.setInstalled(installed, currentUserId);
14859                        }
14860                        // these install state changes will be persisted in the
14861                        // upcoming call to mSettings.writeLPr().
14862                    }
14863                }
14864                // It's implied that when a user requests installation, they want the app to be
14865                // installed and enabled.
14866                if (userId != UserHandle.USER_ALL) {
14867                    ps.setInstalled(true, userId);
14868                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14869                }
14870            }
14871            res.name = pkgName;
14872            res.uid = newPackage.applicationInfo.uid;
14873            res.pkg = newPackage;
14874            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14875            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14876            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14877            //to update install status
14878            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14879            mSettings.writeLPr();
14880            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14881        }
14882
14883        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14884    }
14885
14886    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14887        try {
14888            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14889            installPackageLI(args, res);
14890        } finally {
14891            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14892        }
14893    }
14894
14895    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14896        final int installFlags = args.installFlags;
14897        final String installerPackageName = args.installerPackageName;
14898        final String volumeUuid = args.volumeUuid;
14899        final File tmpPackageFile = new File(args.getCodePath());
14900        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14901        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14902                || (args.volumeUuid != null));
14903        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14904        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14905        boolean replace = false;
14906        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14907        if (args.move != null) {
14908            // moving a complete application; perform an initial scan on the new install location
14909            scanFlags |= SCAN_INITIAL;
14910        }
14911        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14912            scanFlags |= SCAN_DONT_KILL_APP;
14913        }
14914
14915        // Result object to be returned
14916        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14917
14918        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14919
14920        // Sanity check
14921        if (ephemeral && (forwardLocked || onExternal)) {
14922            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14923                    + " external=" + onExternal);
14924            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14925            return;
14926        }
14927
14928        // Retrieve PackageSettings and parse package
14929        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14930                | PackageParser.PARSE_ENFORCE_CODE
14931                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14932                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14933                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14934                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14935        PackageParser pp = new PackageParser();
14936        pp.setSeparateProcesses(mSeparateProcesses);
14937        pp.setDisplayMetrics(mMetrics);
14938
14939        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14940        final PackageParser.Package pkg;
14941        try {
14942            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14943        } catch (PackageParserException e) {
14944            res.setError("Failed parse during installPackageLI", e);
14945            return;
14946        } finally {
14947            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14948        }
14949
14950        // If we are installing a clustered package add results for the children
14951        if (pkg.childPackages != null) {
14952            synchronized (mPackages) {
14953                final int childCount = pkg.childPackages.size();
14954                for (int i = 0; i < childCount; i++) {
14955                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14956                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14957                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14958                    childRes.pkg = childPkg;
14959                    childRes.name = childPkg.packageName;
14960                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14961                    if (childPs != null) {
14962                        childRes.origUsers = childPs.queryInstalledUsers(
14963                                sUserManager.getUserIds(), true);
14964                    }
14965                    if ((mPackages.containsKey(childPkg.packageName))) {
14966                        childRes.removedInfo = new PackageRemovedInfo();
14967                        childRes.removedInfo.removedPackage = childPkg.packageName;
14968                    }
14969                    if (res.addedChildPackages == null) {
14970                        res.addedChildPackages = new ArrayMap<>();
14971                    }
14972                    res.addedChildPackages.put(childPkg.packageName, childRes);
14973                }
14974            }
14975        }
14976
14977        // If package doesn't declare API override, mark that we have an install
14978        // time CPU ABI override.
14979        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14980            pkg.cpuAbiOverride = args.abiOverride;
14981        }
14982
14983        String pkgName = res.name = pkg.packageName;
14984        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14985            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14986                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14987                return;
14988            }
14989        }
14990
14991        try {
14992            // either use what we've been given or parse directly from the APK
14993            if (args.certificates != null) {
14994                try {
14995                    PackageParser.populateCertificates(pkg, args.certificates);
14996                } catch (PackageParserException e) {
14997                    // there was something wrong with the certificates we were given;
14998                    // try to pull them from the APK
14999                    PackageParser.collectCertificates(pkg, parseFlags);
15000                }
15001            } else {
15002                PackageParser.collectCertificates(pkg, parseFlags);
15003            }
15004        } catch (PackageParserException e) {
15005            res.setError("Failed collect during installPackageLI", e);
15006            return;
15007        }
15008
15009        // Get rid of all references to package scan path via parser.
15010        pp = null;
15011        String oldCodePath = null;
15012        boolean systemApp = false;
15013        synchronized (mPackages) {
15014            // Check if installing already existing package
15015            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15016                String oldName = mSettings.mRenamedPackages.get(pkgName);
15017                if (pkg.mOriginalPackages != null
15018                        && pkg.mOriginalPackages.contains(oldName)
15019                        && mPackages.containsKey(oldName)) {
15020                    // This package is derived from an original package,
15021                    // and this device has been updating from that original
15022                    // name.  We must continue using the original name, so
15023                    // rename the new package here.
15024                    pkg.setPackageName(oldName);
15025                    pkgName = pkg.packageName;
15026                    replace = true;
15027                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15028                            + oldName + " pkgName=" + pkgName);
15029                } else if (mPackages.containsKey(pkgName)) {
15030                    // This package, under its official name, already exists
15031                    // on the device; we should replace it.
15032                    replace = true;
15033                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15034                }
15035
15036                // Child packages are installed through the parent package
15037                if (pkg.parentPackage != null) {
15038                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15039                            "Package " + pkg.packageName + " is child of package "
15040                                    + pkg.parentPackage.parentPackage + ". Child packages "
15041                                    + "can be updated only through the parent package.");
15042                    return;
15043                }
15044
15045                if (replace) {
15046                    // Prevent apps opting out from runtime permissions
15047                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15048                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15049                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15050                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15051                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15052                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15053                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15054                                        + " doesn't support runtime permissions but the old"
15055                                        + " target SDK " + oldTargetSdk + " does.");
15056                        return;
15057                    }
15058
15059                    // Prevent installing of child packages
15060                    if (oldPackage.parentPackage != null) {
15061                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15062                                "Package " + pkg.packageName + " is child of package "
15063                                        + oldPackage.parentPackage + ". Child packages "
15064                                        + "can be updated only through the parent package.");
15065                        return;
15066                    }
15067                }
15068            }
15069
15070            PackageSetting ps = mSettings.mPackages.get(pkgName);
15071            if (ps != null) {
15072                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15073
15074                // Quick sanity check that we're signed correctly if updating;
15075                // we'll check this again later when scanning, but we want to
15076                // bail early here before tripping over redefined permissions.
15077                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15078                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15079                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15080                                + pkg.packageName + " upgrade keys do not match the "
15081                                + "previously installed version");
15082                        return;
15083                    }
15084                } else {
15085                    try {
15086                        verifySignaturesLP(ps, pkg);
15087                    } catch (PackageManagerException e) {
15088                        res.setError(e.error, e.getMessage());
15089                        return;
15090                    }
15091                }
15092
15093                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15094                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15095                    systemApp = (ps.pkg.applicationInfo.flags &
15096                            ApplicationInfo.FLAG_SYSTEM) != 0;
15097                }
15098                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15099            }
15100
15101            // Check whether the newly-scanned package wants to define an already-defined perm
15102            int N = pkg.permissions.size();
15103            for (int i = N-1; i >= 0; i--) {
15104                PackageParser.Permission perm = pkg.permissions.get(i);
15105                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15106                if (bp != null) {
15107                    // If the defining package is signed with our cert, it's okay.  This
15108                    // also includes the "updating the same package" case, of course.
15109                    // "updating same package" could also involve key-rotation.
15110                    final boolean sigsOk;
15111                    if (bp.sourcePackage.equals(pkg.packageName)
15112                            && (bp.packageSetting instanceof PackageSetting)
15113                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15114                                    scanFlags))) {
15115                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15116                    } else {
15117                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15118                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15119                    }
15120                    if (!sigsOk) {
15121                        // If the owning package is the system itself, we log but allow
15122                        // install to proceed; we fail the install on all other permission
15123                        // redefinitions.
15124                        if (!bp.sourcePackage.equals("android")) {
15125                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15126                                    + pkg.packageName + " attempting to redeclare permission "
15127                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15128                            res.origPermission = perm.info.name;
15129                            res.origPackage = bp.sourcePackage;
15130                            return;
15131                        } else {
15132                            Slog.w(TAG, "Package " + pkg.packageName
15133                                    + " attempting to redeclare system permission "
15134                                    + perm.info.name + "; ignoring new declaration");
15135                            pkg.permissions.remove(i);
15136                        }
15137                    }
15138                }
15139            }
15140        }
15141
15142        if (systemApp) {
15143            if (onExternal) {
15144                // Abort update; system app can't be replaced with app on sdcard
15145                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15146                        "Cannot install updates to system apps on sdcard");
15147                return;
15148            } else if (ephemeral) {
15149                // Abort update; system app can't be replaced with an ephemeral app
15150                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15151                        "Cannot update a system app with an ephemeral app");
15152                return;
15153            }
15154        }
15155
15156        if (args.move != null) {
15157            // We did an in-place move, so dex is ready to roll
15158            scanFlags |= SCAN_NO_DEX;
15159            scanFlags |= SCAN_MOVE;
15160
15161            synchronized (mPackages) {
15162                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15163                if (ps == null) {
15164                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15165                            "Missing settings for moved package " + pkgName);
15166                }
15167
15168                // We moved the entire application as-is, so bring over the
15169                // previously derived ABI information.
15170                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15171                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15172            }
15173
15174        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15175            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15176            scanFlags |= SCAN_NO_DEX;
15177
15178            try {
15179                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15180                    args.abiOverride : pkg.cpuAbiOverride);
15181                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15182                        true /* extract libs */);
15183            } catch (PackageManagerException pme) {
15184                Slog.e(TAG, "Error deriving application ABI", pme);
15185                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15186                return;
15187            }
15188
15189            // Shared libraries for the package need to be updated.
15190            synchronized (mPackages) {
15191                try {
15192                    updateSharedLibrariesLPw(pkg, null);
15193                } catch (PackageManagerException e) {
15194                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15195                }
15196            }
15197            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15198            // Do not run PackageDexOptimizer through the local performDexOpt
15199            // method because `pkg` may not be in `mPackages` yet.
15200            //
15201            // Also, don't fail application installs if the dexopt step fails.
15202            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15203                    null /* instructionSets */, false /* checkProfiles */,
15204                    getCompilerFilterForReason(REASON_INSTALL),
15205                    getOrCreateCompilerPackageStats(pkg));
15206            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15207
15208            // Notify BackgroundDexOptService that the package has been changed.
15209            // If this is an update of a package which used to fail to compile,
15210            // BDOS will remove it from its blacklist.
15211            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15212        }
15213
15214        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15215            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15216            return;
15217        }
15218
15219        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15220
15221        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15222                "installPackageLI")) {
15223            if (replace) {
15224                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15225                        installerPackageName, res);
15226            } else {
15227                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15228                        args.user, installerPackageName, volumeUuid, res);
15229            }
15230        }
15231        synchronized (mPackages) {
15232            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15233            if (ps != null) {
15234                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15235            }
15236
15237            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15238            for (int i = 0; i < childCount; i++) {
15239                PackageParser.Package childPkg = pkg.childPackages.get(i);
15240                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15241                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15242                if (childPs != null) {
15243                    childRes.newUsers = childPs.queryInstalledUsers(
15244                            sUserManager.getUserIds(), true);
15245                }
15246            }
15247        }
15248    }
15249
15250    private void startIntentFilterVerifications(int userId, boolean replacing,
15251            PackageParser.Package pkg) {
15252        if (mIntentFilterVerifierComponent == null) {
15253            Slog.w(TAG, "No IntentFilter verification will not be done as "
15254                    + "there is no IntentFilterVerifier available!");
15255            return;
15256        }
15257
15258        final int verifierUid = getPackageUid(
15259                mIntentFilterVerifierComponent.getPackageName(),
15260                MATCH_DEBUG_TRIAGED_MISSING,
15261                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15262
15263        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15264        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15265        mHandler.sendMessage(msg);
15266
15267        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15268        for (int i = 0; i < childCount; i++) {
15269            PackageParser.Package childPkg = pkg.childPackages.get(i);
15270            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15271            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15272            mHandler.sendMessage(msg);
15273        }
15274    }
15275
15276    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15277            PackageParser.Package pkg) {
15278        int size = pkg.activities.size();
15279        if (size == 0) {
15280            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15281                    "No activity, so no need to verify any IntentFilter!");
15282            return;
15283        }
15284
15285        final boolean hasDomainURLs = hasDomainURLs(pkg);
15286        if (!hasDomainURLs) {
15287            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15288                    "No domain URLs, so no need to verify any IntentFilter!");
15289            return;
15290        }
15291
15292        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15293                + " if any IntentFilter from the " + size
15294                + " Activities needs verification ...");
15295
15296        int count = 0;
15297        final String packageName = pkg.packageName;
15298
15299        synchronized (mPackages) {
15300            // If this is a new install and we see that we've already run verification for this
15301            // package, we have nothing to do: it means the state was restored from backup.
15302            if (!replacing) {
15303                IntentFilterVerificationInfo ivi =
15304                        mSettings.getIntentFilterVerificationLPr(packageName);
15305                if (ivi != null) {
15306                    if (DEBUG_DOMAIN_VERIFICATION) {
15307                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15308                                + ivi.getStatusString());
15309                    }
15310                    return;
15311                }
15312            }
15313
15314            // If any filters need to be verified, then all need to be.
15315            boolean needToVerify = false;
15316            for (PackageParser.Activity a : pkg.activities) {
15317                for (ActivityIntentInfo filter : a.intents) {
15318                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15319                        if (DEBUG_DOMAIN_VERIFICATION) {
15320                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15321                        }
15322                        needToVerify = true;
15323                        break;
15324                    }
15325                }
15326            }
15327
15328            if (needToVerify) {
15329                final int verificationId = mIntentFilterVerificationToken++;
15330                for (PackageParser.Activity a : pkg.activities) {
15331                    for (ActivityIntentInfo filter : a.intents) {
15332                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15333                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15334                                    "Verification needed for IntentFilter:" + filter.toString());
15335                            mIntentFilterVerifier.addOneIntentFilterVerification(
15336                                    verifierUid, userId, verificationId, filter, packageName);
15337                            count++;
15338                        }
15339                    }
15340                }
15341            }
15342        }
15343
15344        if (count > 0) {
15345            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15346                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15347                    +  " for userId:" + userId);
15348            mIntentFilterVerifier.startVerifications(userId);
15349        } else {
15350            if (DEBUG_DOMAIN_VERIFICATION) {
15351                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15352            }
15353        }
15354    }
15355
15356    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15357        final ComponentName cn  = filter.activity.getComponentName();
15358        final String packageName = cn.getPackageName();
15359
15360        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15361                packageName);
15362        if (ivi == null) {
15363            return true;
15364        }
15365        int status = ivi.getStatus();
15366        switch (status) {
15367            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15368            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15369                return true;
15370
15371            default:
15372                // Nothing to do
15373                return false;
15374        }
15375    }
15376
15377    private static boolean isMultiArch(ApplicationInfo info) {
15378        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15379    }
15380
15381    private static boolean isExternal(PackageParser.Package pkg) {
15382        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15383    }
15384
15385    private static boolean isExternal(PackageSetting ps) {
15386        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15387    }
15388
15389    private static boolean isEphemeral(PackageParser.Package pkg) {
15390        return pkg.applicationInfo.isEphemeralApp();
15391    }
15392
15393    private static boolean isEphemeral(PackageSetting ps) {
15394        return ps.pkg != null && isEphemeral(ps.pkg);
15395    }
15396
15397    private static boolean isSystemApp(PackageParser.Package pkg) {
15398        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15399    }
15400
15401    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15402        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15403    }
15404
15405    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15406        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15407    }
15408
15409    private static boolean isSystemApp(PackageSetting ps) {
15410        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15411    }
15412
15413    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15414        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15415    }
15416
15417    private int packageFlagsToInstallFlags(PackageSetting ps) {
15418        int installFlags = 0;
15419        if (isEphemeral(ps)) {
15420            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15421        }
15422        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15423            // This existing package was an external ASEC install when we have
15424            // the external flag without a UUID
15425            installFlags |= PackageManager.INSTALL_EXTERNAL;
15426        }
15427        if (ps.isForwardLocked()) {
15428            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15429        }
15430        return installFlags;
15431    }
15432
15433    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15434        if (isExternal(pkg)) {
15435            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15436                return StorageManager.UUID_PRIMARY_PHYSICAL;
15437            } else {
15438                return pkg.volumeUuid;
15439            }
15440        } else {
15441            return StorageManager.UUID_PRIVATE_INTERNAL;
15442        }
15443    }
15444
15445    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15446        if (isExternal(pkg)) {
15447            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15448                return mSettings.getExternalVersion();
15449            } else {
15450                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15451            }
15452        } else {
15453            return mSettings.getInternalVersion();
15454        }
15455    }
15456
15457    private void deleteTempPackageFiles() {
15458        final FilenameFilter filter = new FilenameFilter() {
15459            public boolean accept(File dir, String name) {
15460                return name.startsWith("vmdl") && name.endsWith(".tmp");
15461            }
15462        };
15463        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15464            file.delete();
15465        }
15466    }
15467
15468    @Override
15469    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15470            int flags) {
15471        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15472                flags);
15473    }
15474
15475    @Override
15476    public void deletePackage(final String packageName,
15477            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15478        mContext.enforceCallingOrSelfPermission(
15479                android.Manifest.permission.DELETE_PACKAGES, null);
15480        Preconditions.checkNotNull(packageName);
15481        Preconditions.checkNotNull(observer);
15482        final int uid = Binder.getCallingUid();
15483        if (!isOrphaned(packageName)
15484                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15485            try {
15486                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15487                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15488                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15489                observer.onUserActionRequired(intent);
15490            } catch (RemoteException re) {
15491            }
15492            return;
15493        }
15494        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15495        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15496        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15497            mContext.enforceCallingOrSelfPermission(
15498                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15499                    "deletePackage for user " + userId);
15500        }
15501
15502        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15503            try {
15504                observer.onPackageDeleted(packageName,
15505                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15506            } catch (RemoteException re) {
15507            }
15508            return;
15509        }
15510
15511        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15512            try {
15513                observer.onPackageDeleted(packageName,
15514                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15515            } catch (RemoteException re) {
15516            }
15517            return;
15518        }
15519
15520        if (DEBUG_REMOVE) {
15521            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15522                    + " deleteAllUsers: " + deleteAllUsers );
15523        }
15524        // Queue up an async operation since the package deletion may take a little while.
15525        mHandler.post(new Runnable() {
15526            public void run() {
15527                mHandler.removeCallbacks(this);
15528                int returnCode;
15529                if (!deleteAllUsers) {
15530                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15531                } else {
15532                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15533                    // If nobody is blocking uninstall, proceed with delete for all users
15534                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15535                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15536                    } else {
15537                        // Otherwise uninstall individually for users with blockUninstalls=false
15538                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15539                        for (int userId : users) {
15540                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15541                                returnCode = deletePackageX(packageName, userId, userFlags);
15542                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15543                                    Slog.w(TAG, "Package delete failed for user " + userId
15544                                            + ", returnCode " + returnCode);
15545                                }
15546                            }
15547                        }
15548                        // The app has only been marked uninstalled for certain users.
15549                        // We still need to report that delete was blocked
15550                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15551                    }
15552                }
15553                try {
15554                    observer.onPackageDeleted(packageName, returnCode, null);
15555                } catch (RemoteException e) {
15556                    Log.i(TAG, "Observer no longer exists.");
15557                } //end catch
15558            } //end run
15559        });
15560    }
15561
15562    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15563        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15564              || callingUid == Process.SYSTEM_UID) {
15565            return true;
15566        }
15567        final int callingUserId = UserHandle.getUserId(callingUid);
15568        // If the caller installed the pkgName, then allow it to silently uninstall.
15569        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15570            return true;
15571        }
15572
15573        // Allow package verifier to silently uninstall.
15574        if (mRequiredVerifierPackage != null &&
15575                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15576            return true;
15577        }
15578
15579        // Allow package uninstaller to silently uninstall.
15580        if (mRequiredUninstallerPackage != null &&
15581                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15582            return true;
15583        }
15584
15585        // Allow storage manager to silently uninstall.
15586        if (mStorageManagerPackage != null &&
15587                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
15588            return true;
15589        }
15590        return false;
15591    }
15592
15593    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15594        int[] result = EMPTY_INT_ARRAY;
15595        for (int userId : userIds) {
15596            if (getBlockUninstallForUser(packageName, userId)) {
15597                result = ArrayUtils.appendInt(result, userId);
15598            }
15599        }
15600        return result;
15601    }
15602
15603    @Override
15604    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15605        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15606    }
15607
15608    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15609        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15610                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15611        try {
15612            if (dpm != null) {
15613                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15614                        /* callingUserOnly =*/ false);
15615                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15616                        : deviceOwnerComponentName.getPackageName();
15617                // Does the package contains the device owner?
15618                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15619                // this check is probably not needed, since DO should be registered as a device
15620                // admin on some user too. (Original bug for this: b/17657954)
15621                if (packageName.equals(deviceOwnerPackageName)) {
15622                    return true;
15623                }
15624                // Does it contain a device admin for any user?
15625                int[] users;
15626                if (userId == UserHandle.USER_ALL) {
15627                    users = sUserManager.getUserIds();
15628                } else {
15629                    users = new int[]{userId};
15630                }
15631                for (int i = 0; i < users.length; ++i) {
15632                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15633                        return true;
15634                    }
15635                }
15636            }
15637        } catch (RemoteException e) {
15638        }
15639        return false;
15640    }
15641
15642    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15643        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15644    }
15645
15646    /**
15647     *  This method is an internal method that could be get invoked either
15648     *  to delete an installed package or to clean up a failed installation.
15649     *  After deleting an installed package, a broadcast is sent to notify any
15650     *  listeners that the package has been removed. For cleaning up a failed
15651     *  installation, the broadcast is not necessary since the package's
15652     *  installation wouldn't have sent the initial broadcast either
15653     *  The key steps in deleting a package are
15654     *  deleting the package information in internal structures like mPackages,
15655     *  deleting the packages base directories through installd
15656     *  updating mSettings to reflect current status
15657     *  persisting settings for later use
15658     *  sending a broadcast if necessary
15659     */
15660    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15661        final PackageRemovedInfo info = new PackageRemovedInfo();
15662        final boolean res;
15663
15664        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15665                ? UserHandle.USER_ALL : userId;
15666
15667        if (isPackageDeviceAdmin(packageName, removeUser)) {
15668            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15669            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15670        }
15671
15672        PackageSetting uninstalledPs = null;
15673
15674        // for the uninstall-updates case and restricted profiles, remember the per-
15675        // user handle installed state
15676        int[] allUsers;
15677        synchronized (mPackages) {
15678            uninstalledPs = mSettings.mPackages.get(packageName);
15679            if (uninstalledPs == null) {
15680                Slog.w(TAG, "Not removing non-existent package " + packageName);
15681                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15682            }
15683            allUsers = sUserManager.getUserIds();
15684            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15685        }
15686
15687        final int freezeUser;
15688        if (isUpdatedSystemApp(uninstalledPs)
15689                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15690            // We're downgrading a system app, which will apply to all users, so
15691            // freeze them all during the downgrade
15692            freezeUser = UserHandle.USER_ALL;
15693        } else {
15694            freezeUser = removeUser;
15695        }
15696
15697        synchronized (mInstallLock) {
15698            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15699            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15700                    deleteFlags, "deletePackageX")) {
15701                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15702                        deleteFlags | REMOVE_CHATTY, info, true, null);
15703            }
15704            synchronized (mPackages) {
15705                if (res) {
15706                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15707                }
15708            }
15709        }
15710
15711        if (res) {
15712            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15713            info.sendPackageRemovedBroadcasts(killApp);
15714            info.sendSystemPackageUpdatedBroadcasts();
15715            info.sendSystemPackageAppearedBroadcasts();
15716        }
15717        // Force a gc here.
15718        Runtime.getRuntime().gc();
15719        // Delete the resources here after sending the broadcast to let
15720        // other processes clean up before deleting resources.
15721        if (info.args != null) {
15722            synchronized (mInstallLock) {
15723                info.args.doPostDeleteLI(true);
15724            }
15725        }
15726
15727        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15728    }
15729
15730    class PackageRemovedInfo {
15731        String removedPackage;
15732        int uid = -1;
15733        int removedAppId = -1;
15734        int[] origUsers;
15735        int[] removedUsers = null;
15736        boolean isRemovedPackageSystemUpdate = false;
15737        boolean isUpdate;
15738        boolean dataRemoved;
15739        boolean removedForAllUsers;
15740        // Clean up resources deleted packages.
15741        InstallArgs args = null;
15742        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15743        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15744
15745        void sendPackageRemovedBroadcasts(boolean killApp) {
15746            sendPackageRemovedBroadcastInternal(killApp);
15747            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15748            for (int i = 0; i < childCount; i++) {
15749                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15750                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15751            }
15752        }
15753
15754        void sendSystemPackageUpdatedBroadcasts() {
15755            if (isRemovedPackageSystemUpdate) {
15756                sendSystemPackageUpdatedBroadcastsInternal();
15757                final int childCount = (removedChildPackages != null)
15758                        ? removedChildPackages.size() : 0;
15759                for (int i = 0; i < childCount; i++) {
15760                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15761                    if (childInfo.isRemovedPackageSystemUpdate) {
15762                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15763                    }
15764                }
15765            }
15766        }
15767
15768        void sendSystemPackageAppearedBroadcasts() {
15769            final int packageCount = (appearedChildPackages != null)
15770                    ? appearedChildPackages.size() : 0;
15771            for (int i = 0; i < packageCount; i++) {
15772                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15773                for (int userId : installedInfo.newUsers) {
15774                    sendPackageAddedForUser(installedInfo.name, true,
15775                            UserHandle.getAppId(installedInfo.uid), userId);
15776                }
15777            }
15778        }
15779
15780        private void sendSystemPackageUpdatedBroadcastsInternal() {
15781            Bundle extras = new Bundle(2);
15782            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15783            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15784            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15785                    extras, 0, null, null, null);
15786            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15787                    extras, 0, null, null, null);
15788            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15789                    null, 0, removedPackage, null, null);
15790        }
15791
15792        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15793            Bundle extras = new Bundle(2);
15794            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15795            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15796            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15797            if (isUpdate || isRemovedPackageSystemUpdate) {
15798                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15799            }
15800            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15801            if (removedPackage != null) {
15802                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15803                        extras, 0, null, null, removedUsers);
15804                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15805                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15806                            removedPackage, extras, 0, null, null, removedUsers);
15807                }
15808            }
15809            if (removedAppId >= 0) {
15810                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15811                        removedUsers);
15812            }
15813        }
15814    }
15815
15816    /*
15817     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15818     * flag is not set, the data directory is removed as well.
15819     * make sure this flag is set for partially installed apps. If not its meaningless to
15820     * delete a partially installed application.
15821     */
15822    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15823            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15824        String packageName = ps.name;
15825        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15826        // Retrieve object to delete permissions for shared user later on
15827        final PackageParser.Package deletedPkg;
15828        final PackageSetting deletedPs;
15829        // reader
15830        synchronized (mPackages) {
15831            deletedPkg = mPackages.get(packageName);
15832            deletedPs = mSettings.mPackages.get(packageName);
15833            if (outInfo != null) {
15834                outInfo.removedPackage = packageName;
15835                outInfo.removedUsers = deletedPs != null
15836                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15837                        : null;
15838            }
15839        }
15840
15841        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15842
15843        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15844            final PackageParser.Package resolvedPkg;
15845            if (deletedPkg != null) {
15846                resolvedPkg = deletedPkg;
15847            } else {
15848                // We don't have a parsed package when it lives on an ejected
15849                // adopted storage device, so fake something together
15850                resolvedPkg = new PackageParser.Package(ps.name);
15851                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15852            }
15853            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15854                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15855            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15856            if (outInfo != null) {
15857                outInfo.dataRemoved = true;
15858            }
15859            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15860        }
15861
15862        // writer
15863        synchronized (mPackages) {
15864            if (deletedPs != null) {
15865                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15866                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15867                    clearDefaultBrowserIfNeeded(packageName);
15868                    if (outInfo != null) {
15869                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15870                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15871                    }
15872                    updatePermissionsLPw(deletedPs.name, null, 0);
15873                    if (deletedPs.sharedUser != null) {
15874                        // Remove permissions associated with package. Since runtime
15875                        // permissions are per user we have to kill the removed package
15876                        // or packages running under the shared user of the removed
15877                        // package if revoking the permissions requested only by the removed
15878                        // package is successful and this causes a change in gids.
15879                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15880                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15881                                    userId);
15882                            if (userIdToKill == UserHandle.USER_ALL
15883                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15884                                // If gids changed for this user, kill all affected packages.
15885                                mHandler.post(new Runnable() {
15886                                    @Override
15887                                    public void run() {
15888                                        // This has to happen with no lock held.
15889                                        killApplication(deletedPs.name, deletedPs.appId,
15890                                                KILL_APP_REASON_GIDS_CHANGED);
15891                                    }
15892                                });
15893                                break;
15894                            }
15895                        }
15896                    }
15897                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15898                }
15899                // make sure to preserve per-user disabled state if this removal was just
15900                // a downgrade of a system app to the factory package
15901                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15902                    if (DEBUG_REMOVE) {
15903                        Slog.d(TAG, "Propagating install state across downgrade");
15904                    }
15905                    for (int userId : allUserHandles) {
15906                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15907                        if (DEBUG_REMOVE) {
15908                            Slog.d(TAG, "    user " + userId + " => " + installed);
15909                        }
15910                        ps.setInstalled(installed, userId);
15911                    }
15912                }
15913            }
15914            // can downgrade to reader
15915            if (writeSettings) {
15916                // Save settings now
15917                mSettings.writeLPr();
15918            }
15919        }
15920        if (outInfo != null) {
15921            // A user ID was deleted here. Go through all users and remove it
15922            // from KeyStore.
15923            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15924        }
15925    }
15926
15927    static boolean locationIsPrivileged(File path) {
15928        try {
15929            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15930                    .getCanonicalPath();
15931            return path.getCanonicalPath().startsWith(privilegedAppDir);
15932        } catch (IOException e) {
15933            Slog.e(TAG, "Unable to access code path " + path);
15934        }
15935        return false;
15936    }
15937
15938    /*
15939     * Tries to delete system package.
15940     */
15941    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15942            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15943            boolean writeSettings) {
15944        if (deletedPs.parentPackageName != null) {
15945            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15946            return false;
15947        }
15948
15949        final boolean applyUserRestrictions
15950                = (allUserHandles != null) && (outInfo.origUsers != null);
15951        final PackageSetting disabledPs;
15952        // Confirm if the system package has been updated
15953        // An updated system app can be deleted. This will also have to restore
15954        // the system pkg from system partition
15955        // reader
15956        synchronized (mPackages) {
15957            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15958        }
15959
15960        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15961                + " disabledPs=" + disabledPs);
15962
15963        if (disabledPs == null) {
15964            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15965            return false;
15966        } else if (DEBUG_REMOVE) {
15967            Slog.d(TAG, "Deleting system pkg from data partition");
15968        }
15969
15970        if (DEBUG_REMOVE) {
15971            if (applyUserRestrictions) {
15972                Slog.d(TAG, "Remembering install states:");
15973                for (int userId : allUserHandles) {
15974                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15975                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15976                }
15977            }
15978        }
15979
15980        // Delete the updated package
15981        outInfo.isRemovedPackageSystemUpdate = true;
15982        if (outInfo.removedChildPackages != null) {
15983            final int childCount = (deletedPs.childPackageNames != null)
15984                    ? deletedPs.childPackageNames.size() : 0;
15985            for (int i = 0; i < childCount; i++) {
15986                String childPackageName = deletedPs.childPackageNames.get(i);
15987                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15988                        .contains(childPackageName)) {
15989                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15990                            childPackageName);
15991                    if (childInfo != null) {
15992                        childInfo.isRemovedPackageSystemUpdate = true;
15993                    }
15994                }
15995            }
15996        }
15997
15998        if (disabledPs.versionCode < deletedPs.versionCode) {
15999            // Delete data for downgrades
16000            flags &= ~PackageManager.DELETE_KEEP_DATA;
16001        } else {
16002            // Preserve data by setting flag
16003            flags |= PackageManager.DELETE_KEEP_DATA;
16004        }
16005
16006        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16007                outInfo, writeSettings, disabledPs.pkg);
16008        if (!ret) {
16009            return false;
16010        }
16011
16012        // writer
16013        synchronized (mPackages) {
16014            // Reinstate the old system package
16015            enableSystemPackageLPw(disabledPs.pkg);
16016            // Remove any native libraries from the upgraded package.
16017            removeNativeBinariesLI(deletedPs);
16018        }
16019
16020        // Install the system package
16021        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16022        int parseFlags = mDefParseFlags
16023                | PackageParser.PARSE_MUST_BE_APK
16024                | PackageParser.PARSE_IS_SYSTEM
16025                | PackageParser.PARSE_IS_SYSTEM_DIR;
16026        if (locationIsPrivileged(disabledPs.codePath)) {
16027            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16028        }
16029
16030        final PackageParser.Package newPkg;
16031        try {
16032            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16033        } catch (PackageManagerException e) {
16034            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16035                    + e.getMessage());
16036            return false;
16037        }
16038        try {
16039            // update shared libraries for the newly re-installed system package
16040            updateSharedLibrariesLPw(newPkg, null);
16041        } catch (PackageManagerException e) {
16042            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16043        }
16044
16045        prepareAppDataAfterInstallLIF(newPkg);
16046
16047        // writer
16048        synchronized (mPackages) {
16049            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16050
16051            // Propagate the permissions state as we do not want to drop on the floor
16052            // runtime permissions. The update permissions method below will take
16053            // care of removing obsolete permissions and grant install permissions.
16054            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16055            updatePermissionsLPw(newPkg.packageName, newPkg,
16056                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16057
16058            if (applyUserRestrictions) {
16059                if (DEBUG_REMOVE) {
16060                    Slog.d(TAG, "Propagating install state across reinstall");
16061                }
16062                for (int userId : allUserHandles) {
16063                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16064                    if (DEBUG_REMOVE) {
16065                        Slog.d(TAG, "    user " + userId + " => " + installed);
16066                    }
16067                    ps.setInstalled(installed, userId);
16068
16069                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16070                }
16071                // Regardless of writeSettings we need to ensure that this restriction
16072                // state propagation is persisted
16073                mSettings.writeAllUsersPackageRestrictionsLPr();
16074            }
16075            // can downgrade to reader here
16076            if (writeSettings) {
16077                mSettings.writeLPr();
16078            }
16079        }
16080        return true;
16081    }
16082
16083    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16084            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16085            PackageRemovedInfo outInfo, boolean writeSettings,
16086            PackageParser.Package replacingPackage) {
16087        synchronized (mPackages) {
16088            if (outInfo != null) {
16089                outInfo.uid = ps.appId;
16090            }
16091
16092            if (outInfo != null && outInfo.removedChildPackages != null) {
16093                final int childCount = (ps.childPackageNames != null)
16094                        ? ps.childPackageNames.size() : 0;
16095                for (int i = 0; i < childCount; i++) {
16096                    String childPackageName = ps.childPackageNames.get(i);
16097                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16098                    if (childPs == null) {
16099                        return false;
16100                    }
16101                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16102                            childPackageName);
16103                    if (childInfo != null) {
16104                        childInfo.uid = childPs.appId;
16105                    }
16106                }
16107            }
16108        }
16109
16110        // Delete package data from internal structures and also remove data if flag is set
16111        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16112
16113        // Delete the child packages data
16114        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16115        for (int i = 0; i < childCount; i++) {
16116            PackageSetting childPs;
16117            synchronized (mPackages) {
16118                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16119            }
16120            if (childPs != null) {
16121                PackageRemovedInfo childOutInfo = (outInfo != null
16122                        && outInfo.removedChildPackages != null)
16123                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16124                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16125                        && (replacingPackage != null
16126                        && !replacingPackage.hasChildPackage(childPs.name))
16127                        ? flags & ~DELETE_KEEP_DATA : flags;
16128                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16129                        deleteFlags, writeSettings);
16130            }
16131        }
16132
16133        // Delete application code and resources only for parent packages
16134        if (ps.parentPackageName == null) {
16135            if (deleteCodeAndResources && (outInfo != null)) {
16136                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16137                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16138                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16139            }
16140        }
16141
16142        return true;
16143    }
16144
16145    @Override
16146    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16147            int userId) {
16148        mContext.enforceCallingOrSelfPermission(
16149                android.Manifest.permission.DELETE_PACKAGES, null);
16150        synchronized (mPackages) {
16151            PackageSetting ps = mSettings.mPackages.get(packageName);
16152            if (ps == null) {
16153                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16154                return false;
16155            }
16156            if (!ps.getInstalled(userId)) {
16157                // Can't block uninstall for an app that is not installed or enabled.
16158                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16159                return false;
16160            }
16161            ps.setBlockUninstall(blockUninstall, userId);
16162            mSettings.writePackageRestrictionsLPr(userId);
16163        }
16164        return true;
16165    }
16166
16167    @Override
16168    public boolean getBlockUninstallForUser(String packageName, int userId) {
16169        synchronized (mPackages) {
16170            PackageSetting ps = mSettings.mPackages.get(packageName);
16171            if (ps == null) {
16172                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16173                return false;
16174            }
16175            return ps.getBlockUninstall(userId);
16176        }
16177    }
16178
16179    @Override
16180    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16181        int callingUid = Binder.getCallingUid();
16182        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16183            throw new SecurityException(
16184                    "setRequiredForSystemUser can only be run by the system or root");
16185        }
16186        synchronized (mPackages) {
16187            PackageSetting ps = mSettings.mPackages.get(packageName);
16188            if (ps == null) {
16189                Log.w(TAG, "Package doesn't exist: " + packageName);
16190                return false;
16191            }
16192            if (systemUserApp) {
16193                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16194            } else {
16195                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16196            }
16197            mSettings.writeLPr();
16198        }
16199        return true;
16200    }
16201
16202    /*
16203     * This method handles package deletion in general
16204     */
16205    private boolean deletePackageLIF(String packageName, UserHandle user,
16206            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16207            PackageRemovedInfo outInfo, boolean writeSettings,
16208            PackageParser.Package replacingPackage) {
16209        if (packageName == null) {
16210            Slog.w(TAG, "Attempt to delete null packageName.");
16211            return false;
16212        }
16213
16214        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16215
16216        PackageSetting ps;
16217
16218        synchronized (mPackages) {
16219            ps = mSettings.mPackages.get(packageName);
16220            if (ps == null) {
16221                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16222                return false;
16223            }
16224
16225            if (ps.parentPackageName != null && (!isSystemApp(ps)
16226                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16227                if (DEBUG_REMOVE) {
16228                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16229                            + ((user == null) ? UserHandle.USER_ALL : user));
16230                }
16231                final int removedUserId = (user != null) ? user.getIdentifier()
16232                        : UserHandle.USER_ALL;
16233                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16234                    return false;
16235                }
16236                markPackageUninstalledForUserLPw(ps, user);
16237                scheduleWritePackageRestrictionsLocked(user);
16238                return true;
16239            }
16240        }
16241
16242        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16243                && user.getIdentifier() != UserHandle.USER_ALL)) {
16244            // The caller is asking that the package only be deleted for a single
16245            // user.  To do this, we just mark its uninstalled state and delete
16246            // its data. If this is a system app, we only allow this to happen if
16247            // they have set the special DELETE_SYSTEM_APP which requests different
16248            // semantics than normal for uninstalling system apps.
16249            markPackageUninstalledForUserLPw(ps, user);
16250
16251            if (!isSystemApp(ps)) {
16252                // Do not uninstall the APK if an app should be cached
16253                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16254                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16255                    // Other user still have this package installed, so all
16256                    // we need to do is clear this user's data and save that
16257                    // it is uninstalled.
16258                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16259                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16260                        return false;
16261                    }
16262                    scheduleWritePackageRestrictionsLocked(user);
16263                    return true;
16264                } else {
16265                    // We need to set it back to 'installed' so the uninstall
16266                    // broadcasts will be sent correctly.
16267                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16268                    ps.setInstalled(true, user.getIdentifier());
16269                }
16270            } else {
16271                // This is a system app, so we assume that the
16272                // other users still have this package installed, so all
16273                // we need to do is clear this user's data and save that
16274                // it is uninstalled.
16275                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16276                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16277                    return false;
16278                }
16279                scheduleWritePackageRestrictionsLocked(user);
16280                return true;
16281            }
16282        }
16283
16284        // If we are deleting a composite package for all users, keep track
16285        // of result for each child.
16286        if (ps.childPackageNames != null && outInfo != null) {
16287            synchronized (mPackages) {
16288                final int childCount = ps.childPackageNames.size();
16289                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16290                for (int i = 0; i < childCount; i++) {
16291                    String childPackageName = ps.childPackageNames.get(i);
16292                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16293                    childInfo.removedPackage = childPackageName;
16294                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16295                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16296                    if (childPs != null) {
16297                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16298                    }
16299                }
16300            }
16301        }
16302
16303        boolean ret = false;
16304        if (isSystemApp(ps)) {
16305            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16306            // When an updated system application is deleted we delete the existing resources
16307            // as well and fall back to existing code in system partition
16308            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16309        } else {
16310            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16311            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16312                    outInfo, writeSettings, replacingPackage);
16313        }
16314
16315        // Take a note whether we deleted the package for all users
16316        if (outInfo != null) {
16317            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16318            if (outInfo.removedChildPackages != null) {
16319                synchronized (mPackages) {
16320                    final int childCount = outInfo.removedChildPackages.size();
16321                    for (int i = 0; i < childCount; i++) {
16322                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16323                        if (childInfo != null) {
16324                            childInfo.removedForAllUsers = mPackages.get(
16325                                    childInfo.removedPackage) == null;
16326                        }
16327                    }
16328                }
16329            }
16330            // If we uninstalled an update to a system app there may be some
16331            // child packages that appeared as they are declared in the system
16332            // app but were not declared in the update.
16333            if (isSystemApp(ps)) {
16334                synchronized (mPackages) {
16335                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16336                    final int childCount = (updatedPs.childPackageNames != null)
16337                            ? updatedPs.childPackageNames.size() : 0;
16338                    for (int i = 0; i < childCount; i++) {
16339                        String childPackageName = updatedPs.childPackageNames.get(i);
16340                        if (outInfo.removedChildPackages == null
16341                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16342                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16343                            if (childPs == null) {
16344                                continue;
16345                            }
16346                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16347                            installRes.name = childPackageName;
16348                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16349                            installRes.pkg = mPackages.get(childPackageName);
16350                            installRes.uid = childPs.pkg.applicationInfo.uid;
16351                            if (outInfo.appearedChildPackages == null) {
16352                                outInfo.appearedChildPackages = new ArrayMap<>();
16353                            }
16354                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16355                        }
16356                    }
16357                }
16358            }
16359        }
16360
16361        return ret;
16362    }
16363
16364    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16365        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16366                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16367        for (int nextUserId : userIds) {
16368            if (DEBUG_REMOVE) {
16369                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16370            }
16371            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16372                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16373                    false /*hidden*/, false /*suspended*/, null, null, null,
16374                    false /*blockUninstall*/,
16375                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16376        }
16377    }
16378
16379    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16380            PackageRemovedInfo outInfo) {
16381        final PackageParser.Package pkg;
16382        synchronized (mPackages) {
16383            pkg = mPackages.get(ps.name);
16384        }
16385
16386        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16387                : new int[] {userId};
16388        for (int nextUserId : userIds) {
16389            if (DEBUG_REMOVE) {
16390                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16391                        + nextUserId);
16392            }
16393
16394            destroyAppDataLIF(pkg, userId,
16395                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16396            destroyAppProfilesLIF(pkg, userId);
16397            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16398            schedulePackageCleaning(ps.name, nextUserId, false);
16399            synchronized (mPackages) {
16400                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16401                    scheduleWritePackageRestrictionsLocked(nextUserId);
16402                }
16403                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16404            }
16405        }
16406
16407        if (outInfo != null) {
16408            outInfo.removedPackage = ps.name;
16409            outInfo.removedAppId = ps.appId;
16410            outInfo.removedUsers = userIds;
16411        }
16412
16413        return true;
16414    }
16415
16416    private final class ClearStorageConnection implements ServiceConnection {
16417        IMediaContainerService mContainerService;
16418
16419        @Override
16420        public void onServiceConnected(ComponentName name, IBinder service) {
16421            synchronized (this) {
16422                mContainerService = IMediaContainerService.Stub.asInterface(service);
16423                notifyAll();
16424            }
16425        }
16426
16427        @Override
16428        public void onServiceDisconnected(ComponentName name) {
16429        }
16430    }
16431
16432    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16433        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16434
16435        final boolean mounted;
16436        if (Environment.isExternalStorageEmulated()) {
16437            mounted = true;
16438        } else {
16439            final String status = Environment.getExternalStorageState();
16440
16441            mounted = status.equals(Environment.MEDIA_MOUNTED)
16442                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16443        }
16444
16445        if (!mounted) {
16446            return;
16447        }
16448
16449        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16450        int[] users;
16451        if (userId == UserHandle.USER_ALL) {
16452            users = sUserManager.getUserIds();
16453        } else {
16454            users = new int[] { userId };
16455        }
16456        final ClearStorageConnection conn = new ClearStorageConnection();
16457        if (mContext.bindServiceAsUser(
16458                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16459            try {
16460                for (int curUser : users) {
16461                    long timeout = SystemClock.uptimeMillis() + 5000;
16462                    synchronized (conn) {
16463                        long now;
16464                        while (conn.mContainerService == null &&
16465                                (now = SystemClock.uptimeMillis()) < timeout) {
16466                            try {
16467                                conn.wait(timeout - now);
16468                            } catch (InterruptedException e) {
16469                            }
16470                        }
16471                    }
16472                    if (conn.mContainerService == null) {
16473                        return;
16474                    }
16475
16476                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16477                    clearDirectory(conn.mContainerService,
16478                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16479                    if (allData) {
16480                        clearDirectory(conn.mContainerService,
16481                                userEnv.buildExternalStorageAppDataDirs(packageName));
16482                        clearDirectory(conn.mContainerService,
16483                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16484                    }
16485                }
16486            } finally {
16487                mContext.unbindService(conn);
16488            }
16489        }
16490    }
16491
16492    @Override
16493    public void clearApplicationProfileData(String packageName) {
16494        enforceSystemOrRoot("Only the system can clear all profile data");
16495
16496        final PackageParser.Package pkg;
16497        synchronized (mPackages) {
16498            pkg = mPackages.get(packageName);
16499        }
16500
16501        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16502            synchronized (mInstallLock) {
16503                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16504                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16505                        true /* removeBaseMarker */);
16506            }
16507        }
16508    }
16509
16510    @Override
16511    public void clearApplicationUserData(final String packageName,
16512            final IPackageDataObserver observer, final int userId) {
16513        mContext.enforceCallingOrSelfPermission(
16514                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16515
16516        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16517                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16518
16519        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16520            throw new SecurityException("Cannot clear data for a protected package: "
16521                    + packageName);
16522        }
16523        // Queue up an async operation since the package deletion may take a little while.
16524        mHandler.post(new Runnable() {
16525            public void run() {
16526                mHandler.removeCallbacks(this);
16527                final boolean succeeded;
16528                try (PackageFreezer freezer = freezePackage(packageName,
16529                        "clearApplicationUserData")) {
16530                    synchronized (mInstallLock) {
16531                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16532                    }
16533                    clearExternalStorageDataSync(packageName, userId, true);
16534                }
16535                if (succeeded) {
16536                    // invoke DeviceStorageMonitor's update method to clear any notifications
16537                    DeviceStorageMonitorInternal dsm = LocalServices
16538                            .getService(DeviceStorageMonitorInternal.class);
16539                    if (dsm != null) {
16540                        dsm.checkMemory();
16541                    }
16542                }
16543                if(observer != null) {
16544                    try {
16545                        observer.onRemoveCompleted(packageName, succeeded);
16546                    } catch (RemoteException e) {
16547                        Log.i(TAG, "Observer no longer exists.");
16548                    }
16549                } //end if observer
16550            } //end run
16551        });
16552    }
16553
16554    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16555        if (packageName == null) {
16556            Slog.w(TAG, "Attempt to delete null packageName.");
16557            return false;
16558        }
16559
16560        // Try finding details about the requested package
16561        PackageParser.Package pkg;
16562        synchronized (mPackages) {
16563            pkg = mPackages.get(packageName);
16564            if (pkg == null) {
16565                final PackageSetting ps = mSettings.mPackages.get(packageName);
16566                if (ps != null) {
16567                    pkg = ps.pkg;
16568                }
16569            }
16570
16571            if (pkg == null) {
16572                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16573                return false;
16574            }
16575
16576            PackageSetting ps = (PackageSetting) pkg.mExtras;
16577            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16578        }
16579
16580        clearAppDataLIF(pkg, userId,
16581                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16582
16583        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16584        removeKeystoreDataIfNeeded(userId, appId);
16585
16586        UserManagerInternal umInternal = getUserManagerInternal();
16587        final int flags;
16588        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16589            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16590        } else if (umInternal.isUserRunning(userId)) {
16591            flags = StorageManager.FLAG_STORAGE_DE;
16592        } else {
16593            flags = 0;
16594        }
16595        prepareAppDataContentsLIF(pkg, userId, flags);
16596
16597        return true;
16598    }
16599
16600    /**
16601     * Reverts user permission state changes (permissions and flags) in
16602     * all packages for a given user.
16603     *
16604     * @param userId The device user for which to do a reset.
16605     */
16606    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16607        final int packageCount = mPackages.size();
16608        for (int i = 0; i < packageCount; i++) {
16609            PackageParser.Package pkg = mPackages.valueAt(i);
16610            PackageSetting ps = (PackageSetting) pkg.mExtras;
16611            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16612        }
16613    }
16614
16615    private void resetNetworkPolicies(int userId) {
16616        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16617    }
16618
16619    /**
16620     * Reverts user permission state changes (permissions and flags).
16621     *
16622     * @param ps The package for which to reset.
16623     * @param userId The device user for which to do a reset.
16624     */
16625    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16626            final PackageSetting ps, final int userId) {
16627        if (ps.pkg == null) {
16628            return;
16629        }
16630
16631        // These are flags that can change base on user actions.
16632        final int userSettableMask = FLAG_PERMISSION_USER_SET
16633                | FLAG_PERMISSION_USER_FIXED
16634                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16635                | FLAG_PERMISSION_REVIEW_REQUIRED;
16636
16637        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16638                | FLAG_PERMISSION_POLICY_FIXED;
16639
16640        boolean writeInstallPermissions = false;
16641        boolean writeRuntimePermissions = false;
16642
16643        final int permissionCount = ps.pkg.requestedPermissions.size();
16644        for (int i = 0; i < permissionCount; i++) {
16645            String permission = ps.pkg.requestedPermissions.get(i);
16646
16647            BasePermission bp = mSettings.mPermissions.get(permission);
16648            if (bp == null) {
16649                continue;
16650            }
16651
16652            // If shared user we just reset the state to which only this app contributed.
16653            if (ps.sharedUser != null) {
16654                boolean used = false;
16655                final int packageCount = ps.sharedUser.packages.size();
16656                for (int j = 0; j < packageCount; j++) {
16657                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16658                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16659                            && pkg.pkg.requestedPermissions.contains(permission)) {
16660                        used = true;
16661                        break;
16662                    }
16663                }
16664                if (used) {
16665                    continue;
16666                }
16667            }
16668
16669            PermissionsState permissionsState = ps.getPermissionsState();
16670
16671            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16672
16673            // Always clear the user settable flags.
16674            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16675                    bp.name) != null;
16676            // If permission review is enabled and this is a legacy app, mark the
16677            // permission as requiring a review as this is the initial state.
16678            int flags = 0;
16679            if (Build.PERMISSIONS_REVIEW_REQUIRED
16680                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16681                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16682            }
16683            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16684                if (hasInstallState) {
16685                    writeInstallPermissions = true;
16686                } else {
16687                    writeRuntimePermissions = true;
16688                }
16689            }
16690
16691            // Below is only runtime permission handling.
16692            if (!bp.isRuntime()) {
16693                continue;
16694            }
16695
16696            // Never clobber system or policy.
16697            if ((oldFlags & policyOrSystemFlags) != 0) {
16698                continue;
16699            }
16700
16701            // If this permission was granted by default, make sure it is.
16702            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16703                if (permissionsState.grantRuntimePermission(bp, userId)
16704                        != PERMISSION_OPERATION_FAILURE) {
16705                    writeRuntimePermissions = true;
16706                }
16707            // If permission review is enabled the permissions for a legacy apps
16708            // are represented as constantly granted runtime ones, so don't revoke.
16709            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16710                // Otherwise, reset the permission.
16711                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16712                switch (revokeResult) {
16713                    case PERMISSION_OPERATION_SUCCESS:
16714                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16715                        writeRuntimePermissions = true;
16716                        final int appId = ps.appId;
16717                        mHandler.post(new Runnable() {
16718                            @Override
16719                            public void run() {
16720                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16721                            }
16722                        });
16723                    } break;
16724                }
16725            }
16726        }
16727
16728        // Synchronously write as we are taking permissions away.
16729        if (writeRuntimePermissions) {
16730            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16731        }
16732
16733        // Synchronously write as we are taking permissions away.
16734        if (writeInstallPermissions) {
16735            mSettings.writeLPr();
16736        }
16737    }
16738
16739    /**
16740     * Remove entries from the keystore daemon. Will only remove it if the
16741     * {@code appId} is valid.
16742     */
16743    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16744        if (appId < 0) {
16745            return;
16746        }
16747
16748        final KeyStore keyStore = KeyStore.getInstance();
16749        if (keyStore != null) {
16750            if (userId == UserHandle.USER_ALL) {
16751                for (final int individual : sUserManager.getUserIds()) {
16752                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16753                }
16754            } else {
16755                keyStore.clearUid(UserHandle.getUid(userId, appId));
16756            }
16757        } else {
16758            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16759        }
16760    }
16761
16762    @Override
16763    public void deleteApplicationCacheFiles(final String packageName,
16764            final IPackageDataObserver observer) {
16765        final int userId = UserHandle.getCallingUserId();
16766        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16767    }
16768
16769    @Override
16770    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16771            final IPackageDataObserver observer) {
16772        mContext.enforceCallingOrSelfPermission(
16773                android.Manifest.permission.DELETE_CACHE_FILES, null);
16774        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16775                /* requireFullPermission= */ true, /* checkShell= */ false,
16776                "delete application cache files");
16777
16778        final PackageParser.Package pkg;
16779        synchronized (mPackages) {
16780            pkg = mPackages.get(packageName);
16781        }
16782
16783        // Queue up an async operation since the package deletion may take a little while.
16784        mHandler.post(new Runnable() {
16785            public void run() {
16786                synchronized (mInstallLock) {
16787                    final int flags = StorageManager.FLAG_STORAGE_DE
16788                            | StorageManager.FLAG_STORAGE_CE;
16789                    // We're only clearing cache files, so we don't care if the
16790                    // app is unfrozen and still able to run
16791                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16792                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16793                }
16794                clearExternalStorageDataSync(packageName, userId, false);
16795                if (observer != null) {
16796                    try {
16797                        observer.onRemoveCompleted(packageName, true);
16798                    } catch (RemoteException e) {
16799                        Log.i(TAG, "Observer no longer exists.");
16800                    }
16801                }
16802            }
16803        });
16804    }
16805
16806    @Override
16807    public void getPackageSizeInfo(final String packageName, int userHandle,
16808            final IPackageStatsObserver observer) {
16809        mContext.enforceCallingOrSelfPermission(
16810                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16811        if (packageName == null) {
16812            throw new IllegalArgumentException("Attempt to get size of null packageName");
16813        }
16814
16815        PackageStats stats = new PackageStats(packageName, userHandle);
16816
16817        /*
16818         * Queue up an async operation since the package measurement may take a
16819         * little while.
16820         */
16821        Message msg = mHandler.obtainMessage(INIT_COPY);
16822        msg.obj = new MeasureParams(stats, observer);
16823        mHandler.sendMessage(msg);
16824    }
16825
16826    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16827        final PackageSetting ps;
16828        synchronized (mPackages) {
16829            ps = mSettings.mPackages.get(packageName);
16830            if (ps == null) {
16831                Slog.w(TAG, "Failed to find settings for " + packageName);
16832                return false;
16833            }
16834        }
16835        try {
16836            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16837                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16838                    ps.getCeDataInode(userId), ps.codePathString, stats);
16839        } catch (InstallerException e) {
16840            Slog.w(TAG, String.valueOf(e));
16841            return false;
16842        }
16843
16844        // For now, ignore code size of packages on system partition
16845        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16846            stats.codeSize = 0;
16847        }
16848
16849        return true;
16850    }
16851
16852    private int getUidTargetSdkVersionLockedLPr(int uid) {
16853        Object obj = mSettings.getUserIdLPr(uid);
16854        if (obj instanceof SharedUserSetting) {
16855            final SharedUserSetting sus = (SharedUserSetting) obj;
16856            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16857            final Iterator<PackageSetting> it = sus.packages.iterator();
16858            while (it.hasNext()) {
16859                final PackageSetting ps = it.next();
16860                if (ps.pkg != null) {
16861                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16862                    if (v < vers) vers = v;
16863                }
16864            }
16865            return vers;
16866        } else if (obj instanceof PackageSetting) {
16867            final PackageSetting ps = (PackageSetting) obj;
16868            if (ps.pkg != null) {
16869                return ps.pkg.applicationInfo.targetSdkVersion;
16870            }
16871        }
16872        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16873    }
16874
16875    @Override
16876    public void addPreferredActivity(IntentFilter filter, int match,
16877            ComponentName[] set, ComponentName activity, int userId) {
16878        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16879                "Adding preferred");
16880    }
16881
16882    private void addPreferredActivityInternal(IntentFilter filter, int match,
16883            ComponentName[] set, ComponentName activity, boolean always, int userId,
16884            String opname) {
16885        // writer
16886        int callingUid = Binder.getCallingUid();
16887        enforceCrossUserPermission(callingUid, userId,
16888                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16889        if (filter.countActions() == 0) {
16890            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16891            return;
16892        }
16893        synchronized (mPackages) {
16894            if (mContext.checkCallingOrSelfPermission(
16895                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16896                    != PackageManager.PERMISSION_GRANTED) {
16897                if (getUidTargetSdkVersionLockedLPr(callingUid)
16898                        < Build.VERSION_CODES.FROYO) {
16899                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16900                            + callingUid);
16901                    return;
16902                }
16903                mContext.enforceCallingOrSelfPermission(
16904                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16905            }
16906
16907            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16908            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16909                    + userId + ":");
16910            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16911            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16912            scheduleWritePackageRestrictionsLocked(userId);
16913            postPreferredActivityChangedBroadcast(userId);
16914        }
16915    }
16916
16917    private void postPreferredActivityChangedBroadcast(int userId) {
16918        mHandler.post(() -> {
16919            final IActivityManager am = ActivityManagerNative.getDefault();
16920            if (am == null) {
16921                return;
16922            }
16923
16924            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
16925            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
16926            try {
16927                am.broadcastIntent(null, intent, null, null,
16928                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
16929                        null, false, false, userId);
16930            } catch (RemoteException e) {
16931            }
16932        });
16933    }
16934
16935    @Override
16936    public void replacePreferredActivity(IntentFilter filter, int match,
16937            ComponentName[] set, ComponentName activity, int userId) {
16938        if (filter.countActions() != 1) {
16939            throw new IllegalArgumentException(
16940                    "replacePreferredActivity expects filter to have only 1 action.");
16941        }
16942        if (filter.countDataAuthorities() != 0
16943                || filter.countDataPaths() != 0
16944                || filter.countDataSchemes() > 1
16945                || filter.countDataTypes() != 0) {
16946            throw new IllegalArgumentException(
16947                    "replacePreferredActivity expects filter to have no data authorities, " +
16948                    "paths, or types; and at most one scheme.");
16949        }
16950
16951        final int callingUid = Binder.getCallingUid();
16952        enforceCrossUserPermission(callingUid, userId,
16953                true /* requireFullPermission */, false /* checkShell */,
16954                "replace preferred activity");
16955        synchronized (mPackages) {
16956            if (mContext.checkCallingOrSelfPermission(
16957                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16958                    != PackageManager.PERMISSION_GRANTED) {
16959                if (getUidTargetSdkVersionLockedLPr(callingUid)
16960                        < Build.VERSION_CODES.FROYO) {
16961                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16962                            + Binder.getCallingUid());
16963                    return;
16964                }
16965                mContext.enforceCallingOrSelfPermission(
16966                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16967            }
16968
16969            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16970            if (pir != null) {
16971                // Get all of the existing entries that exactly match this filter.
16972                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16973                if (existing != null && existing.size() == 1) {
16974                    PreferredActivity cur = existing.get(0);
16975                    if (DEBUG_PREFERRED) {
16976                        Slog.i(TAG, "Checking replace of preferred:");
16977                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16978                        if (!cur.mPref.mAlways) {
16979                            Slog.i(TAG, "  -- CUR; not mAlways!");
16980                        } else {
16981                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16982                            Slog.i(TAG, "  -- CUR: mSet="
16983                                    + Arrays.toString(cur.mPref.mSetComponents));
16984                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16985                            Slog.i(TAG, "  -- NEW: mMatch="
16986                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16987                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16988                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16989                        }
16990                    }
16991                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16992                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16993                            && cur.mPref.sameSet(set)) {
16994                        // Setting the preferred activity to what it happens to be already
16995                        if (DEBUG_PREFERRED) {
16996                            Slog.i(TAG, "Replacing with same preferred activity "
16997                                    + cur.mPref.mShortComponent + " for user "
16998                                    + userId + ":");
16999                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17000                        }
17001                        return;
17002                    }
17003                }
17004
17005                if (existing != null) {
17006                    if (DEBUG_PREFERRED) {
17007                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17008                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17009                    }
17010                    for (int i = 0; i < existing.size(); i++) {
17011                        PreferredActivity pa = existing.get(i);
17012                        if (DEBUG_PREFERRED) {
17013                            Slog.i(TAG, "Removing existing preferred activity "
17014                                    + pa.mPref.mComponent + ":");
17015                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17016                        }
17017                        pir.removeFilter(pa);
17018                    }
17019                }
17020            }
17021            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17022                    "Replacing preferred");
17023        }
17024    }
17025
17026    @Override
17027    public void clearPackagePreferredActivities(String packageName) {
17028        final int uid = Binder.getCallingUid();
17029        // writer
17030        synchronized (mPackages) {
17031            PackageParser.Package pkg = mPackages.get(packageName);
17032            if (pkg == null || pkg.applicationInfo.uid != uid) {
17033                if (mContext.checkCallingOrSelfPermission(
17034                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17035                        != PackageManager.PERMISSION_GRANTED) {
17036                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17037                            < Build.VERSION_CODES.FROYO) {
17038                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17039                                + Binder.getCallingUid());
17040                        return;
17041                    }
17042                    mContext.enforceCallingOrSelfPermission(
17043                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17044                }
17045            }
17046
17047            int user = UserHandle.getCallingUserId();
17048            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17049                scheduleWritePackageRestrictionsLocked(user);
17050            }
17051        }
17052    }
17053
17054    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17055    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17056        ArrayList<PreferredActivity> removed = null;
17057        boolean changed = false;
17058        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17059            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17060            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17061            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17062                continue;
17063            }
17064            Iterator<PreferredActivity> it = pir.filterIterator();
17065            while (it.hasNext()) {
17066                PreferredActivity pa = it.next();
17067                // Mark entry for removal only if it matches the package name
17068                // and the entry is of type "always".
17069                if (packageName == null ||
17070                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17071                                && pa.mPref.mAlways)) {
17072                    if (removed == null) {
17073                        removed = new ArrayList<PreferredActivity>();
17074                    }
17075                    removed.add(pa);
17076                }
17077            }
17078            if (removed != null) {
17079                for (int j=0; j<removed.size(); j++) {
17080                    PreferredActivity pa = removed.get(j);
17081                    pir.removeFilter(pa);
17082                }
17083                changed = true;
17084            }
17085        }
17086        if (changed) {
17087            postPreferredActivityChangedBroadcast(userId);
17088        }
17089        return changed;
17090    }
17091
17092    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17093    private void clearIntentFilterVerificationsLPw(int userId) {
17094        final int packageCount = mPackages.size();
17095        for (int i = 0; i < packageCount; i++) {
17096            PackageParser.Package pkg = mPackages.valueAt(i);
17097            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17098        }
17099    }
17100
17101    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17102    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17103        if (userId == UserHandle.USER_ALL) {
17104            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17105                    sUserManager.getUserIds())) {
17106                for (int oneUserId : sUserManager.getUserIds()) {
17107                    scheduleWritePackageRestrictionsLocked(oneUserId);
17108                }
17109            }
17110        } else {
17111            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17112                scheduleWritePackageRestrictionsLocked(userId);
17113            }
17114        }
17115    }
17116
17117    void clearDefaultBrowserIfNeeded(String packageName) {
17118        for (int oneUserId : sUserManager.getUserIds()) {
17119            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17120            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17121            if (packageName.equals(defaultBrowserPackageName)) {
17122                setDefaultBrowserPackageName(null, oneUserId);
17123            }
17124        }
17125    }
17126
17127    @Override
17128    public void resetApplicationPreferences(int userId) {
17129        mContext.enforceCallingOrSelfPermission(
17130                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17131        final long identity = Binder.clearCallingIdentity();
17132        // writer
17133        try {
17134            synchronized (mPackages) {
17135                clearPackagePreferredActivitiesLPw(null, userId);
17136                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17137                // TODO: We have to reset the default SMS and Phone. This requires
17138                // significant refactoring to keep all default apps in the package
17139                // manager (cleaner but more work) or have the services provide
17140                // callbacks to the package manager to request a default app reset.
17141                applyFactoryDefaultBrowserLPw(userId);
17142                clearIntentFilterVerificationsLPw(userId);
17143                primeDomainVerificationsLPw(userId);
17144                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17145                scheduleWritePackageRestrictionsLocked(userId);
17146            }
17147            resetNetworkPolicies(userId);
17148        } finally {
17149            Binder.restoreCallingIdentity(identity);
17150        }
17151    }
17152
17153    @Override
17154    public int getPreferredActivities(List<IntentFilter> outFilters,
17155            List<ComponentName> outActivities, String packageName) {
17156
17157        int num = 0;
17158        final int userId = UserHandle.getCallingUserId();
17159        // reader
17160        synchronized (mPackages) {
17161            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17162            if (pir != null) {
17163                final Iterator<PreferredActivity> it = pir.filterIterator();
17164                while (it.hasNext()) {
17165                    final PreferredActivity pa = it.next();
17166                    if (packageName == null
17167                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17168                                    && pa.mPref.mAlways)) {
17169                        if (outFilters != null) {
17170                            outFilters.add(new IntentFilter(pa));
17171                        }
17172                        if (outActivities != null) {
17173                            outActivities.add(pa.mPref.mComponent);
17174                        }
17175                    }
17176                }
17177            }
17178        }
17179
17180        return num;
17181    }
17182
17183    @Override
17184    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17185            int userId) {
17186        int callingUid = Binder.getCallingUid();
17187        if (callingUid != Process.SYSTEM_UID) {
17188            throw new SecurityException(
17189                    "addPersistentPreferredActivity can only be run by the system");
17190        }
17191        if (filter.countActions() == 0) {
17192            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17193            return;
17194        }
17195        synchronized (mPackages) {
17196            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17197                    ":");
17198            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17199            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17200                    new PersistentPreferredActivity(filter, activity));
17201            scheduleWritePackageRestrictionsLocked(userId);
17202            postPreferredActivityChangedBroadcast(userId);
17203        }
17204    }
17205
17206    @Override
17207    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17208        int callingUid = Binder.getCallingUid();
17209        if (callingUid != Process.SYSTEM_UID) {
17210            throw new SecurityException(
17211                    "clearPackagePersistentPreferredActivities can only be run by the system");
17212        }
17213        ArrayList<PersistentPreferredActivity> removed = null;
17214        boolean changed = false;
17215        synchronized (mPackages) {
17216            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17217                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17218                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17219                        .valueAt(i);
17220                if (userId != thisUserId) {
17221                    continue;
17222                }
17223                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17224                while (it.hasNext()) {
17225                    PersistentPreferredActivity ppa = it.next();
17226                    // Mark entry for removal only if it matches the package name.
17227                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17228                        if (removed == null) {
17229                            removed = new ArrayList<PersistentPreferredActivity>();
17230                        }
17231                        removed.add(ppa);
17232                    }
17233                }
17234                if (removed != null) {
17235                    for (int j=0; j<removed.size(); j++) {
17236                        PersistentPreferredActivity ppa = removed.get(j);
17237                        ppir.removeFilter(ppa);
17238                    }
17239                    changed = true;
17240                }
17241            }
17242
17243            if (changed) {
17244                scheduleWritePackageRestrictionsLocked(userId);
17245                postPreferredActivityChangedBroadcast(userId);
17246            }
17247        }
17248    }
17249
17250    /**
17251     * Common machinery for picking apart a restored XML blob and passing
17252     * it to a caller-supplied functor to be applied to the running system.
17253     */
17254    private void restoreFromXml(XmlPullParser parser, int userId,
17255            String expectedStartTag, BlobXmlRestorer functor)
17256            throws IOException, XmlPullParserException {
17257        int type;
17258        while ((type = parser.next()) != XmlPullParser.START_TAG
17259                && type != XmlPullParser.END_DOCUMENT) {
17260        }
17261        if (type != XmlPullParser.START_TAG) {
17262            // oops didn't find a start tag?!
17263            if (DEBUG_BACKUP) {
17264                Slog.e(TAG, "Didn't find start tag during restore");
17265            }
17266            return;
17267        }
17268Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17269        // this is supposed to be TAG_PREFERRED_BACKUP
17270        if (!expectedStartTag.equals(parser.getName())) {
17271            if (DEBUG_BACKUP) {
17272                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17273            }
17274            return;
17275        }
17276
17277        // skip interfering stuff, then we're aligned with the backing implementation
17278        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17279Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17280        functor.apply(parser, userId);
17281    }
17282
17283    private interface BlobXmlRestorer {
17284        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17285    }
17286
17287    /**
17288     * Non-Binder method, support for the backup/restore mechanism: write the
17289     * full set of preferred activities in its canonical XML format.  Returns the
17290     * XML output as a byte array, or null if there is none.
17291     */
17292    @Override
17293    public byte[] getPreferredActivityBackup(int userId) {
17294        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17295            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17296        }
17297
17298        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17299        try {
17300            final XmlSerializer serializer = new FastXmlSerializer();
17301            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17302            serializer.startDocument(null, true);
17303            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17304
17305            synchronized (mPackages) {
17306                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17307            }
17308
17309            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17310            serializer.endDocument();
17311            serializer.flush();
17312        } catch (Exception e) {
17313            if (DEBUG_BACKUP) {
17314                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17315            }
17316            return null;
17317        }
17318
17319        return dataStream.toByteArray();
17320    }
17321
17322    @Override
17323    public void restorePreferredActivities(byte[] backup, int userId) {
17324        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17325            throw new SecurityException("Only the system may call restorePreferredActivities()");
17326        }
17327
17328        try {
17329            final XmlPullParser parser = Xml.newPullParser();
17330            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17331            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17332                    new BlobXmlRestorer() {
17333                        @Override
17334                        public void apply(XmlPullParser parser, int userId)
17335                                throws XmlPullParserException, IOException {
17336                            synchronized (mPackages) {
17337                                mSettings.readPreferredActivitiesLPw(parser, userId);
17338                            }
17339                        }
17340                    } );
17341        } catch (Exception e) {
17342            if (DEBUG_BACKUP) {
17343                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17344            }
17345        }
17346    }
17347
17348    /**
17349     * Non-Binder method, support for the backup/restore mechanism: write the
17350     * default browser (etc) settings in its canonical XML format.  Returns the default
17351     * browser XML representation as a byte array, or null if there is none.
17352     */
17353    @Override
17354    public byte[] getDefaultAppsBackup(int userId) {
17355        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17356            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17357        }
17358
17359        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17360        try {
17361            final XmlSerializer serializer = new FastXmlSerializer();
17362            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17363            serializer.startDocument(null, true);
17364            serializer.startTag(null, TAG_DEFAULT_APPS);
17365
17366            synchronized (mPackages) {
17367                mSettings.writeDefaultAppsLPr(serializer, userId);
17368            }
17369
17370            serializer.endTag(null, TAG_DEFAULT_APPS);
17371            serializer.endDocument();
17372            serializer.flush();
17373        } catch (Exception e) {
17374            if (DEBUG_BACKUP) {
17375                Slog.e(TAG, "Unable to write default apps for backup", e);
17376            }
17377            return null;
17378        }
17379
17380        return dataStream.toByteArray();
17381    }
17382
17383    @Override
17384    public void restoreDefaultApps(byte[] backup, int userId) {
17385        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17386            throw new SecurityException("Only the system may call restoreDefaultApps()");
17387        }
17388
17389        try {
17390            final XmlPullParser parser = Xml.newPullParser();
17391            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17392            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17393                    new BlobXmlRestorer() {
17394                        @Override
17395                        public void apply(XmlPullParser parser, int userId)
17396                                throws XmlPullParserException, IOException {
17397                            synchronized (mPackages) {
17398                                mSettings.readDefaultAppsLPw(parser, userId);
17399                            }
17400                        }
17401                    } );
17402        } catch (Exception e) {
17403            if (DEBUG_BACKUP) {
17404                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17405            }
17406        }
17407    }
17408
17409    @Override
17410    public byte[] getIntentFilterVerificationBackup(int userId) {
17411        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17412            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17413        }
17414
17415        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17416        try {
17417            final XmlSerializer serializer = new FastXmlSerializer();
17418            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17419            serializer.startDocument(null, true);
17420            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17421
17422            synchronized (mPackages) {
17423                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17424            }
17425
17426            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17427            serializer.endDocument();
17428            serializer.flush();
17429        } catch (Exception e) {
17430            if (DEBUG_BACKUP) {
17431                Slog.e(TAG, "Unable to write default apps for backup", e);
17432            }
17433            return null;
17434        }
17435
17436        return dataStream.toByteArray();
17437    }
17438
17439    @Override
17440    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17441        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17442            throw new SecurityException("Only the system may call restorePreferredActivities()");
17443        }
17444
17445        try {
17446            final XmlPullParser parser = Xml.newPullParser();
17447            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17448            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17449                    new BlobXmlRestorer() {
17450                        @Override
17451                        public void apply(XmlPullParser parser, int userId)
17452                                throws XmlPullParserException, IOException {
17453                            synchronized (mPackages) {
17454                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17455                                mSettings.writeLPr();
17456                            }
17457                        }
17458                    } );
17459        } catch (Exception e) {
17460            if (DEBUG_BACKUP) {
17461                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17462            }
17463        }
17464    }
17465
17466    @Override
17467    public byte[] getPermissionGrantBackup(int userId) {
17468        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17469            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17470        }
17471
17472        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17473        try {
17474            final XmlSerializer serializer = new FastXmlSerializer();
17475            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17476            serializer.startDocument(null, true);
17477            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17478
17479            synchronized (mPackages) {
17480                serializeRuntimePermissionGrantsLPr(serializer, userId);
17481            }
17482
17483            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17484            serializer.endDocument();
17485            serializer.flush();
17486        } catch (Exception e) {
17487            if (DEBUG_BACKUP) {
17488                Slog.e(TAG, "Unable to write default apps for backup", e);
17489            }
17490            return null;
17491        }
17492
17493        return dataStream.toByteArray();
17494    }
17495
17496    @Override
17497    public void restorePermissionGrants(byte[] backup, int userId) {
17498        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17499            throw new SecurityException("Only the system may call restorePermissionGrants()");
17500        }
17501
17502        try {
17503            final XmlPullParser parser = Xml.newPullParser();
17504            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17505            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17506                    new BlobXmlRestorer() {
17507                        @Override
17508                        public void apply(XmlPullParser parser, int userId)
17509                                throws XmlPullParserException, IOException {
17510                            synchronized (mPackages) {
17511                                processRestoredPermissionGrantsLPr(parser, userId);
17512                            }
17513                        }
17514                    } );
17515        } catch (Exception e) {
17516            if (DEBUG_BACKUP) {
17517                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17518            }
17519        }
17520    }
17521
17522    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17523            throws IOException {
17524        serializer.startTag(null, TAG_ALL_GRANTS);
17525
17526        final int N = mSettings.mPackages.size();
17527        for (int i = 0; i < N; i++) {
17528            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17529            boolean pkgGrantsKnown = false;
17530
17531            PermissionsState packagePerms = ps.getPermissionsState();
17532
17533            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17534                final int grantFlags = state.getFlags();
17535                // only look at grants that are not system/policy fixed
17536                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17537                    final boolean isGranted = state.isGranted();
17538                    // And only back up the user-twiddled state bits
17539                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17540                        final String packageName = mSettings.mPackages.keyAt(i);
17541                        if (!pkgGrantsKnown) {
17542                            serializer.startTag(null, TAG_GRANT);
17543                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17544                            pkgGrantsKnown = true;
17545                        }
17546
17547                        final boolean userSet =
17548                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17549                        final boolean userFixed =
17550                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17551                        final boolean revoke =
17552                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17553
17554                        serializer.startTag(null, TAG_PERMISSION);
17555                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17556                        if (isGranted) {
17557                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17558                        }
17559                        if (userSet) {
17560                            serializer.attribute(null, ATTR_USER_SET, "true");
17561                        }
17562                        if (userFixed) {
17563                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17564                        }
17565                        if (revoke) {
17566                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17567                        }
17568                        serializer.endTag(null, TAG_PERMISSION);
17569                    }
17570                }
17571            }
17572
17573            if (pkgGrantsKnown) {
17574                serializer.endTag(null, TAG_GRANT);
17575            }
17576        }
17577
17578        serializer.endTag(null, TAG_ALL_GRANTS);
17579    }
17580
17581    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17582            throws XmlPullParserException, IOException {
17583        String pkgName = null;
17584        int outerDepth = parser.getDepth();
17585        int type;
17586        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17587                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17588            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17589                continue;
17590            }
17591
17592            final String tagName = parser.getName();
17593            if (tagName.equals(TAG_GRANT)) {
17594                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17595                if (DEBUG_BACKUP) {
17596                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17597                }
17598            } else if (tagName.equals(TAG_PERMISSION)) {
17599
17600                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17601                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17602
17603                int newFlagSet = 0;
17604                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17605                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17606                }
17607                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17608                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17609                }
17610                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17611                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17612                }
17613                if (DEBUG_BACKUP) {
17614                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17615                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17616                }
17617                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17618                if (ps != null) {
17619                    // Already installed so we apply the grant immediately
17620                    if (DEBUG_BACKUP) {
17621                        Slog.v(TAG, "        + already installed; applying");
17622                    }
17623                    PermissionsState perms = ps.getPermissionsState();
17624                    BasePermission bp = mSettings.mPermissions.get(permName);
17625                    if (bp != null) {
17626                        if (isGranted) {
17627                            perms.grantRuntimePermission(bp, userId);
17628                        }
17629                        if (newFlagSet != 0) {
17630                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17631                        }
17632                    }
17633                } else {
17634                    // Need to wait for post-restore install to apply the grant
17635                    if (DEBUG_BACKUP) {
17636                        Slog.v(TAG, "        - not yet installed; saving for later");
17637                    }
17638                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17639                            isGranted, newFlagSet, userId);
17640                }
17641            } else {
17642                PackageManagerService.reportSettingsProblem(Log.WARN,
17643                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17644                XmlUtils.skipCurrentTag(parser);
17645            }
17646        }
17647
17648        scheduleWriteSettingsLocked();
17649        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17650    }
17651
17652    @Override
17653    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17654            int sourceUserId, int targetUserId, int flags) {
17655        mContext.enforceCallingOrSelfPermission(
17656                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17657        int callingUid = Binder.getCallingUid();
17658        enforceOwnerRights(ownerPackage, callingUid);
17659        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17660        if (intentFilter.countActions() == 0) {
17661            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17662            return;
17663        }
17664        synchronized (mPackages) {
17665            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17666                    ownerPackage, targetUserId, flags);
17667            CrossProfileIntentResolver resolver =
17668                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17669            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17670            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17671            if (existing != null) {
17672                int size = existing.size();
17673                for (int i = 0; i < size; i++) {
17674                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17675                        return;
17676                    }
17677                }
17678            }
17679            resolver.addFilter(newFilter);
17680            scheduleWritePackageRestrictionsLocked(sourceUserId);
17681        }
17682    }
17683
17684    @Override
17685    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17686        mContext.enforceCallingOrSelfPermission(
17687                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17688        int callingUid = Binder.getCallingUid();
17689        enforceOwnerRights(ownerPackage, callingUid);
17690        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17691        synchronized (mPackages) {
17692            CrossProfileIntentResolver resolver =
17693                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17694            ArraySet<CrossProfileIntentFilter> set =
17695                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17696            for (CrossProfileIntentFilter filter : set) {
17697                if (filter.getOwnerPackage().equals(ownerPackage)) {
17698                    resolver.removeFilter(filter);
17699                }
17700            }
17701            scheduleWritePackageRestrictionsLocked(sourceUserId);
17702        }
17703    }
17704
17705    // Enforcing that callingUid is owning pkg on userId
17706    private void enforceOwnerRights(String pkg, int callingUid) {
17707        // The system owns everything.
17708        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17709            return;
17710        }
17711        int callingUserId = UserHandle.getUserId(callingUid);
17712        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17713        if (pi == null) {
17714            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17715                    + callingUserId);
17716        }
17717        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17718            throw new SecurityException("Calling uid " + callingUid
17719                    + " does not own package " + pkg);
17720        }
17721    }
17722
17723    @Override
17724    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17725        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17726    }
17727
17728    private Intent getHomeIntent() {
17729        Intent intent = new Intent(Intent.ACTION_MAIN);
17730        intent.addCategory(Intent.CATEGORY_HOME);
17731        intent.addCategory(Intent.CATEGORY_DEFAULT);
17732        return intent;
17733    }
17734
17735    private IntentFilter getHomeFilter() {
17736        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17737        filter.addCategory(Intent.CATEGORY_HOME);
17738        filter.addCategory(Intent.CATEGORY_DEFAULT);
17739        return filter;
17740    }
17741
17742    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17743            int userId) {
17744        Intent intent  = getHomeIntent();
17745        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17746                PackageManager.GET_META_DATA, userId);
17747        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17748                true, false, false, userId);
17749
17750        allHomeCandidates.clear();
17751        if (list != null) {
17752            for (ResolveInfo ri : list) {
17753                allHomeCandidates.add(ri);
17754            }
17755        }
17756        return (preferred == null || preferred.activityInfo == null)
17757                ? null
17758                : new ComponentName(preferred.activityInfo.packageName,
17759                        preferred.activityInfo.name);
17760    }
17761
17762    @Override
17763    public void setHomeActivity(ComponentName comp, int userId) {
17764        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17765        getHomeActivitiesAsUser(homeActivities, userId);
17766
17767        boolean found = false;
17768
17769        final int size = homeActivities.size();
17770        final ComponentName[] set = new ComponentName[size];
17771        for (int i = 0; i < size; i++) {
17772            final ResolveInfo candidate = homeActivities.get(i);
17773            final ActivityInfo info = candidate.activityInfo;
17774            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17775            set[i] = activityName;
17776            if (!found && activityName.equals(comp)) {
17777                found = true;
17778            }
17779        }
17780        if (!found) {
17781            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17782                    + userId);
17783        }
17784        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17785                set, comp, userId);
17786    }
17787
17788    private @Nullable String getSetupWizardPackageName() {
17789        final Intent intent = new Intent(Intent.ACTION_MAIN);
17790        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17791
17792        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17793                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17794                        | MATCH_DISABLED_COMPONENTS,
17795                UserHandle.myUserId());
17796        if (matches.size() == 1) {
17797            return matches.get(0).getComponentInfo().packageName;
17798        } else {
17799            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17800                    + ": matches=" + matches);
17801            return null;
17802        }
17803    }
17804
17805    private @Nullable String getStorageManagerPackageName() {
17806        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
17807
17808        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17809                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17810                        | MATCH_DISABLED_COMPONENTS,
17811                UserHandle.myUserId());
17812        if (matches.size() == 1) {
17813            return matches.get(0).getComponentInfo().packageName;
17814        } else {
17815            Slog.e(TAG, "There should probably be exactly one storage manager; found "
17816                    + matches.size() + ": matches=" + matches);
17817            return null;
17818        }
17819    }
17820
17821    @Override
17822    public void setApplicationEnabledSetting(String appPackageName,
17823            int newState, int flags, int userId, String callingPackage) {
17824        if (!sUserManager.exists(userId)) return;
17825        if (callingPackage == null) {
17826            callingPackage = Integer.toString(Binder.getCallingUid());
17827        }
17828        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17829    }
17830
17831    @Override
17832    public void setComponentEnabledSetting(ComponentName componentName,
17833            int newState, int flags, int userId) {
17834        if (!sUserManager.exists(userId)) return;
17835        setEnabledSetting(componentName.getPackageName(),
17836                componentName.getClassName(), newState, flags, userId, null);
17837    }
17838
17839    private void setEnabledSetting(final String packageName, String className, int newState,
17840            final int flags, int userId, String callingPackage) {
17841        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17842              || newState == COMPONENT_ENABLED_STATE_ENABLED
17843              || newState == COMPONENT_ENABLED_STATE_DISABLED
17844              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17845              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17846            throw new IllegalArgumentException("Invalid new component state: "
17847                    + newState);
17848        }
17849        PackageSetting pkgSetting;
17850        final int uid = Binder.getCallingUid();
17851        final int permission;
17852        if (uid == Process.SYSTEM_UID) {
17853            permission = PackageManager.PERMISSION_GRANTED;
17854        } else {
17855            permission = mContext.checkCallingOrSelfPermission(
17856                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17857        }
17858        enforceCrossUserPermission(uid, userId,
17859                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17860        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17861        boolean sendNow = false;
17862        boolean isApp = (className == null);
17863        String componentName = isApp ? packageName : className;
17864        int packageUid = -1;
17865        ArrayList<String> components;
17866
17867        // writer
17868        synchronized (mPackages) {
17869            pkgSetting = mSettings.mPackages.get(packageName);
17870            if (pkgSetting == null) {
17871                if (className == null) {
17872                    throw new IllegalArgumentException("Unknown package: " + packageName);
17873                }
17874                throw new IllegalArgumentException(
17875                        "Unknown component: " + packageName + "/" + className);
17876            }
17877        }
17878
17879        // Limit who can change which apps
17880        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17881            // Don't allow apps that don't have permission to modify other apps
17882            if (!allowedByPermission) {
17883                throw new SecurityException(
17884                        "Permission Denial: attempt to change component state from pid="
17885                        + Binder.getCallingPid()
17886                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17887            }
17888            // Don't allow changing protected packages.
17889            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17890                throw new SecurityException("Cannot disable a protected package: " + packageName);
17891            }
17892        }
17893
17894        synchronized (mPackages) {
17895            if (uid == Process.SHELL_UID) {
17896                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17897                int oldState = pkgSetting.getEnabled(userId);
17898                if (className == null
17899                    &&
17900                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17901                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17902                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17903                    &&
17904                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17905                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17906                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17907                    // ok
17908                } else {
17909                    throw new SecurityException(
17910                            "Shell cannot change component state for " + packageName + "/"
17911                            + className + " to " + newState);
17912                }
17913            }
17914            if (className == null) {
17915                // We're dealing with an application/package level state change
17916                if (pkgSetting.getEnabled(userId) == newState) {
17917                    // Nothing to do
17918                    return;
17919                }
17920                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17921                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17922                    // Don't care about who enables an app.
17923                    callingPackage = null;
17924                }
17925                pkgSetting.setEnabled(newState, userId, callingPackage);
17926                // pkgSetting.pkg.mSetEnabled = newState;
17927            } else {
17928                // We're dealing with a component level state change
17929                // First, verify that this is a valid class name.
17930                PackageParser.Package pkg = pkgSetting.pkg;
17931                if (pkg == null || !pkg.hasComponentClassName(className)) {
17932                    if (pkg != null &&
17933                            pkg.applicationInfo.targetSdkVersion >=
17934                                    Build.VERSION_CODES.JELLY_BEAN) {
17935                        throw new IllegalArgumentException("Component class " + className
17936                                + " does not exist in " + packageName);
17937                    } else {
17938                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17939                                + className + " does not exist in " + packageName);
17940                    }
17941                }
17942                switch (newState) {
17943                case COMPONENT_ENABLED_STATE_ENABLED:
17944                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17945                        return;
17946                    }
17947                    break;
17948                case COMPONENT_ENABLED_STATE_DISABLED:
17949                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17950                        return;
17951                    }
17952                    break;
17953                case COMPONENT_ENABLED_STATE_DEFAULT:
17954                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17955                        return;
17956                    }
17957                    break;
17958                default:
17959                    Slog.e(TAG, "Invalid new component state: " + newState);
17960                    return;
17961                }
17962            }
17963            scheduleWritePackageRestrictionsLocked(userId);
17964            components = mPendingBroadcasts.get(userId, packageName);
17965            final boolean newPackage = components == null;
17966            if (newPackage) {
17967                components = new ArrayList<String>();
17968            }
17969            if (!components.contains(componentName)) {
17970                components.add(componentName);
17971            }
17972            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17973                sendNow = true;
17974                // Purge entry from pending broadcast list if another one exists already
17975                // since we are sending one right away.
17976                mPendingBroadcasts.remove(userId, packageName);
17977            } else {
17978                if (newPackage) {
17979                    mPendingBroadcasts.put(userId, packageName, components);
17980                }
17981                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17982                    // Schedule a message
17983                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17984                }
17985            }
17986        }
17987
17988        long callingId = Binder.clearCallingIdentity();
17989        try {
17990            if (sendNow) {
17991                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17992                sendPackageChangedBroadcast(packageName,
17993                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17994            }
17995        } finally {
17996            Binder.restoreCallingIdentity(callingId);
17997        }
17998    }
17999
18000    @Override
18001    public void flushPackageRestrictionsAsUser(int userId) {
18002        if (!sUserManager.exists(userId)) {
18003            return;
18004        }
18005        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18006                false /* checkShell */, "flushPackageRestrictions");
18007        synchronized (mPackages) {
18008            mSettings.writePackageRestrictionsLPr(userId);
18009            mDirtyUsers.remove(userId);
18010            if (mDirtyUsers.isEmpty()) {
18011                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18012            }
18013        }
18014    }
18015
18016    private void sendPackageChangedBroadcast(String packageName,
18017            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18018        if (DEBUG_INSTALL)
18019            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18020                    + componentNames);
18021        Bundle extras = new Bundle(4);
18022        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18023        String nameList[] = new String[componentNames.size()];
18024        componentNames.toArray(nameList);
18025        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18026        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18027        extras.putInt(Intent.EXTRA_UID, packageUid);
18028        // If this is not reporting a change of the overall package, then only send it
18029        // to registered receivers.  We don't want to launch a swath of apps for every
18030        // little component state change.
18031        final int flags = !componentNames.contains(packageName)
18032                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18033        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18034                new int[] {UserHandle.getUserId(packageUid)});
18035    }
18036
18037    @Override
18038    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18039        if (!sUserManager.exists(userId)) return;
18040        final int uid = Binder.getCallingUid();
18041        final int permission = mContext.checkCallingOrSelfPermission(
18042                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18043        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18044        enforceCrossUserPermission(uid, userId,
18045                true /* requireFullPermission */, true /* checkShell */, "stop package");
18046        // writer
18047        synchronized (mPackages) {
18048            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18049                    allowedByPermission, uid, userId)) {
18050                scheduleWritePackageRestrictionsLocked(userId);
18051            }
18052        }
18053    }
18054
18055    @Override
18056    public String getInstallerPackageName(String packageName) {
18057        // reader
18058        synchronized (mPackages) {
18059            return mSettings.getInstallerPackageNameLPr(packageName);
18060        }
18061    }
18062
18063    public boolean isOrphaned(String packageName) {
18064        // reader
18065        synchronized (mPackages) {
18066            return mSettings.isOrphaned(packageName);
18067        }
18068    }
18069
18070    @Override
18071    public int getApplicationEnabledSetting(String packageName, int userId) {
18072        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18073        int uid = Binder.getCallingUid();
18074        enforceCrossUserPermission(uid, userId,
18075                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18076        // reader
18077        synchronized (mPackages) {
18078            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18079        }
18080    }
18081
18082    @Override
18083    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18084        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18085        int uid = Binder.getCallingUid();
18086        enforceCrossUserPermission(uid, userId,
18087                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18088        // reader
18089        synchronized (mPackages) {
18090            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18091        }
18092    }
18093
18094    @Override
18095    public void enterSafeMode() {
18096        enforceSystemOrRoot("Only the system can request entering safe mode");
18097
18098        if (!mSystemReady) {
18099            mSafeMode = true;
18100        }
18101    }
18102
18103    @Override
18104    public void systemReady() {
18105        mSystemReady = true;
18106
18107        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18108        // disabled after already being started.
18109        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18110                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18111
18112        // Read the compatibilty setting when the system is ready.
18113        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18114                mContext.getContentResolver(),
18115                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18116        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18117        if (DEBUG_SETTINGS) {
18118            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18119        }
18120
18121        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18122
18123        synchronized (mPackages) {
18124            // Verify that all of the preferred activity components actually
18125            // exist.  It is possible for applications to be updated and at
18126            // that point remove a previously declared activity component that
18127            // had been set as a preferred activity.  We try to clean this up
18128            // the next time we encounter that preferred activity, but it is
18129            // possible for the user flow to never be able to return to that
18130            // situation so here we do a sanity check to make sure we haven't
18131            // left any junk around.
18132            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18133            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18134                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18135                removed.clear();
18136                for (PreferredActivity pa : pir.filterSet()) {
18137                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18138                        removed.add(pa);
18139                    }
18140                }
18141                if (removed.size() > 0) {
18142                    for (int r=0; r<removed.size(); r++) {
18143                        PreferredActivity pa = removed.get(r);
18144                        Slog.w(TAG, "Removing dangling preferred activity: "
18145                                + pa.mPref.mComponent);
18146                        pir.removeFilter(pa);
18147                    }
18148                    mSettings.writePackageRestrictionsLPr(
18149                            mSettings.mPreferredActivities.keyAt(i));
18150                }
18151            }
18152
18153            for (int userId : UserManagerService.getInstance().getUserIds()) {
18154                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18155                    grantPermissionsUserIds = ArrayUtils.appendInt(
18156                            grantPermissionsUserIds, userId);
18157                }
18158            }
18159        }
18160        sUserManager.systemReady();
18161
18162        // If we upgraded grant all default permissions before kicking off.
18163        for (int userId : grantPermissionsUserIds) {
18164            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18165        }
18166
18167        // If we did not grant default permissions, we preload from this the
18168        // default permission exceptions lazily to ensure we don't hit the
18169        // disk on a new user creation.
18170        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18171            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18172        }
18173
18174        // Kick off any messages waiting for system ready
18175        if (mPostSystemReadyMessages != null) {
18176            for (Message msg : mPostSystemReadyMessages) {
18177                msg.sendToTarget();
18178            }
18179            mPostSystemReadyMessages = null;
18180        }
18181
18182        // Watch for external volumes that come and go over time
18183        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18184        storage.registerListener(mStorageListener);
18185
18186        mInstallerService.systemReady();
18187        mPackageDexOptimizer.systemReady();
18188
18189        MountServiceInternal mountServiceInternal = LocalServices.getService(
18190                MountServiceInternal.class);
18191        mountServiceInternal.addExternalStoragePolicy(
18192                new MountServiceInternal.ExternalStorageMountPolicy() {
18193            @Override
18194            public int getMountMode(int uid, String packageName) {
18195                if (Process.isIsolated(uid)) {
18196                    return Zygote.MOUNT_EXTERNAL_NONE;
18197                }
18198                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18199                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18200                }
18201                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18202                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18203                }
18204                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18205                    return Zygote.MOUNT_EXTERNAL_READ;
18206                }
18207                return Zygote.MOUNT_EXTERNAL_WRITE;
18208            }
18209
18210            @Override
18211            public boolean hasExternalStorage(int uid, String packageName) {
18212                return true;
18213            }
18214        });
18215
18216        // Now that we're mostly running, clean up stale users and apps
18217        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18218        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18219    }
18220
18221    @Override
18222    public boolean isSafeMode() {
18223        return mSafeMode;
18224    }
18225
18226    @Override
18227    public boolean hasSystemUidErrors() {
18228        return mHasSystemUidErrors;
18229    }
18230
18231    static String arrayToString(int[] array) {
18232        StringBuffer buf = new StringBuffer(128);
18233        buf.append('[');
18234        if (array != null) {
18235            for (int i=0; i<array.length; i++) {
18236                if (i > 0) buf.append(", ");
18237                buf.append(array[i]);
18238            }
18239        }
18240        buf.append(']');
18241        return buf.toString();
18242    }
18243
18244    static class DumpState {
18245        public static final int DUMP_LIBS = 1 << 0;
18246        public static final int DUMP_FEATURES = 1 << 1;
18247        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18248        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18249        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18250        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18251        public static final int DUMP_PERMISSIONS = 1 << 6;
18252        public static final int DUMP_PACKAGES = 1 << 7;
18253        public static final int DUMP_SHARED_USERS = 1 << 8;
18254        public static final int DUMP_MESSAGES = 1 << 9;
18255        public static final int DUMP_PROVIDERS = 1 << 10;
18256        public static final int DUMP_VERIFIERS = 1 << 11;
18257        public static final int DUMP_PREFERRED = 1 << 12;
18258        public static final int DUMP_PREFERRED_XML = 1 << 13;
18259        public static final int DUMP_KEYSETS = 1 << 14;
18260        public static final int DUMP_VERSION = 1 << 15;
18261        public static final int DUMP_INSTALLS = 1 << 16;
18262        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18263        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18264        public static final int DUMP_FROZEN = 1 << 19;
18265        public static final int DUMP_DEXOPT = 1 << 20;
18266        public static final int DUMP_COMPILER_STATS = 1 << 21;
18267
18268        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18269
18270        private int mTypes;
18271
18272        private int mOptions;
18273
18274        private boolean mTitlePrinted;
18275
18276        private SharedUserSetting mSharedUser;
18277
18278        public boolean isDumping(int type) {
18279            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18280                return true;
18281            }
18282
18283            return (mTypes & type) != 0;
18284        }
18285
18286        public void setDump(int type) {
18287            mTypes |= type;
18288        }
18289
18290        public boolean isOptionEnabled(int option) {
18291            return (mOptions & option) != 0;
18292        }
18293
18294        public void setOptionEnabled(int option) {
18295            mOptions |= option;
18296        }
18297
18298        public boolean onTitlePrinted() {
18299            final boolean printed = mTitlePrinted;
18300            mTitlePrinted = true;
18301            return printed;
18302        }
18303
18304        public boolean getTitlePrinted() {
18305            return mTitlePrinted;
18306        }
18307
18308        public void setTitlePrinted(boolean enabled) {
18309            mTitlePrinted = enabled;
18310        }
18311
18312        public SharedUserSetting getSharedUser() {
18313            return mSharedUser;
18314        }
18315
18316        public void setSharedUser(SharedUserSetting user) {
18317            mSharedUser = user;
18318        }
18319    }
18320
18321    @Override
18322    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18323            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18324        (new PackageManagerShellCommand(this)).exec(
18325                this, in, out, err, args, resultReceiver);
18326    }
18327
18328    @Override
18329    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18330        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18331                != PackageManager.PERMISSION_GRANTED) {
18332            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18333                    + Binder.getCallingPid()
18334                    + ", uid=" + Binder.getCallingUid()
18335                    + " without permission "
18336                    + android.Manifest.permission.DUMP);
18337            return;
18338        }
18339
18340        DumpState dumpState = new DumpState();
18341        boolean fullPreferred = false;
18342        boolean checkin = false;
18343
18344        String packageName = null;
18345        ArraySet<String> permissionNames = null;
18346
18347        int opti = 0;
18348        while (opti < args.length) {
18349            String opt = args[opti];
18350            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18351                break;
18352            }
18353            opti++;
18354
18355            if ("-a".equals(opt)) {
18356                // Right now we only know how to print all.
18357            } else if ("-h".equals(opt)) {
18358                pw.println("Package manager dump options:");
18359                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18360                pw.println("    --checkin: dump for a checkin");
18361                pw.println("    -f: print details of intent filters");
18362                pw.println("    -h: print this help");
18363                pw.println("  cmd may be one of:");
18364                pw.println("    l[ibraries]: list known shared libraries");
18365                pw.println("    f[eatures]: list device features");
18366                pw.println("    k[eysets]: print known keysets");
18367                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18368                pw.println("    perm[issions]: dump permissions");
18369                pw.println("    permission [name ...]: dump declaration and use of given permission");
18370                pw.println("    pref[erred]: print preferred package settings");
18371                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18372                pw.println("    prov[iders]: dump content providers");
18373                pw.println("    p[ackages]: dump installed packages");
18374                pw.println("    s[hared-users]: dump shared user IDs");
18375                pw.println("    m[essages]: print collected runtime messages");
18376                pw.println("    v[erifiers]: print package verifier info");
18377                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18378                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18379                pw.println("    version: print database version info");
18380                pw.println("    write: write current settings now");
18381                pw.println("    installs: details about install sessions");
18382                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18383                pw.println("    dexopt: dump dexopt state");
18384                pw.println("    compiler-stats: dump compiler statistics");
18385                pw.println("    <package.name>: info about given package");
18386                return;
18387            } else if ("--checkin".equals(opt)) {
18388                checkin = true;
18389            } else if ("-f".equals(opt)) {
18390                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18391            } else {
18392                pw.println("Unknown argument: " + opt + "; use -h for help");
18393            }
18394        }
18395
18396        // Is the caller requesting to dump a particular piece of data?
18397        if (opti < args.length) {
18398            String cmd = args[opti];
18399            opti++;
18400            // Is this a package name?
18401            if ("android".equals(cmd) || cmd.contains(".")) {
18402                packageName = cmd;
18403                // When dumping a single package, we always dump all of its
18404                // filter information since the amount of data will be reasonable.
18405                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18406            } else if ("check-permission".equals(cmd)) {
18407                if (opti >= args.length) {
18408                    pw.println("Error: check-permission missing permission argument");
18409                    return;
18410                }
18411                String perm = args[opti];
18412                opti++;
18413                if (opti >= args.length) {
18414                    pw.println("Error: check-permission missing package argument");
18415                    return;
18416                }
18417                String pkg = args[opti];
18418                opti++;
18419                int user = UserHandle.getUserId(Binder.getCallingUid());
18420                if (opti < args.length) {
18421                    try {
18422                        user = Integer.parseInt(args[opti]);
18423                    } catch (NumberFormatException e) {
18424                        pw.println("Error: check-permission user argument is not a number: "
18425                                + args[opti]);
18426                        return;
18427                    }
18428                }
18429                pw.println(checkPermission(perm, pkg, user));
18430                return;
18431            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18432                dumpState.setDump(DumpState.DUMP_LIBS);
18433            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18434                dumpState.setDump(DumpState.DUMP_FEATURES);
18435            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18436                if (opti >= args.length) {
18437                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18438                            | DumpState.DUMP_SERVICE_RESOLVERS
18439                            | DumpState.DUMP_RECEIVER_RESOLVERS
18440                            | DumpState.DUMP_CONTENT_RESOLVERS);
18441                } else {
18442                    while (opti < args.length) {
18443                        String name = args[opti];
18444                        if ("a".equals(name) || "activity".equals(name)) {
18445                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18446                        } else if ("s".equals(name) || "service".equals(name)) {
18447                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18448                        } else if ("r".equals(name) || "receiver".equals(name)) {
18449                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18450                        } else if ("c".equals(name) || "content".equals(name)) {
18451                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18452                        } else {
18453                            pw.println("Error: unknown resolver table type: " + name);
18454                            return;
18455                        }
18456                        opti++;
18457                    }
18458                }
18459            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18460                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18461            } else if ("permission".equals(cmd)) {
18462                if (opti >= args.length) {
18463                    pw.println("Error: permission requires permission name");
18464                    return;
18465                }
18466                permissionNames = new ArraySet<>();
18467                while (opti < args.length) {
18468                    permissionNames.add(args[opti]);
18469                    opti++;
18470                }
18471                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18472                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18473            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18474                dumpState.setDump(DumpState.DUMP_PREFERRED);
18475            } else if ("preferred-xml".equals(cmd)) {
18476                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18477                if (opti < args.length && "--full".equals(args[opti])) {
18478                    fullPreferred = true;
18479                    opti++;
18480                }
18481            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18482                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18483            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18484                dumpState.setDump(DumpState.DUMP_PACKAGES);
18485            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18486                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18487            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18488                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18489            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18490                dumpState.setDump(DumpState.DUMP_MESSAGES);
18491            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18492                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18493            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18494                    || "intent-filter-verifiers".equals(cmd)) {
18495                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18496            } else if ("version".equals(cmd)) {
18497                dumpState.setDump(DumpState.DUMP_VERSION);
18498            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18499                dumpState.setDump(DumpState.DUMP_KEYSETS);
18500            } else if ("installs".equals(cmd)) {
18501                dumpState.setDump(DumpState.DUMP_INSTALLS);
18502            } else if ("frozen".equals(cmd)) {
18503                dumpState.setDump(DumpState.DUMP_FROZEN);
18504            } else if ("dexopt".equals(cmd)) {
18505                dumpState.setDump(DumpState.DUMP_DEXOPT);
18506            } else if ("compiler-stats".equals(cmd)) {
18507                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18508            } else if ("write".equals(cmd)) {
18509                synchronized (mPackages) {
18510                    mSettings.writeLPr();
18511                    pw.println("Settings written.");
18512                    return;
18513                }
18514            }
18515        }
18516
18517        if (checkin) {
18518            pw.println("vers,1");
18519        }
18520
18521        // reader
18522        synchronized (mPackages) {
18523            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18524                if (!checkin) {
18525                    if (dumpState.onTitlePrinted())
18526                        pw.println();
18527                    pw.println("Database versions:");
18528                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18529                }
18530            }
18531
18532            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18533                if (!checkin) {
18534                    if (dumpState.onTitlePrinted())
18535                        pw.println();
18536                    pw.println("Verifiers:");
18537                    pw.print("  Required: ");
18538                    pw.print(mRequiredVerifierPackage);
18539                    pw.print(" (uid=");
18540                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18541                            UserHandle.USER_SYSTEM));
18542                    pw.println(")");
18543                } else if (mRequiredVerifierPackage != null) {
18544                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18545                    pw.print(",");
18546                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18547                            UserHandle.USER_SYSTEM));
18548                }
18549            }
18550
18551            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18552                    packageName == null) {
18553                if (mIntentFilterVerifierComponent != null) {
18554                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18555                    if (!checkin) {
18556                        if (dumpState.onTitlePrinted())
18557                            pw.println();
18558                        pw.println("Intent Filter Verifier:");
18559                        pw.print("  Using: ");
18560                        pw.print(verifierPackageName);
18561                        pw.print(" (uid=");
18562                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18563                                UserHandle.USER_SYSTEM));
18564                        pw.println(")");
18565                    } else if (verifierPackageName != null) {
18566                        pw.print("ifv,"); pw.print(verifierPackageName);
18567                        pw.print(",");
18568                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18569                                UserHandle.USER_SYSTEM));
18570                    }
18571                } else {
18572                    pw.println();
18573                    pw.println("No Intent Filter Verifier available!");
18574                }
18575            }
18576
18577            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18578                boolean printedHeader = false;
18579                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18580                while (it.hasNext()) {
18581                    String name = it.next();
18582                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18583                    if (!checkin) {
18584                        if (!printedHeader) {
18585                            if (dumpState.onTitlePrinted())
18586                                pw.println();
18587                            pw.println("Libraries:");
18588                            printedHeader = true;
18589                        }
18590                        pw.print("  ");
18591                    } else {
18592                        pw.print("lib,");
18593                    }
18594                    pw.print(name);
18595                    if (!checkin) {
18596                        pw.print(" -> ");
18597                    }
18598                    if (ent.path != null) {
18599                        if (!checkin) {
18600                            pw.print("(jar) ");
18601                            pw.print(ent.path);
18602                        } else {
18603                            pw.print(",jar,");
18604                            pw.print(ent.path);
18605                        }
18606                    } else {
18607                        if (!checkin) {
18608                            pw.print("(apk) ");
18609                            pw.print(ent.apk);
18610                        } else {
18611                            pw.print(",apk,");
18612                            pw.print(ent.apk);
18613                        }
18614                    }
18615                    pw.println();
18616                }
18617            }
18618
18619            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18620                if (dumpState.onTitlePrinted())
18621                    pw.println();
18622                if (!checkin) {
18623                    pw.println("Features:");
18624                }
18625
18626                for (FeatureInfo feat : mAvailableFeatures.values()) {
18627                    if (checkin) {
18628                        pw.print("feat,");
18629                        pw.print(feat.name);
18630                        pw.print(",");
18631                        pw.println(feat.version);
18632                    } else {
18633                        pw.print("  ");
18634                        pw.print(feat.name);
18635                        if (feat.version > 0) {
18636                            pw.print(" version=");
18637                            pw.print(feat.version);
18638                        }
18639                        pw.println();
18640                    }
18641                }
18642            }
18643
18644            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18645                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18646                        : "Activity Resolver Table:", "  ", packageName,
18647                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18648                    dumpState.setTitlePrinted(true);
18649                }
18650            }
18651            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18652                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18653                        : "Receiver Resolver Table:", "  ", packageName,
18654                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18655                    dumpState.setTitlePrinted(true);
18656                }
18657            }
18658            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18659                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18660                        : "Service Resolver Table:", "  ", packageName,
18661                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18662                    dumpState.setTitlePrinted(true);
18663                }
18664            }
18665            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18666                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18667                        : "Provider Resolver Table:", "  ", packageName,
18668                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18669                    dumpState.setTitlePrinted(true);
18670                }
18671            }
18672
18673            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18674                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18675                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18676                    int user = mSettings.mPreferredActivities.keyAt(i);
18677                    if (pir.dump(pw,
18678                            dumpState.getTitlePrinted()
18679                                ? "\nPreferred Activities User " + user + ":"
18680                                : "Preferred Activities User " + user + ":", "  ",
18681                            packageName, true, false)) {
18682                        dumpState.setTitlePrinted(true);
18683                    }
18684                }
18685            }
18686
18687            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18688                pw.flush();
18689                FileOutputStream fout = new FileOutputStream(fd);
18690                BufferedOutputStream str = new BufferedOutputStream(fout);
18691                XmlSerializer serializer = new FastXmlSerializer();
18692                try {
18693                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18694                    serializer.startDocument(null, true);
18695                    serializer.setFeature(
18696                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18697                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18698                    serializer.endDocument();
18699                    serializer.flush();
18700                } catch (IllegalArgumentException e) {
18701                    pw.println("Failed writing: " + e);
18702                } catch (IllegalStateException e) {
18703                    pw.println("Failed writing: " + e);
18704                } catch (IOException e) {
18705                    pw.println("Failed writing: " + e);
18706                }
18707            }
18708
18709            if (!checkin
18710                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18711                    && packageName == null) {
18712                pw.println();
18713                int count = mSettings.mPackages.size();
18714                if (count == 0) {
18715                    pw.println("No applications!");
18716                    pw.println();
18717                } else {
18718                    final String prefix = "  ";
18719                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18720                    if (allPackageSettings.size() == 0) {
18721                        pw.println("No domain preferred apps!");
18722                        pw.println();
18723                    } else {
18724                        pw.println("App verification status:");
18725                        pw.println();
18726                        count = 0;
18727                        for (PackageSetting ps : allPackageSettings) {
18728                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18729                            if (ivi == null || ivi.getPackageName() == null) continue;
18730                            pw.println(prefix + "Package: " + ivi.getPackageName());
18731                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18732                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18733                            pw.println();
18734                            count++;
18735                        }
18736                        if (count == 0) {
18737                            pw.println(prefix + "No app verification established.");
18738                            pw.println();
18739                        }
18740                        for (int userId : sUserManager.getUserIds()) {
18741                            pw.println("App linkages for user " + userId + ":");
18742                            pw.println();
18743                            count = 0;
18744                            for (PackageSetting ps : allPackageSettings) {
18745                                final long status = ps.getDomainVerificationStatusForUser(userId);
18746                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18747                                    continue;
18748                                }
18749                                pw.println(prefix + "Package: " + ps.name);
18750                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18751                                String statusStr = IntentFilterVerificationInfo.
18752                                        getStatusStringFromValue(status);
18753                                pw.println(prefix + "Status:  " + statusStr);
18754                                pw.println();
18755                                count++;
18756                            }
18757                            if (count == 0) {
18758                                pw.println(prefix + "No configured app linkages.");
18759                                pw.println();
18760                            }
18761                        }
18762                    }
18763                }
18764            }
18765
18766            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18767                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18768                if (packageName == null && permissionNames == null) {
18769                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18770                        if (iperm == 0) {
18771                            if (dumpState.onTitlePrinted())
18772                                pw.println();
18773                            pw.println("AppOp Permissions:");
18774                        }
18775                        pw.print("  AppOp Permission ");
18776                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18777                        pw.println(":");
18778                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18779                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18780                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18781                        }
18782                    }
18783                }
18784            }
18785
18786            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18787                boolean printedSomething = false;
18788                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18789                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18790                        continue;
18791                    }
18792                    if (!printedSomething) {
18793                        if (dumpState.onTitlePrinted())
18794                            pw.println();
18795                        pw.println("Registered ContentProviders:");
18796                        printedSomething = true;
18797                    }
18798                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18799                    pw.print("    "); pw.println(p.toString());
18800                }
18801                printedSomething = false;
18802                for (Map.Entry<String, PackageParser.Provider> entry :
18803                        mProvidersByAuthority.entrySet()) {
18804                    PackageParser.Provider p = entry.getValue();
18805                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18806                        continue;
18807                    }
18808                    if (!printedSomething) {
18809                        if (dumpState.onTitlePrinted())
18810                            pw.println();
18811                        pw.println("ContentProvider Authorities:");
18812                        printedSomething = true;
18813                    }
18814                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18815                    pw.print("    "); pw.println(p.toString());
18816                    if (p.info != null && p.info.applicationInfo != null) {
18817                        final String appInfo = p.info.applicationInfo.toString();
18818                        pw.print("      applicationInfo="); pw.println(appInfo);
18819                    }
18820                }
18821            }
18822
18823            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18824                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18825            }
18826
18827            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18828                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18829            }
18830
18831            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18832                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18833            }
18834
18835            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18836                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18837            }
18838
18839            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18840                // XXX should handle packageName != null by dumping only install data that
18841                // the given package is involved with.
18842                if (dumpState.onTitlePrinted()) pw.println();
18843                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18844            }
18845
18846            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18847                // XXX should handle packageName != null by dumping only install data that
18848                // the given package is involved with.
18849                if (dumpState.onTitlePrinted()) pw.println();
18850
18851                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18852                ipw.println();
18853                ipw.println("Frozen packages:");
18854                ipw.increaseIndent();
18855                if (mFrozenPackages.size() == 0) {
18856                    ipw.println("(none)");
18857                } else {
18858                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18859                        ipw.println(mFrozenPackages.valueAt(i));
18860                    }
18861                }
18862                ipw.decreaseIndent();
18863            }
18864
18865            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18866                if (dumpState.onTitlePrinted()) pw.println();
18867                dumpDexoptStateLPr(pw, packageName);
18868            }
18869
18870            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
18871                if (dumpState.onTitlePrinted()) pw.println();
18872                dumpCompilerStatsLPr(pw, packageName);
18873            }
18874
18875            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18876                if (dumpState.onTitlePrinted()) pw.println();
18877                mSettings.dumpReadMessagesLPr(pw, dumpState);
18878
18879                pw.println();
18880                pw.println("Package warning messages:");
18881                BufferedReader in = null;
18882                String line = null;
18883                try {
18884                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18885                    while ((line = in.readLine()) != null) {
18886                        if (line.contains("ignored: updated version")) continue;
18887                        pw.println(line);
18888                    }
18889                } catch (IOException ignored) {
18890                } finally {
18891                    IoUtils.closeQuietly(in);
18892                }
18893            }
18894
18895            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18896                BufferedReader in = null;
18897                String line = null;
18898                try {
18899                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18900                    while ((line = in.readLine()) != null) {
18901                        if (line.contains("ignored: updated version")) continue;
18902                        pw.print("msg,");
18903                        pw.println(line);
18904                    }
18905                } catch (IOException ignored) {
18906                } finally {
18907                    IoUtils.closeQuietly(in);
18908                }
18909            }
18910        }
18911    }
18912
18913    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18914        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18915        ipw.println();
18916        ipw.println("Dexopt state:");
18917        ipw.increaseIndent();
18918        Collection<PackageParser.Package> packages = null;
18919        if (packageName != null) {
18920            PackageParser.Package targetPackage = mPackages.get(packageName);
18921            if (targetPackage != null) {
18922                packages = Collections.singletonList(targetPackage);
18923            } else {
18924                ipw.println("Unable to find package: " + packageName);
18925                return;
18926            }
18927        } else {
18928            packages = mPackages.values();
18929        }
18930
18931        for (PackageParser.Package pkg : packages) {
18932            ipw.println("[" + pkg.packageName + "]");
18933            ipw.increaseIndent();
18934            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18935            ipw.decreaseIndent();
18936        }
18937    }
18938
18939    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
18940        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18941        ipw.println();
18942        ipw.println("Compiler stats:");
18943        ipw.increaseIndent();
18944        Collection<PackageParser.Package> packages = null;
18945        if (packageName != null) {
18946            PackageParser.Package targetPackage = mPackages.get(packageName);
18947            if (targetPackage != null) {
18948                packages = Collections.singletonList(targetPackage);
18949            } else {
18950                ipw.println("Unable to find package: " + packageName);
18951                return;
18952            }
18953        } else {
18954            packages = mPackages.values();
18955        }
18956
18957        for (PackageParser.Package pkg : packages) {
18958            ipw.println("[" + pkg.packageName + "]");
18959            ipw.increaseIndent();
18960
18961            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
18962            if (stats == null) {
18963                ipw.println("(No recorded stats)");
18964            } else {
18965                stats.dump(ipw);
18966            }
18967            ipw.decreaseIndent();
18968        }
18969    }
18970
18971    private String dumpDomainString(String packageName) {
18972        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18973                .getList();
18974        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18975
18976        ArraySet<String> result = new ArraySet<>();
18977        if (iviList.size() > 0) {
18978            for (IntentFilterVerificationInfo ivi : iviList) {
18979                for (String host : ivi.getDomains()) {
18980                    result.add(host);
18981                }
18982            }
18983        }
18984        if (filters != null && filters.size() > 0) {
18985            for (IntentFilter filter : filters) {
18986                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18987                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18988                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18989                    result.addAll(filter.getHostsList());
18990                }
18991            }
18992        }
18993
18994        StringBuilder sb = new StringBuilder(result.size() * 16);
18995        for (String domain : result) {
18996            if (sb.length() > 0) sb.append(" ");
18997            sb.append(domain);
18998        }
18999        return sb.toString();
19000    }
19001
19002    // ------- apps on sdcard specific code -------
19003    static final boolean DEBUG_SD_INSTALL = false;
19004
19005    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19006
19007    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19008
19009    private boolean mMediaMounted = false;
19010
19011    static String getEncryptKey() {
19012        try {
19013            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19014                    SD_ENCRYPTION_KEYSTORE_NAME);
19015            if (sdEncKey == null) {
19016                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19017                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19018                if (sdEncKey == null) {
19019                    Slog.e(TAG, "Failed to create encryption keys");
19020                    return null;
19021                }
19022            }
19023            return sdEncKey;
19024        } catch (NoSuchAlgorithmException nsae) {
19025            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19026            return null;
19027        } catch (IOException ioe) {
19028            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19029            return null;
19030        }
19031    }
19032
19033    /*
19034     * Update media status on PackageManager.
19035     */
19036    @Override
19037    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19038        int callingUid = Binder.getCallingUid();
19039        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19040            throw new SecurityException("Media status can only be updated by the system");
19041        }
19042        // reader; this apparently protects mMediaMounted, but should probably
19043        // be a different lock in that case.
19044        synchronized (mPackages) {
19045            Log.i(TAG, "Updating external media status from "
19046                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19047                    + (mediaStatus ? "mounted" : "unmounted"));
19048            if (DEBUG_SD_INSTALL)
19049                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19050                        + ", mMediaMounted=" + mMediaMounted);
19051            if (mediaStatus == mMediaMounted) {
19052                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19053                        : 0, -1);
19054                mHandler.sendMessage(msg);
19055                return;
19056            }
19057            mMediaMounted = mediaStatus;
19058        }
19059        // Queue up an async operation since the package installation may take a
19060        // little while.
19061        mHandler.post(new Runnable() {
19062            public void run() {
19063                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19064            }
19065        });
19066    }
19067
19068    /**
19069     * Called by MountService when the initial ASECs to scan are available.
19070     * Should block until all the ASEC containers are finished being scanned.
19071     */
19072    public void scanAvailableAsecs() {
19073        updateExternalMediaStatusInner(true, false, false);
19074    }
19075
19076    /*
19077     * Collect information of applications on external media, map them against
19078     * existing containers and update information based on current mount status.
19079     * Please note that we always have to report status if reportStatus has been
19080     * set to true especially when unloading packages.
19081     */
19082    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19083            boolean externalStorage) {
19084        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19085        int[] uidArr = EmptyArray.INT;
19086
19087        final String[] list = PackageHelper.getSecureContainerList();
19088        if (ArrayUtils.isEmpty(list)) {
19089            Log.i(TAG, "No secure containers found");
19090        } else {
19091            // Process list of secure containers and categorize them
19092            // as active or stale based on their package internal state.
19093
19094            // reader
19095            synchronized (mPackages) {
19096                for (String cid : list) {
19097                    // Leave stages untouched for now; installer service owns them
19098                    if (PackageInstallerService.isStageName(cid)) continue;
19099
19100                    if (DEBUG_SD_INSTALL)
19101                        Log.i(TAG, "Processing container " + cid);
19102                    String pkgName = getAsecPackageName(cid);
19103                    if (pkgName == null) {
19104                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19105                        continue;
19106                    }
19107                    if (DEBUG_SD_INSTALL)
19108                        Log.i(TAG, "Looking for pkg : " + pkgName);
19109
19110                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19111                    if (ps == null) {
19112                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19113                        continue;
19114                    }
19115
19116                    /*
19117                     * Skip packages that are not external if we're unmounting
19118                     * external storage.
19119                     */
19120                    if (externalStorage && !isMounted && !isExternal(ps)) {
19121                        continue;
19122                    }
19123
19124                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19125                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19126                    // The package status is changed only if the code path
19127                    // matches between settings and the container id.
19128                    if (ps.codePathString != null
19129                            && ps.codePathString.startsWith(args.getCodePath())) {
19130                        if (DEBUG_SD_INSTALL) {
19131                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19132                                    + " at code path: " + ps.codePathString);
19133                        }
19134
19135                        // We do have a valid package installed on sdcard
19136                        processCids.put(args, ps.codePathString);
19137                        final int uid = ps.appId;
19138                        if (uid != -1) {
19139                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19140                        }
19141                    } else {
19142                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19143                                + ps.codePathString);
19144                    }
19145                }
19146            }
19147
19148            Arrays.sort(uidArr);
19149        }
19150
19151        // Process packages with valid entries.
19152        if (isMounted) {
19153            if (DEBUG_SD_INSTALL)
19154                Log.i(TAG, "Loading packages");
19155            loadMediaPackages(processCids, uidArr, externalStorage);
19156            startCleaningPackages();
19157            mInstallerService.onSecureContainersAvailable();
19158        } else {
19159            if (DEBUG_SD_INSTALL)
19160                Log.i(TAG, "Unloading packages");
19161            unloadMediaPackages(processCids, uidArr, reportStatus);
19162        }
19163    }
19164
19165    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19166            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19167        final int size = infos.size();
19168        final String[] packageNames = new String[size];
19169        final int[] packageUids = new int[size];
19170        for (int i = 0; i < size; i++) {
19171            final ApplicationInfo info = infos.get(i);
19172            packageNames[i] = info.packageName;
19173            packageUids[i] = info.uid;
19174        }
19175        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19176                finishedReceiver);
19177    }
19178
19179    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19180            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19181        sendResourcesChangedBroadcast(mediaStatus, replacing,
19182                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19183    }
19184
19185    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19186            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19187        int size = pkgList.length;
19188        if (size > 0) {
19189            // Send broadcasts here
19190            Bundle extras = new Bundle();
19191            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19192            if (uidArr != null) {
19193                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19194            }
19195            if (replacing) {
19196                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19197            }
19198            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19199                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19200            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19201        }
19202    }
19203
19204   /*
19205     * Look at potentially valid container ids from processCids If package
19206     * information doesn't match the one on record or package scanning fails,
19207     * the cid is added to list of removeCids. We currently don't delete stale
19208     * containers.
19209     */
19210    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19211            boolean externalStorage) {
19212        ArrayList<String> pkgList = new ArrayList<String>();
19213        Set<AsecInstallArgs> keys = processCids.keySet();
19214
19215        for (AsecInstallArgs args : keys) {
19216            String codePath = processCids.get(args);
19217            if (DEBUG_SD_INSTALL)
19218                Log.i(TAG, "Loading container : " + args.cid);
19219            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19220            try {
19221                // Make sure there are no container errors first.
19222                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19223                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19224                            + " when installing from sdcard");
19225                    continue;
19226                }
19227                // Check code path here.
19228                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19229                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19230                            + " does not match one in settings " + codePath);
19231                    continue;
19232                }
19233                // Parse package
19234                int parseFlags = mDefParseFlags;
19235                if (args.isExternalAsec()) {
19236                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19237                }
19238                if (args.isFwdLocked()) {
19239                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19240                }
19241
19242                synchronized (mInstallLock) {
19243                    PackageParser.Package pkg = null;
19244                    try {
19245                        // Sadly we don't know the package name yet to freeze it
19246                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19247                                SCAN_IGNORE_FROZEN, 0, null);
19248                    } catch (PackageManagerException e) {
19249                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19250                    }
19251                    // Scan the package
19252                    if (pkg != null) {
19253                        /*
19254                         * TODO why is the lock being held? doPostInstall is
19255                         * called in other places without the lock. This needs
19256                         * to be straightened out.
19257                         */
19258                        // writer
19259                        synchronized (mPackages) {
19260                            retCode = PackageManager.INSTALL_SUCCEEDED;
19261                            pkgList.add(pkg.packageName);
19262                            // Post process args
19263                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19264                                    pkg.applicationInfo.uid);
19265                        }
19266                    } else {
19267                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19268                    }
19269                }
19270
19271            } finally {
19272                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19273                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19274                }
19275            }
19276        }
19277        // writer
19278        synchronized (mPackages) {
19279            // If the platform SDK has changed since the last time we booted,
19280            // we need to re-grant app permission to catch any new ones that
19281            // appear. This is really a hack, and means that apps can in some
19282            // cases get permissions that the user didn't initially explicitly
19283            // allow... it would be nice to have some better way to handle
19284            // this situation.
19285            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19286                    : mSettings.getInternalVersion();
19287            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19288                    : StorageManager.UUID_PRIVATE_INTERNAL;
19289
19290            int updateFlags = UPDATE_PERMISSIONS_ALL;
19291            if (ver.sdkVersion != mSdkVersion) {
19292                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19293                        + mSdkVersion + "; regranting permissions for external");
19294                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19295            }
19296            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19297
19298            // Yay, everything is now upgraded
19299            ver.forceCurrent();
19300
19301            // can downgrade to reader
19302            // Persist settings
19303            mSettings.writeLPr();
19304        }
19305        // Send a broadcast to let everyone know we are done processing
19306        if (pkgList.size() > 0) {
19307            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19308        }
19309    }
19310
19311   /*
19312     * Utility method to unload a list of specified containers
19313     */
19314    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19315        // Just unmount all valid containers.
19316        for (AsecInstallArgs arg : cidArgs) {
19317            synchronized (mInstallLock) {
19318                arg.doPostDeleteLI(false);
19319           }
19320       }
19321   }
19322
19323    /*
19324     * Unload packages mounted on external media. This involves deleting package
19325     * data from internal structures, sending broadcasts about disabled packages,
19326     * gc'ing to free up references, unmounting all secure containers
19327     * corresponding to packages on external media, and posting a
19328     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19329     * that we always have to post this message if status has been requested no
19330     * matter what.
19331     */
19332    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19333            final boolean reportStatus) {
19334        if (DEBUG_SD_INSTALL)
19335            Log.i(TAG, "unloading media packages");
19336        ArrayList<String> pkgList = new ArrayList<String>();
19337        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19338        final Set<AsecInstallArgs> keys = processCids.keySet();
19339        for (AsecInstallArgs args : keys) {
19340            String pkgName = args.getPackageName();
19341            if (DEBUG_SD_INSTALL)
19342                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19343            // Delete package internally
19344            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19345            synchronized (mInstallLock) {
19346                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19347                final boolean res;
19348                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19349                        "unloadMediaPackages")) {
19350                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19351                            null);
19352                }
19353                if (res) {
19354                    pkgList.add(pkgName);
19355                } else {
19356                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19357                    failedList.add(args);
19358                }
19359            }
19360        }
19361
19362        // reader
19363        synchronized (mPackages) {
19364            // We didn't update the settings after removing each package;
19365            // write them now for all packages.
19366            mSettings.writeLPr();
19367        }
19368
19369        // We have to absolutely send UPDATED_MEDIA_STATUS only
19370        // after confirming that all the receivers processed the ordered
19371        // broadcast when packages get disabled, force a gc to clean things up.
19372        // and unload all the containers.
19373        if (pkgList.size() > 0) {
19374            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19375                    new IIntentReceiver.Stub() {
19376                public void performReceive(Intent intent, int resultCode, String data,
19377                        Bundle extras, boolean ordered, boolean sticky,
19378                        int sendingUser) throws RemoteException {
19379                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19380                            reportStatus ? 1 : 0, 1, keys);
19381                    mHandler.sendMessage(msg);
19382                }
19383            });
19384        } else {
19385            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19386                    keys);
19387            mHandler.sendMessage(msg);
19388        }
19389    }
19390
19391    private void loadPrivatePackages(final VolumeInfo vol) {
19392        mHandler.post(new Runnable() {
19393            @Override
19394            public void run() {
19395                loadPrivatePackagesInner(vol);
19396            }
19397        });
19398    }
19399
19400    private void loadPrivatePackagesInner(VolumeInfo vol) {
19401        final String volumeUuid = vol.fsUuid;
19402        if (TextUtils.isEmpty(volumeUuid)) {
19403            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19404            return;
19405        }
19406
19407        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19408        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19409        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19410
19411        final VersionInfo ver;
19412        final List<PackageSetting> packages;
19413        synchronized (mPackages) {
19414            ver = mSettings.findOrCreateVersion(volumeUuid);
19415            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19416        }
19417
19418        for (PackageSetting ps : packages) {
19419            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19420            synchronized (mInstallLock) {
19421                final PackageParser.Package pkg;
19422                try {
19423                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19424                    loaded.add(pkg.applicationInfo);
19425
19426                } catch (PackageManagerException e) {
19427                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19428                }
19429
19430                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19431                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19432                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19433                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19434                }
19435            }
19436        }
19437
19438        // Reconcile app data for all started/unlocked users
19439        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19440        final UserManager um = mContext.getSystemService(UserManager.class);
19441        UserManagerInternal umInternal = getUserManagerInternal();
19442        for (UserInfo user : um.getUsers()) {
19443            final int flags;
19444            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19445                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19446            } else if (umInternal.isUserRunning(user.id)) {
19447                flags = StorageManager.FLAG_STORAGE_DE;
19448            } else {
19449                continue;
19450            }
19451
19452            try {
19453                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19454                synchronized (mInstallLock) {
19455                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19456                }
19457            } catch (IllegalStateException e) {
19458                // Device was probably ejected, and we'll process that event momentarily
19459                Slog.w(TAG, "Failed to prepare storage: " + e);
19460            }
19461        }
19462
19463        synchronized (mPackages) {
19464            int updateFlags = UPDATE_PERMISSIONS_ALL;
19465            if (ver.sdkVersion != mSdkVersion) {
19466                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19467                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19468                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19469            }
19470            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19471
19472            // Yay, everything is now upgraded
19473            ver.forceCurrent();
19474
19475            mSettings.writeLPr();
19476        }
19477
19478        for (PackageFreezer freezer : freezers) {
19479            freezer.close();
19480        }
19481
19482        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19483        sendResourcesChangedBroadcast(true, false, loaded, null);
19484    }
19485
19486    private void unloadPrivatePackages(final VolumeInfo vol) {
19487        mHandler.post(new Runnable() {
19488            @Override
19489            public void run() {
19490                unloadPrivatePackagesInner(vol);
19491            }
19492        });
19493    }
19494
19495    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19496        final String volumeUuid = vol.fsUuid;
19497        if (TextUtils.isEmpty(volumeUuid)) {
19498            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19499            return;
19500        }
19501
19502        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19503        synchronized (mInstallLock) {
19504        synchronized (mPackages) {
19505            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19506            for (PackageSetting ps : packages) {
19507                if (ps.pkg == null) continue;
19508
19509                final ApplicationInfo info = ps.pkg.applicationInfo;
19510                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19511                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19512
19513                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19514                        "unloadPrivatePackagesInner")) {
19515                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19516                            false, null)) {
19517                        unloaded.add(info);
19518                    } else {
19519                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19520                    }
19521                }
19522
19523                // Try very hard to release any references to this package
19524                // so we don't risk the system server being killed due to
19525                // open FDs
19526                AttributeCache.instance().removePackage(ps.name);
19527            }
19528
19529            mSettings.writeLPr();
19530        }
19531        }
19532
19533        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19534        sendResourcesChangedBroadcast(false, false, unloaded, null);
19535
19536        // Try very hard to release any references to this path so we don't risk
19537        // the system server being killed due to open FDs
19538        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19539
19540        for (int i = 0; i < 3; i++) {
19541            System.gc();
19542            System.runFinalization();
19543        }
19544    }
19545
19546    /**
19547     * Prepare storage areas for given user on all mounted devices.
19548     */
19549    void prepareUserData(int userId, int userSerial, int flags) {
19550        synchronized (mInstallLock) {
19551            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19552            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19553                final String volumeUuid = vol.getFsUuid();
19554                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19555            }
19556        }
19557    }
19558
19559    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19560            boolean allowRecover) {
19561        // Prepare storage and verify that serial numbers are consistent; if
19562        // there's a mismatch we need to destroy to avoid leaking data
19563        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19564        try {
19565            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19566
19567            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19568                UserManagerService.enforceSerialNumber(
19569                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19570                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19571                    UserManagerService.enforceSerialNumber(
19572                            Environment.getDataSystemDeDirectory(userId), userSerial);
19573                }
19574            }
19575            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19576                UserManagerService.enforceSerialNumber(
19577                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19578                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19579                    UserManagerService.enforceSerialNumber(
19580                            Environment.getDataSystemCeDirectory(userId), userSerial);
19581                }
19582            }
19583
19584            synchronized (mInstallLock) {
19585                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19586            }
19587        } catch (Exception e) {
19588            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19589                    + " because we failed to prepare: " + e);
19590            destroyUserDataLI(volumeUuid, userId,
19591                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19592
19593            if (allowRecover) {
19594                // Try one last time; if we fail again we're really in trouble
19595                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19596            }
19597        }
19598    }
19599
19600    /**
19601     * Destroy storage areas for given user on all mounted devices.
19602     */
19603    void destroyUserData(int userId, int flags) {
19604        synchronized (mInstallLock) {
19605            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19606            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19607                final String volumeUuid = vol.getFsUuid();
19608                destroyUserDataLI(volumeUuid, userId, flags);
19609            }
19610        }
19611    }
19612
19613    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19614        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19615        try {
19616            // Clean up app data, profile data, and media data
19617            mInstaller.destroyUserData(volumeUuid, userId, flags);
19618
19619            // Clean up system data
19620            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19621                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19622                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19623                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19624                }
19625                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19626                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19627                }
19628            }
19629
19630            // Data with special labels is now gone, so finish the job
19631            storage.destroyUserStorage(volumeUuid, userId, flags);
19632
19633        } catch (Exception e) {
19634            logCriticalInfo(Log.WARN,
19635                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19636        }
19637    }
19638
19639    /**
19640     * Examine all users present on given mounted volume, and destroy data
19641     * belonging to users that are no longer valid, or whose user ID has been
19642     * recycled.
19643     */
19644    private void reconcileUsers(String volumeUuid) {
19645        final List<File> files = new ArrayList<>();
19646        Collections.addAll(files, FileUtils
19647                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19648        Collections.addAll(files, FileUtils
19649                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19650        Collections.addAll(files, FileUtils
19651                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19652        Collections.addAll(files, FileUtils
19653                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19654        for (File file : files) {
19655            if (!file.isDirectory()) continue;
19656
19657            final int userId;
19658            final UserInfo info;
19659            try {
19660                userId = Integer.parseInt(file.getName());
19661                info = sUserManager.getUserInfo(userId);
19662            } catch (NumberFormatException e) {
19663                Slog.w(TAG, "Invalid user directory " + file);
19664                continue;
19665            }
19666
19667            boolean destroyUser = false;
19668            if (info == null) {
19669                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19670                        + " because no matching user was found");
19671                destroyUser = true;
19672            } else if (!mOnlyCore) {
19673                try {
19674                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19675                } catch (IOException e) {
19676                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19677                            + " because we failed to enforce serial number: " + e);
19678                    destroyUser = true;
19679                }
19680            }
19681
19682            if (destroyUser) {
19683                synchronized (mInstallLock) {
19684                    destroyUserDataLI(volumeUuid, userId,
19685                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19686                }
19687            }
19688        }
19689    }
19690
19691    private void assertPackageKnown(String volumeUuid, String packageName)
19692            throws PackageManagerException {
19693        synchronized (mPackages) {
19694            final PackageSetting ps = mSettings.mPackages.get(packageName);
19695            if (ps == null) {
19696                throw new PackageManagerException("Package " + packageName + " is unknown");
19697            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19698                throw new PackageManagerException(
19699                        "Package " + packageName + " found on unknown volume " + volumeUuid
19700                                + "; expected volume " + ps.volumeUuid);
19701            }
19702        }
19703    }
19704
19705    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19706            throws PackageManagerException {
19707        synchronized (mPackages) {
19708            final PackageSetting ps = mSettings.mPackages.get(packageName);
19709            if (ps == null) {
19710                throw new PackageManagerException("Package " + packageName + " is unknown");
19711            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19712                throw new PackageManagerException(
19713                        "Package " + packageName + " found on unknown volume " + volumeUuid
19714                                + "; expected volume " + ps.volumeUuid);
19715            } else if (!ps.getInstalled(userId)) {
19716                throw new PackageManagerException(
19717                        "Package " + packageName + " not installed for user " + userId);
19718            }
19719        }
19720    }
19721
19722    /**
19723     * Examine all apps present on given mounted volume, and destroy apps that
19724     * aren't expected, either due to uninstallation or reinstallation on
19725     * another volume.
19726     */
19727    private void reconcileApps(String volumeUuid) {
19728        final File[] files = FileUtils
19729                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19730        for (File file : files) {
19731            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19732                    && !PackageInstallerService.isStageName(file.getName());
19733            if (!isPackage) {
19734                // Ignore entries which are not packages
19735                continue;
19736            }
19737
19738            try {
19739                final PackageLite pkg = PackageParser.parsePackageLite(file,
19740                        PackageParser.PARSE_MUST_BE_APK);
19741                assertPackageKnown(volumeUuid, pkg.packageName);
19742
19743            } catch (PackageParserException | PackageManagerException e) {
19744                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19745                synchronized (mInstallLock) {
19746                    removeCodePathLI(file);
19747                }
19748            }
19749        }
19750    }
19751
19752    /**
19753     * Reconcile all app data for the given user.
19754     * <p>
19755     * Verifies that directories exist and that ownership and labeling is
19756     * correct for all installed apps on all mounted volumes.
19757     */
19758    void reconcileAppsData(int userId, int flags) {
19759        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19760        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19761            final String volumeUuid = vol.getFsUuid();
19762            synchronized (mInstallLock) {
19763                reconcileAppsDataLI(volumeUuid, userId, flags);
19764            }
19765        }
19766    }
19767
19768    /**
19769     * Reconcile all app data on given mounted volume.
19770     * <p>
19771     * Destroys app data that isn't expected, either due to uninstallation or
19772     * reinstallation on another volume.
19773     * <p>
19774     * Verifies that directories exist and that ownership and labeling is
19775     * correct for all installed apps.
19776     */
19777    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19778        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19779                + Integer.toHexString(flags));
19780
19781        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19782        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19783
19784        // First look for stale data that doesn't belong, and check if things
19785        // have changed since we did our last restorecon
19786        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19787            if (StorageManager.isFileEncryptedNativeOrEmulated()
19788                    && !StorageManager.isUserKeyUnlocked(userId)) {
19789                throw new RuntimeException(
19790                        "Yikes, someone asked us to reconcile CE storage while " + userId
19791                                + " was still locked; this would have caused massive data loss!");
19792            }
19793
19794            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19795            for (File file : files) {
19796                final String packageName = file.getName();
19797                try {
19798                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19799                } catch (PackageManagerException e) {
19800                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19801                    try {
19802                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19803                                StorageManager.FLAG_STORAGE_CE, 0);
19804                    } catch (InstallerException e2) {
19805                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19806                    }
19807                }
19808            }
19809        }
19810        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19811            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19812            for (File file : files) {
19813                final String packageName = file.getName();
19814                try {
19815                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19816                } catch (PackageManagerException e) {
19817                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19818                    try {
19819                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19820                                StorageManager.FLAG_STORAGE_DE, 0);
19821                    } catch (InstallerException e2) {
19822                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19823                    }
19824                }
19825            }
19826        }
19827
19828        // Ensure that data directories are ready to roll for all packages
19829        // installed for this volume and user
19830        final List<PackageSetting> packages;
19831        synchronized (mPackages) {
19832            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19833        }
19834        int preparedCount = 0;
19835        for (PackageSetting ps : packages) {
19836            final String packageName = ps.name;
19837            if (ps.pkg == null) {
19838                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19839                // TODO: might be due to legacy ASEC apps; we should circle back
19840                // and reconcile again once they're scanned
19841                continue;
19842            }
19843
19844            if (ps.getInstalled(userId)) {
19845                prepareAppDataLIF(ps.pkg, userId, flags);
19846
19847                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19848                    // We may have just shuffled around app data directories, so
19849                    // prepare them one more time
19850                    prepareAppDataLIF(ps.pkg, userId, flags);
19851                }
19852
19853                preparedCount++;
19854            }
19855        }
19856
19857        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
19858    }
19859
19860    /**
19861     * Prepare app data for the given app just after it was installed or
19862     * upgraded. This method carefully only touches users that it's installed
19863     * for, and it forces a restorecon to handle any seinfo changes.
19864     * <p>
19865     * Verifies that directories exist and that ownership and labeling is
19866     * correct for all installed apps. If there is an ownership mismatch, it
19867     * will try recovering system apps by wiping data; third-party app data is
19868     * left intact.
19869     * <p>
19870     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19871     */
19872    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19873        final PackageSetting ps;
19874        synchronized (mPackages) {
19875            ps = mSettings.mPackages.get(pkg.packageName);
19876            mSettings.writeKernelMappingLPr(ps);
19877        }
19878
19879        final UserManager um = mContext.getSystemService(UserManager.class);
19880        UserManagerInternal umInternal = getUserManagerInternal();
19881        for (UserInfo user : um.getUsers()) {
19882            final int flags;
19883            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19884                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19885            } else if (umInternal.isUserRunning(user.id)) {
19886                flags = StorageManager.FLAG_STORAGE_DE;
19887            } else {
19888                continue;
19889            }
19890
19891            if (ps.getInstalled(user.id)) {
19892                // TODO: when user data is locked, mark that we're still dirty
19893                prepareAppDataLIF(pkg, user.id, flags);
19894            }
19895        }
19896    }
19897
19898    /**
19899     * Prepare app data for the given app.
19900     * <p>
19901     * Verifies that directories exist and that ownership and labeling is
19902     * correct for all installed apps. If there is an ownership mismatch, this
19903     * will try recovering system apps by wiping data; third-party app data is
19904     * left intact.
19905     */
19906    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
19907        if (pkg == null) {
19908            Slog.wtf(TAG, "Package was null!", new Throwable());
19909            return;
19910        }
19911        prepareAppDataLeafLIF(pkg, userId, flags);
19912        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19913        for (int i = 0; i < childCount; i++) {
19914            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
19915        }
19916    }
19917
19918    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19919        if (DEBUG_APP_DATA) {
19920            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19921                    + Integer.toHexString(flags));
19922        }
19923
19924        final String volumeUuid = pkg.volumeUuid;
19925        final String packageName = pkg.packageName;
19926        final ApplicationInfo app = pkg.applicationInfo;
19927        final int appId = UserHandle.getAppId(app.uid);
19928
19929        Preconditions.checkNotNull(app.seinfo);
19930
19931        try {
19932            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19933                    appId, app.seinfo, app.targetSdkVersion);
19934        } catch (InstallerException e) {
19935            if (app.isSystemApp()) {
19936                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19937                        + ", but trying to recover: " + e);
19938                destroyAppDataLeafLIF(pkg, userId, flags);
19939                try {
19940                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19941                            appId, app.seinfo, app.targetSdkVersion);
19942                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19943                } catch (InstallerException e2) {
19944                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19945                }
19946            } else {
19947                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19948            }
19949        }
19950
19951        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19952            try {
19953                // CE storage is unlocked right now, so read out the inode and
19954                // remember for use later when it's locked
19955                // TODO: mark this structure as dirty so we persist it!
19956                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19957                        StorageManager.FLAG_STORAGE_CE);
19958                synchronized (mPackages) {
19959                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19960                    if (ps != null) {
19961                        ps.setCeDataInode(ceDataInode, userId);
19962                    }
19963                }
19964            } catch (InstallerException e) {
19965                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19966            }
19967        }
19968
19969        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19970    }
19971
19972    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19973        if (pkg == null) {
19974            Slog.wtf(TAG, "Package was null!", new Throwable());
19975            return;
19976        }
19977        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19978        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19979        for (int i = 0; i < childCount; i++) {
19980            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19981        }
19982    }
19983
19984    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19985        final String volumeUuid = pkg.volumeUuid;
19986        final String packageName = pkg.packageName;
19987        final ApplicationInfo app = pkg.applicationInfo;
19988
19989        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19990            // Create a native library symlink only if we have native libraries
19991            // and if the native libraries are 32 bit libraries. We do not provide
19992            // this symlink for 64 bit libraries.
19993            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19994                final String nativeLibPath = app.nativeLibraryDir;
19995                try {
19996                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19997                            nativeLibPath, userId);
19998                } catch (InstallerException e) {
19999                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20000                }
20001            }
20002        }
20003    }
20004
20005    /**
20006     * For system apps on non-FBE devices, this method migrates any existing
20007     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20008     * requested by the app.
20009     */
20010    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20011        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20012                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20013            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20014                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20015            try {
20016                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20017                        storageTarget);
20018            } catch (InstallerException e) {
20019                logCriticalInfo(Log.WARN,
20020                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20021            }
20022            return true;
20023        } else {
20024            return false;
20025        }
20026    }
20027
20028    public PackageFreezer freezePackage(String packageName, String killReason) {
20029        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20030    }
20031
20032    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20033        return new PackageFreezer(packageName, userId, killReason);
20034    }
20035
20036    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20037            String killReason) {
20038        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20039    }
20040
20041    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20042            String killReason) {
20043        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20044            return new PackageFreezer();
20045        } else {
20046            return freezePackage(packageName, userId, killReason);
20047        }
20048    }
20049
20050    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20051            String killReason) {
20052        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20053    }
20054
20055    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20056            String killReason) {
20057        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20058            return new PackageFreezer();
20059        } else {
20060            return freezePackage(packageName, userId, killReason);
20061        }
20062    }
20063
20064    /**
20065     * Class that freezes and kills the given package upon creation, and
20066     * unfreezes it upon closing. This is typically used when doing surgery on
20067     * app code/data to prevent the app from running while you're working.
20068     */
20069    private class PackageFreezer implements AutoCloseable {
20070        private final String mPackageName;
20071        private final PackageFreezer[] mChildren;
20072
20073        private final boolean mWeFroze;
20074
20075        private final AtomicBoolean mClosed = new AtomicBoolean();
20076        private final CloseGuard mCloseGuard = CloseGuard.get();
20077
20078        /**
20079         * Create and return a stub freezer that doesn't actually do anything,
20080         * typically used when someone requested
20081         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20082         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20083         */
20084        public PackageFreezer() {
20085            mPackageName = null;
20086            mChildren = null;
20087            mWeFroze = false;
20088            mCloseGuard.open("close");
20089        }
20090
20091        public PackageFreezer(String packageName, int userId, String killReason) {
20092            synchronized (mPackages) {
20093                mPackageName = packageName;
20094                mWeFroze = mFrozenPackages.add(mPackageName);
20095
20096                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20097                if (ps != null) {
20098                    killApplication(ps.name, ps.appId, userId, killReason);
20099                }
20100
20101                final PackageParser.Package p = mPackages.get(packageName);
20102                if (p != null && p.childPackages != null) {
20103                    final int N = p.childPackages.size();
20104                    mChildren = new PackageFreezer[N];
20105                    for (int i = 0; i < N; i++) {
20106                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20107                                userId, killReason);
20108                    }
20109                } else {
20110                    mChildren = null;
20111                }
20112            }
20113            mCloseGuard.open("close");
20114        }
20115
20116        @Override
20117        protected void finalize() throws Throwable {
20118            try {
20119                mCloseGuard.warnIfOpen();
20120                close();
20121            } finally {
20122                super.finalize();
20123            }
20124        }
20125
20126        @Override
20127        public void close() {
20128            mCloseGuard.close();
20129            if (mClosed.compareAndSet(false, true)) {
20130                synchronized (mPackages) {
20131                    if (mWeFroze) {
20132                        mFrozenPackages.remove(mPackageName);
20133                    }
20134
20135                    if (mChildren != null) {
20136                        for (PackageFreezer freezer : mChildren) {
20137                            freezer.close();
20138                        }
20139                    }
20140                }
20141            }
20142        }
20143    }
20144
20145    /**
20146     * Verify that given package is currently frozen.
20147     */
20148    private void checkPackageFrozen(String packageName) {
20149        synchronized (mPackages) {
20150            if (!mFrozenPackages.contains(packageName)) {
20151                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20152            }
20153        }
20154    }
20155
20156    @Override
20157    public int movePackage(final String packageName, final String volumeUuid) {
20158        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20159
20160        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20161        final int moveId = mNextMoveId.getAndIncrement();
20162        mHandler.post(new Runnable() {
20163            @Override
20164            public void run() {
20165                try {
20166                    movePackageInternal(packageName, volumeUuid, moveId, user);
20167                } catch (PackageManagerException e) {
20168                    Slog.w(TAG, "Failed to move " + packageName, e);
20169                    mMoveCallbacks.notifyStatusChanged(moveId,
20170                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20171                }
20172            }
20173        });
20174        return moveId;
20175    }
20176
20177    private void movePackageInternal(final String packageName, final String volumeUuid,
20178            final int moveId, UserHandle user) throws PackageManagerException {
20179        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20180        final PackageManager pm = mContext.getPackageManager();
20181
20182        final boolean currentAsec;
20183        final String currentVolumeUuid;
20184        final File codeFile;
20185        final String installerPackageName;
20186        final String packageAbiOverride;
20187        final int appId;
20188        final String seinfo;
20189        final String label;
20190        final int targetSdkVersion;
20191        final PackageFreezer freezer;
20192        final int[] installedUserIds;
20193
20194        // reader
20195        synchronized (mPackages) {
20196            final PackageParser.Package pkg = mPackages.get(packageName);
20197            final PackageSetting ps = mSettings.mPackages.get(packageName);
20198            if (pkg == null || ps == null) {
20199                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20200            }
20201
20202            if (pkg.applicationInfo.isSystemApp()) {
20203                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20204                        "Cannot move system application");
20205            }
20206
20207            if (pkg.applicationInfo.isExternalAsec()) {
20208                currentAsec = true;
20209                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20210            } else if (pkg.applicationInfo.isForwardLocked()) {
20211                currentAsec = true;
20212                currentVolumeUuid = "forward_locked";
20213            } else {
20214                currentAsec = false;
20215                currentVolumeUuid = ps.volumeUuid;
20216
20217                final File probe = new File(pkg.codePath);
20218                final File probeOat = new File(probe, "oat");
20219                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20220                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20221                            "Move only supported for modern cluster style installs");
20222                }
20223            }
20224
20225            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20226                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20227                        "Package already moved to " + volumeUuid);
20228            }
20229            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20230                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20231                        "Device admin cannot be moved");
20232            }
20233
20234            if (mFrozenPackages.contains(packageName)) {
20235                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20236                        "Failed to move already frozen package");
20237            }
20238
20239            codeFile = new File(pkg.codePath);
20240            installerPackageName = ps.installerPackageName;
20241            packageAbiOverride = ps.cpuAbiOverrideString;
20242            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20243            seinfo = pkg.applicationInfo.seinfo;
20244            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20245            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20246            freezer = freezePackage(packageName, "movePackageInternal");
20247            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20248        }
20249
20250        final Bundle extras = new Bundle();
20251        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20252        extras.putString(Intent.EXTRA_TITLE, label);
20253        mMoveCallbacks.notifyCreated(moveId, extras);
20254
20255        int installFlags;
20256        final boolean moveCompleteApp;
20257        final File measurePath;
20258
20259        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20260            installFlags = INSTALL_INTERNAL;
20261            moveCompleteApp = !currentAsec;
20262            measurePath = Environment.getDataAppDirectory(volumeUuid);
20263        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20264            installFlags = INSTALL_EXTERNAL;
20265            moveCompleteApp = false;
20266            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20267        } else {
20268            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20269            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20270                    || !volume.isMountedWritable()) {
20271                freezer.close();
20272                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20273                        "Move location not mounted private volume");
20274            }
20275
20276            Preconditions.checkState(!currentAsec);
20277
20278            installFlags = INSTALL_INTERNAL;
20279            moveCompleteApp = true;
20280            measurePath = Environment.getDataAppDirectory(volumeUuid);
20281        }
20282
20283        final PackageStats stats = new PackageStats(null, -1);
20284        synchronized (mInstaller) {
20285            for (int userId : installedUserIds) {
20286                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20287                    freezer.close();
20288                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20289                            "Failed to measure package size");
20290                }
20291            }
20292        }
20293
20294        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20295                + stats.dataSize);
20296
20297        final long startFreeBytes = measurePath.getFreeSpace();
20298        final long sizeBytes;
20299        if (moveCompleteApp) {
20300            sizeBytes = stats.codeSize + stats.dataSize;
20301        } else {
20302            sizeBytes = stats.codeSize;
20303        }
20304
20305        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20306            freezer.close();
20307            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20308                    "Not enough free space to move");
20309        }
20310
20311        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20312
20313        final CountDownLatch installedLatch = new CountDownLatch(1);
20314        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20315            @Override
20316            public void onUserActionRequired(Intent intent) throws RemoteException {
20317                throw new IllegalStateException();
20318            }
20319
20320            @Override
20321            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20322                    Bundle extras) throws RemoteException {
20323                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20324                        + PackageManager.installStatusToString(returnCode, msg));
20325
20326                installedLatch.countDown();
20327                freezer.close();
20328
20329                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20330                switch (status) {
20331                    case PackageInstaller.STATUS_SUCCESS:
20332                        mMoveCallbacks.notifyStatusChanged(moveId,
20333                                PackageManager.MOVE_SUCCEEDED);
20334                        break;
20335                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20336                        mMoveCallbacks.notifyStatusChanged(moveId,
20337                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20338                        break;
20339                    default:
20340                        mMoveCallbacks.notifyStatusChanged(moveId,
20341                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20342                        break;
20343                }
20344            }
20345        };
20346
20347        final MoveInfo move;
20348        if (moveCompleteApp) {
20349            // Kick off a thread to report progress estimates
20350            new Thread() {
20351                @Override
20352                public void run() {
20353                    while (true) {
20354                        try {
20355                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20356                                break;
20357                            }
20358                        } catch (InterruptedException ignored) {
20359                        }
20360
20361                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20362                        final int progress = 10 + (int) MathUtils.constrain(
20363                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20364                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20365                    }
20366                }
20367            }.start();
20368
20369            final String dataAppName = codeFile.getName();
20370            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20371                    dataAppName, appId, seinfo, targetSdkVersion);
20372        } else {
20373            move = null;
20374        }
20375
20376        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20377
20378        final Message msg = mHandler.obtainMessage(INIT_COPY);
20379        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20380        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20381                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20382                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20383        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20384        msg.obj = params;
20385
20386        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20387                System.identityHashCode(msg.obj));
20388        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20389                System.identityHashCode(msg.obj));
20390
20391        mHandler.sendMessage(msg);
20392    }
20393
20394    @Override
20395    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20396        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20397
20398        final int realMoveId = mNextMoveId.getAndIncrement();
20399        final Bundle extras = new Bundle();
20400        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20401        mMoveCallbacks.notifyCreated(realMoveId, extras);
20402
20403        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20404            @Override
20405            public void onCreated(int moveId, Bundle extras) {
20406                // Ignored
20407            }
20408
20409            @Override
20410            public void onStatusChanged(int moveId, int status, long estMillis) {
20411                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20412            }
20413        };
20414
20415        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20416        storage.setPrimaryStorageUuid(volumeUuid, callback);
20417        return realMoveId;
20418    }
20419
20420    @Override
20421    public int getMoveStatus(int moveId) {
20422        mContext.enforceCallingOrSelfPermission(
20423                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20424        return mMoveCallbacks.mLastStatus.get(moveId);
20425    }
20426
20427    @Override
20428    public void registerMoveCallback(IPackageMoveObserver callback) {
20429        mContext.enforceCallingOrSelfPermission(
20430                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20431        mMoveCallbacks.register(callback);
20432    }
20433
20434    @Override
20435    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20436        mContext.enforceCallingOrSelfPermission(
20437                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20438        mMoveCallbacks.unregister(callback);
20439    }
20440
20441    @Override
20442    public boolean setInstallLocation(int loc) {
20443        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20444                null);
20445        if (getInstallLocation() == loc) {
20446            return true;
20447        }
20448        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20449                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20450            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20451                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20452            return true;
20453        }
20454        return false;
20455   }
20456
20457    @Override
20458    public int getInstallLocation() {
20459        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20460                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20461                PackageHelper.APP_INSTALL_AUTO);
20462    }
20463
20464    /** Called by UserManagerService */
20465    void cleanUpUser(UserManagerService userManager, int userHandle) {
20466        synchronized (mPackages) {
20467            mDirtyUsers.remove(userHandle);
20468            mUserNeedsBadging.delete(userHandle);
20469            mSettings.removeUserLPw(userHandle);
20470            mPendingBroadcasts.remove(userHandle);
20471            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20472            removeUnusedPackagesLPw(userManager, userHandle);
20473        }
20474    }
20475
20476    /**
20477     * We're removing userHandle and would like to remove any downloaded packages
20478     * that are no longer in use by any other user.
20479     * @param userHandle the user being removed
20480     */
20481    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20482        final boolean DEBUG_CLEAN_APKS = false;
20483        int [] users = userManager.getUserIds();
20484        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20485        while (psit.hasNext()) {
20486            PackageSetting ps = psit.next();
20487            if (ps.pkg == null) {
20488                continue;
20489            }
20490            final String packageName = ps.pkg.packageName;
20491            // Skip over if system app
20492            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20493                continue;
20494            }
20495            if (DEBUG_CLEAN_APKS) {
20496                Slog.i(TAG, "Checking package " + packageName);
20497            }
20498            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20499            if (keep) {
20500                if (DEBUG_CLEAN_APKS) {
20501                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20502                }
20503            } else {
20504                for (int i = 0; i < users.length; i++) {
20505                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20506                        keep = true;
20507                        if (DEBUG_CLEAN_APKS) {
20508                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20509                                    + users[i]);
20510                        }
20511                        break;
20512                    }
20513                }
20514            }
20515            if (!keep) {
20516                if (DEBUG_CLEAN_APKS) {
20517                    Slog.i(TAG, "  Removing package " + packageName);
20518                }
20519                mHandler.post(new Runnable() {
20520                    public void run() {
20521                        deletePackageX(packageName, userHandle, 0);
20522                    } //end run
20523                });
20524            }
20525        }
20526    }
20527
20528    /** Called by UserManagerService */
20529    void createNewUser(int userId) {
20530        synchronized (mInstallLock) {
20531            mSettings.createNewUserLI(this, mInstaller, userId);
20532        }
20533        synchronized (mPackages) {
20534            scheduleWritePackageRestrictionsLocked(userId);
20535            scheduleWritePackageListLocked(userId);
20536            applyFactoryDefaultBrowserLPw(userId);
20537            primeDomainVerificationsLPw(userId);
20538        }
20539    }
20540
20541    void onNewUserCreated(final int userId) {
20542        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20543        // If permission review for legacy apps is required, we represent
20544        // dagerous permissions for such apps as always granted runtime
20545        // permissions to keep per user flag state whether review is needed.
20546        // Hence, if a new user is added we have to propagate dangerous
20547        // permission grants for these legacy apps.
20548        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20549            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20550                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20551        }
20552    }
20553
20554    @Override
20555    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20556        mContext.enforceCallingOrSelfPermission(
20557                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20558                "Only package verification agents can read the verifier device identity");
20559
20560        synchronized (mPackages) {
20561            return mSettings.getVerifierDeviceIdentityLPw();
20562        }
20563    }
20564
20565    @Override
20566    public void setPermissionEnforced(String permission, boolean enforced) {
20567        // TODO: Now that we no longer change GID for storage, this should to away.
20568        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20569                "setPermissionEnforced");
20570        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20571            synchronized (mPackages) {
20572                if (mSettings.mReadExternalStorageEnforced == null
20573                        || mSettings.mReadExternalStorageEnforced != enforced) {
20574                    mSettings.mReadExternalStorageEnforced = enforced;
20575                    mSettings.writeLPr();
20576                }
20577            }
20578            // kill any non-foreground processes so we restart them and
20579            // grant/revoke the GID.
20580            final IActivityManager am = ActivityManagerNative.getDefault();
20581            if (am != null) {
20582                final long token = Binder.clearCallingIdentity();
20583                try {
20584                    am.killProcessesBelowForeground("setPermissionEnforcement");
20585                } catch (RemoteException e) {
20586                } finally {
20587                    Binder.restoreCallingIdentity(token);
20588                }
20589            }
20590        } else {
20591            throw new IllegalArgumentException("No selective enforcement for " + permission);
20592        }
20593    }
20594
20595    @Override
20596    @Deprecated
20597    public boolean isPermissionEnforced(String permission) {
20598        return true;
20599    }
20600
20601    @Override
20602    public boolean isStorageLow() {
20603        final long token = Binder.clearCallingIdentity();
20604        try {
20605            final DeviceStorageMonitorInternal
20606                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20607            if (dsm != null) {
20608                return dsm.isMemoryLow();
20609            } else {
20610                return false;
20611            }
20612        } finally {
20613            Binder.restoreCallingIdentity(token);
20614        }
20615    }
20616
20617    @Override
20618    public IPackageInstaller getPackageInstaller() {
20619        return mInstallerService;
20620    }
20621
20622    private boolean userNeedsBadging(int userId) {
20623        int index = mUserNeedsBadging.indexOfKey(userId);
20624        if (index < 0) {
20625            final UserInfo userInfo;
20626            final long token = Binder.clearCallingIdentity();
20627            try {
20628                userInfo = sUserManager.getUserInfo(userId);
20629            } finally {
20630                Binder.restoreCallingIdentity(token);
20631            }
20632            final boolean b;
20633            if (userInfo != null && userInfo.isManagedProfile()) {
20634                b = true;
20635            } else {
20636                b = false;
20637            }
20638            mUserNeedsBadging.put(userId, b);
20639            return b;
20640        }
20641        return mUserNeedsBadging.valueAt(index);
20642    }
20643
20644    @Override
20645    public KeySet getKeySetByAlias(String packageName, String alias) {
20646        if (packageName == null || alias == null) {
20647            return null;
20648        }
20649        synchronized(mPackages) {
20650            final PackageParser.Package pkg = mPackages.get(packageName);
20651            if (pkg == null) {
20652                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20653                throw new IllegalArgumentException("Unknown package: " + packageName);
20654            }
20655            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20656            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20657        }
20658    }
20659
20660    @Override
20661    public KeySet getSigningKeySet(String packageName) {
20662        if (packageName == null) {
20663            return null;
20664        }
20665        synchronized(mPackages) {
20666            final PackageParser.Package pkg = mPackages.get(packageName);
20667            if (pkg == null) {
20668                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20669                throw new IllegalArgumentException("Unknown package: " + packageName);
20670            }
20671            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20672                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20673                throw new SecurityException("May not access signing KeySet of other apps.");
20674            }
20675            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20676            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20677        }
20678    }
20679
20680    @Override
20681    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20682        if (packageName == null || ks == null) {
20683            return false;
20684        }
20685        synchronized(mPackages) {
20686            final PackageParser.Package pkg = mPackages.get(packageName);
20687            if (pkg == null) {
20688                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20689                throw new IllegalArgumentException("Unknown package: " + packageName);
20690            }
20691            IBinder ksh = ks.getToken();
20692            if (ksh instanceof KeySetHandle) {
20693                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20694                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20695            }
20696            return false;
20697        }
20698    }
20699
20700    @Override
20701    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20702        if (packageName == null || ks == null) {
20703            return false;
20704        }
20705        synchronized(mPackages) {
20706            final PackageParser.Package pkg = mPackages.get(packageName);
20707            if (pkg == null) {
20708                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20709                throw new IllegalArgumentException("Unknown package: " + packageName);
20710            }
20711            IBinder ksh = ks.getToken();
20712            if (ksh instanceof KeySetHandle) {
20713                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20714                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20715            }
20716            return false;
20717        }
20718    }
20719
20720    private void deletePackageIfUnusedLPr(final String packageName) {
20721        PackageSetting ps = mSettings.mPackages.get(packageName);
20722        if (ps == null) {
20723            return;
20724        }
20725        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20726            // TODO Implement atomic delete if package is unused
20727            // It is currently possible that the package will be deleted even if it is installed
20728            // after this method returns.
20729            mHandler.post(new Runnable() {
20730                public void run() {
20731                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20732                }
20733            });
20734        }
20735    }
20736
20737    /**
20738     * Check and throw if the given before/after packages would be considered a
20739     * downgrade.
20740     */
20741    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20742            throws PackageManagerException {
20743        if (after.versionCode < before.mVersionCode) {
20744            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20745                    "Update version code " + after.versionCode + " is older than current "
20746                    + before.mVersionCode);
20747        } else if (after.versionCode == before.mVersionCode) {
20748            if (after.baseRevisionCode < before.baseRevisionCode) {
20749                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20750                        "Update base revision code " + after.baseRevisionCode
20751                        + " is older than current " + before.baseRevisionCode);
20752            }
20753
20754            if (!ArrayUtils.isEmpty(after.splitNames)) {
20755                for (int i = 0; i < after.splitNames.length; i++) {
20756                    final String splitName = after.splitNames[i];
20757                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20758                    if (j != -1) {
20759                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20760                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20761                                    "Update split " + splitName + " revision code "
20762                                    + after.splitRevisionCodes[i] + " is older than current "
20763                                    + before.splitRevisionCodes[j]);
20764                        }
20765                    }
20766                }
20767            }
20768        }
20769    }
20770
20771    private static class MoveCallbacks extends Handler {
20772        private static final int MSG_CREATED = 1;
20773        private static final int MSG_STATUS_CHANGED = 2;
20774
20775        private final RemoteCallbackList<IPackageMoveObserver>
20776                mCallbacks = new RemoteCallbackList<>();
20777
20778        private final SparseIntArray mLastStatus = new SparseIntArray();
20779
20780        public MoveCallbacks(Looper looper) {
20781            super(looper);
20782        }
20783
20784        public void register(IPackageMoveObserver callback) {
20785            mCallbacks.register(callback);
20786        }
20787
20788        public void unregister(IPackageMoveObserver callback) {
20789            mCallbacks.unregister(callback);
20790        }
20791
20792        @Override
20793        public void handleMessage(Message msg) {
20794            final SomeArgs args = (SomeArgs) msg.obj;
20795            final int n = mCallbacks.beginBroadcast();
20796            for (int i = 0; i < n; i++) {
20797                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20798                try {
20799                    invokeCallback(callback, msg.what, args);
20800                } catch (RemoteException ignored) {
20801                }
20802            }
20803            mCallbacks.finishBroadcast();
20804            args.recycle();
20805        }
20806
20807        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20808                throws RemoteException {
20809            switch (what) {
20810                case MSG_CREATED: {
20811                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20812                    break;
20813                }
20814                case MSG_STATUS_CHANGED: {
20815                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20816                    break;
20817                }
20818            }
20819        }
20820
20821        private void notifyCreated(int moveId, Bundle extras) {
20822            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20823
20824            final SomeArgs args = SomeArgs.obtain();
20825            args.argi1 = moveId;
20826            args.arg2 = extras;
20827            obtainMessage(MSG_CREATED, args).sendToTarget();
20828        }
20829
20830        private void notifyStatusChanged(int moveId, int status) {
20831            notifyStatusChanged(moveId, status, -1);
20832        }
20833
20834        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20835            Slog.v(TAG, "Move " + moveId + " status " + status);
20836
20837            final SomeArgs args = SomeArgs.obtain();
20838            args.argi1 = moveId;
20839            args.argi2 = status;
20840            args.arg3 = estMillis;
20841            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20842
20843            synchronized (mLastStatus) {
20844                mLastStatus.put(moveId, status);
20845            }
20846        }
20847    }
20848
20849    private final static class OnPermissionChangeListeners extends Handler {
20850        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20851
20852        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20853                new RemoteCallbackList<>();
20854
20855        public OnPermissionChangeListeners(Looper looper) {
20856            super(looper);
20857        }
20858
20859        @Override
20860        public void handleMessage(Message msg) {
20861            switch (msg.what) {
20862                case MSG_ON_PERMISSIONS_CHANGED: {
20863                    final int uid = msg.arg1;
20864                    handleOnPermissionsChanged(uid);
20865                } break;
20866            }
20867        }
20868
20869        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20870            mPermissionListeners.register(listener);
20871
20872        }
20873
20874        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20875            mPermissionListeners.unregister(listener);
20876        }
20877
20878        public void onPermissionsChanged(int uid) {
20879            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20880                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20881            }
20882        }
20883
20884        private void handleOnPermissionsChanged(int uid) {
20885            final int count = mPermissionListeners.beginBroadcast();
20886            try {
20887                for (int i = 0; i < count; i++) {
20888                    IOnPermissionsChangeListener callback = mPermissionListeners
20889                            .getBroadcastItem(i);
20890                    try {
20891                        callback.onPermissionsChanged(uid);
20892                    } catch (RemoteException e) {
20893                        Log.e(TAG, "Permission listener is dead", e);
20894                    }
20895                }
20896            } finally {
20897                mPermissionListeners.finishBroadcast();
20898            }
20899        }
20900    }
20901
20902    private class PackageManagerInternalImpl extends PackageManagerInternal {
20903        @Override
20904        public void setLocationPackagesProvider(PackagesProvider provider) {
20905            synchronized (mPackages) {
20906                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20907            }
20908        }
20909
20910        @Override
20911        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20912            synchronized (mPackages) {
20913                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20914            }
20915        }
20916
20917        @Override
20918        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20919            synchronized (mPackages) {
20920                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20921            }
20922        }
20923
20924        @Override
20925        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20926            synchronized (mPackages) {
20927                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20928            }
20929        }
20930
20931        @Override
20932        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20933            synchronized (mPackages) {
20934                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20935            }
20936        }
20937
20938        @Override
20939        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20940            synchronized (mPackages) {
20941                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20942            }
20943        }
20944
20945        @Override
20946        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20947            synchronized (mPackages) {
20948                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20949                        packageName, userId);
20950            }
20951        }
20952
20953        @Override
20954        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20955            synchronized (mPackages) {
20956                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20957                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20958                        packageName, userId);
20959            }
20960        }
20961
20962        @Override
20963        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20964            synchronized (mPackages) {
20965                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20966                        packageName, userId);
20967            }
20968        }
20969
20970        @Override
20971        public void setKeepUninstalledPackages(final List<String> packageList) {
20972            Preconditions.checkNotNull(packageList);
20973            List<String> removedFromList = null;
20974            synchronized (mPackages) {
20975                if (mKeepUninstalledPackages != null) {
20976                    final int packagesCount = mKeepUninstalledPackages.size();
20977                    for (int i = 0; i < packagesCount; i++) {
20978                        String oldPackage = mKeepUninstalledPackages.get(i);
20979                        if (packageList != null && packageList.contains(oldPackage)) {
20980                            continue;
20981                        }
20982                        if (removedFromList == null) {
20983                            removedFromList = new ArrayList<>();
20984                        }
20985                        removedFromList.add(oldPackage);
20986                    }
20987                }
20988                mKeepUninstalledPackages = new ArrayList<>(packageList);
20989                if (removedFromList != null) {
20990                    final int removedCount = removedFromList.size();
20991                    for (int i = 0; i < removedCount; i++) {
20992                        deletePackageIfUnusedLPr(removedFromList.get(i));
20993                    }
20994                }
20995            }
20996        }
20997
20998        @Override
20999        public boolean isPermissionsReviewRequired(String packageName, int userId) {
21000            synchronized (mPackages) {
21001                // If we do not support permission review, done.
21002                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
21003                    return false;
21004                }
21005
21006                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21007                if (packageSetting == null) {
21008                    return false;
21009                }
21010
21011                // Permission review applies only to apps not supporting the new permission model.
21012                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21013                    return false;
21014                }
21015
21016                // Legacy apps have the permission and get user consent on launch.
21017                PermissionsState permissionsState = packageSetting.getPermissionsState();
21018                return permissionsState.isPermissionReviewRequired(userId);
21019            }
21020        }
21021
21022        @Override
21023        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21024            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21025        }
21026
21027        @Override
21028        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21029                int userId) {
21030            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21031        }
21032
21033        @Override
21034        public void setDeviceAndProfileOwnerPackages(
21035                int deviceOwnerUserId, String deviceOwnerPackage,
21036                SparseArray<String> profileOwnerPackages) {
21037            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21038                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21039        }
21040
21041        @Override
21042        public boolean isPackageDataProtected(int userId, String packageName) {
21043            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21044        }
21045
21046        @Override
21047        public boolean wasPackageEverLaunched(String packageName, int userId) {
21048            synchronized (mPackages) {
21049                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21050            }
21051        }
21052    }
21053
21054    @Override
21055    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21056        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21057        synchronized (mPackages) {
21058            final long identity = Binder.clearCallingIdentity();
21059            try {
21060                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21061                        packageNames, userId);
21062            } finally {
21063                Binder.restoreCallingIdentity(identity);
21064            }
21065        }
21066    }
21067
21068    private static void enforceSystemOrPhoneCaller(String tag) {
21069        int callingUid = Binder.getCallingUid();
21070        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21071            throw new SecurityException(
21072                    "Cannot call " + tag + " from UID " + callingUid);
21073        }
21074    }
21075
21076    boolean isHistoricalPackageUsageAvailable() {
21077        return mPackageUsage.isHistoricalPackageUsageAvailable();
21078    }
21079
21080    /**
21081     * Return a <b>copy</b> of the collection of packages known to the package manager.
21082     * @return A copy of the values of mPackages.
21083     */
21084    Collection<PackageParser.Package> getPackages() {
21085        synchronized (mPackages) {
21086            return new ArrayList<>(mPackages.values());
21087        }
21088    }
21089
21090    /**
21091     * Logs process start information (including base APK hash) to the security log.
21092     * @hide
21093     */
21094    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21095            String apkFile, int pid) {
21096        if (!SecurityLog.isLoggingEnabled()) {
21097            return;
21098        }
21099        Bundle data = new Bundle();
21100        data.putLong("startTimestamp", System.currentTimeMillis());
21101        data.putString("processName", processName);
21102        data.putInt("uid", uid);
21103        data.putString("seinfo", seinfo);
21104        data.putString("apkFile", apkFile);
21105        data.putInt("pid", pid);
21106        Message msg = mProcessLoggingHandler.obtainMessage(
21107                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21108        msg.setData(data);
21109        mProcessLoggingHandler.sendMessage(msg);
21110    }
21111
21112    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21113        return mCompilerStats.getPackageStats(pkgName);
21114    }
21115
21116    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21117        return getOrCreateCompilerPackageStats(pkg.packageName);
21118    }
21119
21120    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21121        return mCompilerStats.getOrCreatePackageStats(pkgName);
21122    }
21123
21124    public void deleteCompilerPackageStats(String pkgName) {
21125        mCompilerStats.deletePackageStats(pkgName);
21126    }
21127}
21128