PackageManagerService.java revision b501ef1e21e4314aa1177b6d59294b2b18d7d2a0
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.IActivityManager;
105import android.app.ResourcesManager;
106import android.app.admin.IDevicePolicyManager;
107import android.app.admin.SecurityLog;
108import android.app.backup.IBackupManager;
109import android.content.BroadcastReceiver;
110import android.content.ComponentName;
111import android.content.ContentResolver;
112import android.content.Context;
113import android.content.IIntentReceiver;
114import android.content.Intent;
115import android.content.IntentFilter;
116import android.content.IntentSender;
117import android.content.IntentSender.SendIntentException;
118import android.content.ServiceConnection;
119import android.content.pm.ActivityInfo;
120import android.content.pm.ApplicationInfo;
121import android.content.pm.AppsQueryHelper;
122import android.content.pm.ComponentInfo;
123import android.content.pm.EphemeralApplicationInfo;
124import android.content.pm.EphemeralIntentFilter;
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.ShellCallback;
189import android.os.SystemClock;
190import android.os.SystemProperties;
191import android.os.Trace;
192import android.os.UserHandle;
193import android.os.UserManager;
194import android.os.UserManagerInternal;
195import android.os.storage.IMountService;
196import android.os.storage.MountServiceInternal;
197import android.os.storage.StorageEventListener;
198import android.os.storage.StorageManager;
199import android.os.storage.VolumeInfo;
200import android.os.storage.VolumeRecord;
201import android.provider.Settings.Global;
202import android.provider.Settings.Secure;
203import android.security.KeyStore;
204import android.security.SystemKeyStore;
205import android.system.ErrnoException;
206import android.system.Os;
207import android.text.TextUtils;
208import android.text.format.DateUtils;
209import android.util.ArrayMap;
210import android.util.ArraySet;
211import android.util.DisplayMetrics;
212import android.util.EventLog;
213import android.util.ExceptionUtils;
214import android.util.Log;
215import android.util.LogPrinter;
216import android.util.MathUtils;
217import android.util.Pair;
218import android.util.PrintStreamPrinter;
219import android.util.Slog;
220import android.util.SparseArray;
221import android.util.SparseBooleanArray;
222import android.util.SparseIntArray;
223import android.util.Xml;
224import android.util.jar.StrictJarFile;
225import android.view.Display;
226
227import com.android.internal.R;
228import com.android.internal.annotations.GuardedBy;
229import com.android.internal.app.IMediaContainerService;
230import com.android.internal.app.ResolverActivity;
231import com.android.internal.content.NativeLibraryHelper;
232import com.android.internal.content.PackageHelper;
233import com.android.internal.logging.MetricsLogger;
234import com.android.internal.os.IParcelFileDescriptorFactory;
235import com.android.internal.os.InstallerConnection.InstallerException;
236import com.android.internal.os.SomeArgs;
237import com.android.internal.os.Zygote;
238import com.android.internal.telephony.CarrierAppUtils;
239import com.android.internal.util.ArrayUtils;
240import com.android.internal.util.FastPrintWriter;
241import com.android.internal.util.FastXmlSerializer;
242import com.android.internal.util.IndentingPrintWriter;
243import com.android.internal.util.Preconditions;
244import com.android.internal.util.XmlUtils;
245import com.android.server.AttributeCache;
246import com.android.server.EventLogTags;
247import com.android.server.FgThread;
248import com.android.server.IntentResolver;
249import com.android.server.LocalServices;
250import com.android.server.ServiceThread;
251import com.android.server.SystemConfig;
252import com.android.server.Watchdog;
253import com.android.server.net.NetworkPolicyManagerInternal;
254import com.android.server.pm.PermissionsState.PermissionState;
255import com.android.server.pm.Settings.DatabaseVersion;
256import com.android.server.pm.Settings.VersionInfo;
257import com.android.server.storage.DeviceStorageMonitorInternal;
258
259import dalvik.system.CloseGuard;
260import dalvik.system.DexFile;
261import dalvik.system.VMRuntime;
262
263import libcore.io.IoUtils;
264import libcore.util.EmptyArray;
265
266import org.xmlpull.v1.XmlPullParser;
267import org.xmlpull.v1.XmlPullParserException;
268import org.xmlpull.v1.XmlSerializer;
269
270import java.io.BufferedOutputStream;
271import java.io.BufferedReader;
272import java.io.ByteArrayInputStream;
273import java.io.ByteArrayOutputStream;
274import java.io.File;
275import java.io.FileDescriptor;
276import java.io.FileInputStream;
277import java.io.FileNotFoundException;
278import java.io.FileOutputStream;
279import java.io.FileReader;
280import java.io.FilenameFilter;
281import java.io.IOException;
282import java.io.PrintWriter;
283import java.nio.charset.StandardCharsets;
284import java.security.DigestInputStream;
285import java.security.MessageDigest;
286import java.security.NoSuchAlgorithmException;
287import java.security.PublicKey;
288import java.security.cert.Certificate;
289import java.security.cert.CertificateEncodingException;
290import java.security.cert.CertificateException;
291import java.text.SimpleDateFormat;
292import java.util.ArrayList;
293import java.util.Arrays;
294import java.util.Collection;
295import java.util.Collections;
296import java.util.Comparator;
297import java.util.Date;
298import java.util.HashSet;
299import java.util.Iterator;
300import java.util.List;
301import java.util.Map;
302import java.util.Objects;
303import java.util.Set;
304import java.util.concurrent.CountDownLatch;
305import java.util.concurrent.TimeUnit;
306import java.util.concurrent.atomic.AtomicBoolean;
307import java.util.concurrent.atomic.AtomicInteger;
308
309/**
310 * Keep track of all those APKs everywhere.
311 * <p>
312 * Internally there are two important locks:
313 * <ul>
314 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
315 * and other related state. It is a fine-grained lock that should only be held
316 * momentarily, as it's one of the most contended locks in the system.
317 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
318 * operations typically involve heavy lifting of application data on disk. Since
319 * {@code installd} is single-threaded, and it's operations can often be slow,
320 * this lock should never be acquired while already holding {@link #mPackages}.
321 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
322 * holding {@link #mInstallLock}.
323 * </ul>
324 * Many internal methods rely on the caller to hold the appropriate locks, and
325 * this contract is expressed through method name suffixes:
326 * <ul>
327 * <li>fooLI(): the caller must hold {@link #mInstallLock}
328 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
329 * being modified must be frozen
330 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
331 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
332 * </ul>
333 * <p>
334 * Because this class is very central to the platform's security; please run all
335 * CTS and unit tests whenever making modifications:
336 *
337 * <pre>
338 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
339 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
340 * </pre>
341 */
342public class PackageManagerService extends IPackageManager.Stub {
343    static final String TAG = "PackageManager";
344    static final boolean DEBUG_SETTINGS = false;
345    static final boolean DEBUG_PREFERRED = false;
346    static final boolean DEBUG_UPGRADE = false;
347    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
348    private static final boolean DEBUG_BACKUP = false;
349    private static final boolean DEBUG_INSTALL = false;
350    private static final boolean DEBUG_REMOVE = false;
351    private static final boolean DEBUG_BROADCASTS = false;
352    private static final boolean DEBUG_SHOW_INFO = false;
353    private static final boolean DEBUG_PACKAGE_INFO = false;
354    private static final boolean DEBUG_INTENT_MATCHING = false;
355    private static final boolean DEBUG_PACKAGE_SCANNING = false;
356    private static final boolean DEBUG_VERIFY = false;
357    private static final boolean DEBUG_FILTERS = false;
358
359    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
360    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
361    // user, but by default initialize to this.
362    static final boolean DEBUG_DEXOPT = false;
363
364    private static final boolean DEBUG_ABI_SELECTION = false;
365    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
366    private static final boolean DEBUG_TRIAGED_MISSING = false;
367    private static final boolean DEBUG_APP_DATA = false;
368
369    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
370    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
371
372    private static final boolean DISABLE_EPHEMERAL_APPS = false;
373    private static final boolean HIDE_EPHEMERAL_APIS = true;
374
375    private static final int RADIO_UID = Process.PHONE_UID;
376    private static final int LOG_UID = Process.LOG_UID;
377    private static final int NFC_UID = Process.NFC_UID;
378    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
379    private static final int SHELL_UID = Process.SHELL_UID;
380
381    // Cap the size of permission trees that 3rd party apps can define
382    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
383
384    // Suffix used during package installation when copying/moving
385    // package apks to install directory.
386    private static final String INSTALL_PACKAGE_SUFFIX = "-";
387
388    static final int SCAN_NO_DEX = 1<<1;
389    static final int SCAN_FORCE_DEX = 1<<2;
390    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
391    static final int SCAN_NEW_INSTALL = 1<<4;
392    static final int SCAN_NO_PATHS = 1<<5;
393    static final int SCAN_UPDATE_TIME = 1<<6;
394    static final int SCAN_DEFER_DEX = 1<<7;
395    static final int SCAN_BOOTING = 1<<8;
396    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
397    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
398    static final int SCAN_REPLACING = 1<<11;
399    static final int SCAN_REQUIRE_KNOWN = 1<<12;
400    static final int SCAN_MOVE = 1<<13;
401    static final int SCAN_INITIAL = 1<<14;
402    static final int SCAN_CHECK_ONLY = 1<<15;
403    static final int SCAN_DONT_KILL_APP = 1<<17;
404    static final int SCAN_IGNORE_FROZEN = 1<<18;
405
406    static final int REMOVE_CHATTY = 1<<16;
407
408    private static final int[] EMPTY_INT_ARRAY = new int[0];
409
410    /**
411     * Timeout (in milliseconds) after which the watchdog should declare that
412     * our handler thread is wedged.  The usual default for such things is one
413     * minute but we sometimes do very lengthy I/O operations on this thread,
414     * such as installing multi-gigabyte applications, so ours needs to be longer.
415     */
416    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
417
418    /**
419     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
420     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
421     * settings entry if available, otherwise we use the hardcoded default.  If it's been
422     * more than this long since the last fstrim, we force one during the boot sequence.
423     *
424     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
425     * one gets run at the next available charging+idle time.  This final mandatory
426     * no-fstrim check kicks in only of the other scheduling criteria is never met.
427     */
428    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
429
430    /**
431     * Whether verification is enabled by default.
432     */
433    private static final boolean DEFAULT_VERIFY_ENABLE = true;
434
435    /**
436     * The default maximum time to wait for the verification agent to return in
437     * milliseconds.
438     */
439    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
440
441    /**
442     * The default response for package verification timeout.
443     *
444     * This can be either PackageManager.VERIFICATION_ALLOW or
445     * PackageManager.VERIFICATION_REJECT.
446     */
447    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
448
449    static final String PLATFORM_PACKAGE_NAME = "android";
450
451    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
452
453    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
454            DEFAULT_CONTAINER_PACKAGE,
455            "com.android.defcontainer.DefaultContainerService");
456
457    private static final String KILL_APP_REASON_GIDS_CHANGED =
458            "permission grant or revoke changed gids";
459
460    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
461            "permissions revoked";
462
463    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
464
465    private static final String PACKAGE_SCHEME = "package";
466
467    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
468    /**
469     * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
470     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
471     * VENDOR_OVERLAY_DIR.
472     */
473    private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
474    /**
475     * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever
476     * is in VENDOR_OVERLAY_THEME_PROPERTY.
477     */
478    private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY
479            = "persist.vendor.overlay.theme";
480
481    /** Permission grant: not grant the permission. */
482    private static final int GRANT_DENIED = 1;
483
484    /** Permission grant: grant the permission as an install permission. */
485    private static final int GRANT_INSTALL = 2;
486
487    /** Permission grant: grant the permission as a runtime one. */
488    private static final int GRANT_RUNTIME = 3;
489
490    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
491    private static final int GRANT_UPGRADE = 4;
492
493    /** Canonical intent used to identify what counts as a "web browser" app */
494    private static final Intent sBrowserIntent;
495    static {
496        sBrowserIntent = new Intent();
497        sBrowserIntent.setAction(Intent.ACTION_VIEW);
498        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
499        sBrowserIntent.setData(Uri.parse("http:"));
500    }
501
502    /**
503     * The set of all protected actions [i.e. those actions for which a high priority
504     * intent filter is disallowed].
505     */
506    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
507    static {
508        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
509        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
510        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
511        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
512    }
513
514    // Compilation reasons.
515    public static final int REASON_FIRST_BOOT = 0;
516    public static final int REASON_BOOT = 1;
517    public static final int REASON_INSTALL = 2;
518    public static final int REASON_BACKGROUND_DEXOPT = 3;
519    public static final int REASON_AB_OTA = 4;
520    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
521    public static final int REASON_SHARED_APK = 6;
522    public static final int REASON_FORCED_DEXOPT = 7;
523    public static final int REASON_CORE_APP = 8;
524
525    public static final int REASON_LAST = REASON_CORE_APP;
526
527    /** Special library name that skips shared libraries check during compilation. */
528    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
529
530    final ServiceThread mHandlerThread;
531
532    final PackageHandler mHandler;
533
534    private final ProcessLoggingHandler mProcessLoggingHandler;
535
536    /**
537     * Messages for {@link #mHandler} that need to wait for system ready before
538     * being dispatched.
539     */
540    private ArrayList<Message> mPostSystemReadyMessages;
541
542    final int mSdkVersion = Build.VERSION.SDK_INT;
543
544    final Context mContext;
545    final boolean mFactoryTest;
546    final boolean mOnlyCore;
547    final DisplayMetrics mMetrics;
548    final int mDefParseFlags;
549    final String[] mSeparateProcesses;
550    final boolean mIsUpgrade;
551    final boolean mIsPreNUpgrade;
552    final boolean mIsPreNMR1Upgrade;
553
554    @GuardedBy("mPackages")
555    private boolean mDexOptDialogShown;
556
557    /** The location for ASEC container files on internal storage. */
558    final String mAsecInternalPath;
559
560    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
561    // LOCK HELD.  Can be called with mInstallLock held.
562    @GuardedBy("mInstallLock")
563    final Installer mInstaller;
564
565    /** Directory where installed third-party apps stored */
566    final File mAppInstallDir;
567    final File mEphemeralInstallDir;
568
569    /**
570     * Directory to which applications installed internally have their
571     * 32 bit native libraries copied.
572     */
573    private File mAppLib32InstallDir;
574
575    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
576    // apps.
577    final File mDrmAppPrivateInstallDir;
578
579    // ----------------------------------------------------------------
580
581    // Lock for state used when installing and doing other long running
582    // operations.  Methods that must be called with this lock held have
583    // the suffix "LI".
584    final Object mInstallLock = new Object();
585
586    // ----------------------------------------------------------------
587
588    // Keys are String (package name), values are Package.  This also serves
589    // as the lock for the global state.  Methods that must be called with
590    // this lock held have the prefix "LP".
591    @GuardedBy("mPackages")
592    final ArrayMap<String, PackageParser.Package> mPackages =
593            new ArrayMap<String, PackageParser.Package>();
594
595    final ArrayMap<String, Set<String>> mKnownCodebase =
596            new ArrayMap<String, Set<String>>();
597
598    // Tracks available target package names -> overlay package paths.
599    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
600        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
601
602    /**
603     * Tracks new system packages [received in an OTA] that we expect to
604     * find updated user-installed versions. Keys are package name, values
605     * are package location.
606     */
607    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
608    /**
609     * Tracks high priority intent filters for protected actions. During boot, certain
610     * filter actions are protected and should never be allowed to have a high priority
611     * intent filter for them. However, there is one, and only one exception -- the
612     * setup wizard. It must be able to define a high priority intent filter for these
613     * actions to ensure there are no escapes from the wizard. We need to delay processing
614     * of these during boot as we need to look at all of the system packages in order
615     * to know which component is the setup wizard.
616     */
617    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
618    /**
619     * Whether or not processing protected filters should be deferred.
620     */
621    private boolean mDeferProtectedFilters = true;
622
623    /**
624     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
625     */
626    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
627    /**
628     * Whether or not system app permissions should be promoted from install to runtime.
629     */
630    boolean mPromoteSystemApps;
631
632    @GuardedBy("mPackages")
633    final Settings mSettings;
634
635    /**
636     * Set of package names that are currently "frozen", which means active
637     * surgery is being done on the code/data for that package. The platform
638     * will refuse to launch frozen packages to avoid race conditions.
639     *
640     * @see PackageFreezer
641     */
642    @GuardedBy("mPackages")
643    final ArraySet<String> mFrozenPackages = new ArraySet<>();
644
645    final ProtectedPackages mProtectedPackages;
646
647    boolean mFirstBoot;
648
649    // System configuration read by SystemConfig.
650    final int[] mGlobalGids;
651    final SparseArray<ArraySet<String>> mSystemPermissions;
652    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
653
654    // If mac_permissions.xml was found for seinfo labeling.
655    boolean mFoundPolicyFile;
656
657    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
658
659    public static final class SharedLibraryEntry {
660        public final String path;
661        public final String apk;
662
663        SharedLibraryEntry(String _path, String _apk) {
664            path = _path;
665            apk = _apk;
666        }
667    }
668
669    // Currently known shared libraries.
670    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
671            new ArrayMap<String, SharedLibraryEntry>();
672
673    // All available activities, for your resolving pleasure.
674    final ActivityIntentResolver mActivities =
675            new ActivityIntentResolver();
676
677    // All available receivers, for your resolving pleasure.
678    final ActivityIntentResolver mReceivers =
679            new ActivityIntentResolver();
680
681    // All available services, for your resolving pleasure.
682    final ServiceIntentResolver mServices = new ServiceIntentResolver();
683
684    // All available providers, for your resolving pleasure.
685    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
686
687    // Mapping from provider base names (first directory in content URI codePath)
688    // to the provider information.
689    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
690            new ArrayMap<String, PackageParser.Provider>();
691
692    // Mapping from instrumentation class names to info about them.
693    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
694            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
695
696    // Mapping from permission names to info about them.
697    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
698            new ArrayMap<String, PackageParser.PermissionGroup>();
699
700    // Packages whose data we have transfered into another package, thus
701    // should no longer exist.
702    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
703
704    // Broadcast actions that are only available to the system.
705    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
706
707    /** List of packages waiting for verification. */
708    final SparseArray<PackageVerificationState> mPendingVerification
709            = new SparseArray<PackageVerificationState>();
710
711    /** Set of packages associated with each app op permission. */
712    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
713
714    final PackageInstallerService mInstallerService;
715
716    private final PackageDexOptimizer mPackageDexOptimizer;
717
718    private AtomicInteger mNextMoveId = new AtomicInteger();
719    private final MoveCallbacks mMoveCallbacks;
720
721    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
722
723    // Cache of users who need badging.
724    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
725
726    /** Token for keys in mPendingVerification. */
727    private int mPendingVerificationToken = 0;
728
729    volatile boolean mSystemReady;
730    volatile boolean mSafeMode;
731    volatile boolean mHasSystemUidErrors;
732
733    ApplicationInfo mAndroidApplication;
734    final ActivityInfo mResolveActivity = new ActivityInfo();
735    final ResolveInfo mResolveInfo = new ResolveInfo();
736    ComponentName mResolveComponentName;
737    PackageParser.Package mPlatformPackage;
738    ComponentName mCustomResolverComponentName;
739
740    boolean mResolverReplaced = false;
741
742    private final @Nullable ComponentName mIntentFilterVerifierComponent;
743    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
744
745    private int mIntentFilterVerificationToken = 0;
746
747    /** Component that knows whether or not an ephemeral application exists */
748    final ComponentName mEphemeralResolverComponent;
749    /** The service connection to the ephemeral resolver */
750    final EphemeralResolverConnection mEphemeralResolverConnection;
751
752    /** Component used to install ephemeral applications */
753    final ComponentName mEphemeralInstallerComponent;
754    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
755    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
756
757    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
758            = new SparseArray<IntentFilterVerificationState>();
759
760    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
761
762    // List of packages names to keep cached, even if they are uninstalled for all users
763    private List<String> mKeepUninstalledPackages;
764
765    private UserManagerInternal mUserManagerInternal;
766
767    private static class IFVerificationParams {
768        PackageParser.Package pkg;
769        boolean replacing;
770        int userId;
771        int verifierUid;
772
773        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
774                int _userId, int _verifierUid) {
775            pkg = _pkg;
776            replacing = _replacing;
777            userId = _userId;
778            replacing = _replacing;
779            verifierUid = _verifierUid;
780        }
781    }
782
783    private interface IntentFilterVerifier<T extends IntentFilter> {
784        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
785                                               T filter, String packageName);
786        void startVerifications(int userId);
787        void receiveVerificationResponse(int verificationId);
788    }
789
790    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
791        private Context mContext;
792        private ComponentName mIntentFilterVerifierComponent;
793        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
794
795        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
796            mContext = context;
797            mIntentFilterVerifierComponent = verifierComponent;
798        }
799
800        private String getDefaultScheme() {
801            return IntentFilter.SCHEME_HTTPS;
802        }
803
804        @Override
805        public void startVerifications(int userId) {
806            // Launch verifications requests
807            int count = mCurrentIntentFilterVerifications.size();
808            for (int n=0; n<count; n++) {
809                int verificationId = mCurrentIntentFilterVerifications.get(n);
810                final IntentFilterVerificationState ivs =
811                        mIntentFilterVerificationStates.get(verificationId);
812
813                String packageName = ivs.getPackageName();
814
815                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
816                final int filterCount = filters.size();
817                ArraySet<String> domainsSet = new ArraySet<>();
818                for (int m=0; m<filterCount; m++) {
819                    PackageParser.ActivityIntentInfo filter = filters.get(m);
820                    domainsSet.addAll(filter.getHostsList());
821                }
822                synchronized (mPackages) {
823                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
824                            packageName, domainsSet) != null) {
825                        scheduleWriteSettingsLocked();
826                    }
827                }
828                sendVerificationRequest(userId, verificationId, ivs);
829            }
830            mCurrentIntentFilterVerifications.clear();
831        }
832
833        private void sendVerificationRequest(int userId, int verificationId,
834                IntentFilterVerificationState ivs) {
835
836            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
837            verificationIntent.putExtra(
838                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
839                    verificationId);
840            verificationIntent.putExtra(
841                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
842                    getDefaultScheme());
843            verificationIntent.putExtra(
844                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
845                    ivs.getHostsString());
846            verificationIntent.putExtra(
847                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
848                    ivs.getPackageName());
849            verificationIntent.setComponent(mIntentFilterVerifierComponent);
850            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
851
852            UserHandle user = new UserHandle(userId);
853            mContext.sendBroadcastAsUser(verificationIntent, user);
854            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
855                    "Sending IntentFilter verification broadcast");
856        }
857
858        public void receiveVerificationResponse(int verificationId) {
859            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
860
861            final boolean verified = ivs.isVerified();
862
863            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
864            final int count = filters.size();
865            if (DEBUG_DOMAIN_VERIFICATION) {
866                Slog.i(TAG, "Received verification response " + verificationId
867                        + " for " + count + " filters, verified=" + verified);
868            }
869            for (int n=0; n<count; n++) {
870                PackageParser.ActivityIntentInfo filter = filters.get(n);
871                filter.setVerified(verified);
872
873                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
874                        + " verified with result:" + verified + " and hosts:"
875                        + ivs.getHostsString());
876            }
877
878            mIntentFilterVerificationStates.remove(verificationId);
879
880            final String packageName = ivs.getPackageName();
881            IntentFilterVerificationInfo ivi = null;
882
883            synchronized (mPackages) {
884                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
885            }
886            if (ivi == null) {
887                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
888                        + verificationId + " packageName:" + packageName);
889                return;
890            }
891            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
892                    "Updating IntentFilterVerificationInfo for package " + packageName
893                            +" verificationId:" + verificationId);
894
895            synchronized (mPackages) {
896                if (verified) {
897                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
898                } else {
899                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
900                }
901                scheduleWriteSettingsLocked();
902
903                final int userId = ivs.getUserId();
904                if (userId != UserHandle.USER_ALL) {
905                    final int userStatus =
906                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
907
908                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
909                    boolean needUpdate = false;
910
911                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
912                    // already been set by the User thru the Disambiguation dialog
913                    switch (userStatus) {
914                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
915                            if (verified) {
916                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
917                            } else {
918                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
919                            }
920                            needUpdate = true;
921                            break;
922
923                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
924                            if (verified) {
925                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
926                                needUpdate = true;
927                            }
928                            break;
929
930                        default:
931                            // Nothing to do
932                    }
933
934                    if (needUpdate) {
935                        mSettings.updateIntentFilterVerificationStatusLPw(
936                                packageName, updatedStatus, userId);
937                        scheduleWritePackageRestrictionsLocked(userId);
938                    }
939                }
940            }
941        }
942
943        @Override
944        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
945                    ActivityIntentInfo filter, String packageName) {
946            if (!hasValidDomains(filter)) {
947                return false;
948            }
949            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
950            if (ivs == null) {
951                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
952                        packageName);
953            }
954            if (DEBUG_DOMAIN_VERIFICATION) {
955                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
956            }
957            ivs.addFilter(filter);
958            return true;
959        }
960
961        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
962                int userId, int verificationId, String packageName) {
963            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
964                    verifierUid, userId, packageName);
965            ivs.setPendingState();
966            synchronized (mPackages) {
967                mIntentFilterVerificationStates.append(verificationId, ivs);
968                mCurrentIntentFilterVerifications.add(verificationId);
969            }
970            return ivs;
971        }
972    }
973
974    private static boolean hasValidDomains(ActivityIntentInfo filter) {
975        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
976                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
977                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
978    }
979
980    // Set of pending broadcasts for aggregating enable/disable of components.
981    static class PendingPackageBroadcasts {
982        // for each user id, a map of <package name -> components within that package>
983        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
984
985        public PendingPackageBroadcasts() {
986            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
987        }
988
989        public ArrayList<String> get(int userId, String packageName) {
990            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
991            return packages.get(packageName);
992        }
993
994        public void put(int userId, String packageName, ArrayList<String> components) {
995            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
996            packages.put(packageName, components);
997        }
998
999        public void remove(int userId, String packageName) {
1000            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1001            if (packages != null) {
1002                packages.remove(packageName);
1003            }
1004        }
1005
1006        public void remove(int userId) {
1007            mUidMap.remove(userId);
1008        }
1009
1010        public int userIdCount() {
1011            return mUidMap.size();
1012        }
1013
1014        public int userIdAt(int n) {
1015            return mUidMap.keyAt(n);
1016        }
1017
1018        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1019            return mUidMap.get(userId);
1020        }
1021
1022        public int size() {
1023            // total number of pending broadcast entries across all userIds
1024            int num = 0;
1025            for (int i = 0; i< mUidMap.size(); i++) {
1026                num += mUidMap.valueAt(i).size();
1027            }
1028            return num;
1029        }
1030
1031        public void clear() {
1032            mUidMap.clear();
1033        }
1034
1035        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1036            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1037            if (map == null) {
1038                map = new ArrayMap<String, ArrayList<String>>();
1039                mUidMap.put(userId, map);
1040            }
1041            return map;
1042        }
1043    }
1044    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1045
1046    // Service Connection to remote media container service to copy
1047    // package uri's from external media onto secure containers
1048    // or internal storage.
1049    private IMediaContainerService mContainerService = null;
1050
1051    static final int SEND_PENDING_BROADCAST = 1;
1052    static final int MCS_BOUND = 3;
1053    static final int END_COPY = 4;
1054    static final int INIT_COPY = 5;
1055    static final int MCS_UNBIND = 6;
1056    static final int START_CLEANING_PACKAGE = 7;
1057    static final int FIND_INSTALL_LOC = 8;
1058    static final int POST_INSTALL = 9;
1059    static final int MCS_RECONNECT = 10;
1060    static final int MCS_GIVE_UP = 11;
1061    static final int UPDATED_MEDIA_STATUS = 12;
1062    static final int WRITE_SETTINGS = 13;
1063    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1064    static final int PACKAGE_VERIFIED = 15;
1065    static final int CHECK_PENDING_VERIFICATION = 16;
1066    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1067    static final int INTENT_FILTER_VERIFIED = 18;
1068    static final int WRITE_PACKAGE_LIST = 19;
1069
1070    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1071
1072    // Delay time in millisecs
1073    static final int BROADCAST_DELAY = 10 * 1000;
1074
1075    static UserManagerService sUserManager;
1076
1077    // Stores a list of users whose package restrictions file needs to be updated
1078    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1079
1080    final private DefaultContainerConnection mDefContainerConn =
1081            new DefaultContainerConnection();
1082    class DefaultContainerConnection implements ServiceConnection {
1083        public void onServiceConnected(ComponentName name, IBinder service) {
1084            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1085            final IMediaContainerService imcs = IMediaContainerService.Stub
1086                    .asInterface(Binder.allowBlocking(service));
1087            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1088        }
1089
1090        public void onServiceDisconnected(ComponentName name) {
1091            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1092        }
1093    }
1094
1095    // Recordkeeping of restore-after-install operations that are currently in flight
1096    // between the Package Manager and the Backup Manager
1097    static class PostInstallData {
1098        public InstallArgs args;
1099        public PackageInstalledInfo res;
1100
1101        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1102            args = _a;
1103            res = _r;
1104        }
1105    }
1106
1107    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1108    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1109
1110    // XML tags for backup/restore of various bits of state
1111    private static final String TAG_PREFERRED_BACKUP = "pa";
1112    private static final String TAG_DEFAULT_APPS = "da";
1113    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1114
1115    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1116    private static final String TAG_ALL_GRANTS = "rt-grants";
1117    private static final String TAG_GRANT = "grant";
1118    private static final String ATTR_PACKAGE_NAME = "pkg";
1119
1120    private static final String TAG_PERMISSION = "perm";
1121    private static final String ATTR_PERMISSION_NAME = "name";
1122    private static final String ATTR_IS_GRANTED = "g";
1123    private static final String ATTR_USER_SET = "set";
1124    private static final String ATTR_USER_FIXED = "fixed";
1125    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1126
1127    // System/policy permission grants are not backed up
1128    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1129            FLAG_PERMISSION_POLICY_FIXED
1130            | FLAG_PERMISSION_SYSTEM_FIXED
1131            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1132
1133    // And we back up these user-adjusted states
1134    private static final int USER_RUNTIME_GRANT_MASK =
1135            FLAG_PERMISSION_USER_SET
1136            | FLAG_PERMISSION_USER_FIXED
1137            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1138
1139    final @Nullable String mRequiredVerifierPackage;
1140    final @NonNull String mRequiredInstallerPackage;
1141    final @NonNull String mRequiredUninstallerPackage;
1142    final @Nullable String mSetupWizardPackage;
1143    final @Nullable String mStorageManagerPackage;
1144    final @NonNull String mServicesSystemSharedLibraryPackageName;
1145    final @NonNull String mSharedSystemSharedLibraryPackageName;
1146
1147    final boolean mPermissionReviewRequired;
1148
1149    private final PackageUsage mPackageUsage = new PackageUsage();
1150    private final CompilerStats mCompilerStats = new CompilerStats();
1151
1152    class PackageHandler extends Handler {
1153        private boolean mBound = false;
1154        final ArrayList<HandlerParams> mPendingInstalls =
1155            new ArrayList<HandlerParams>();
1156
1157        private boolean connectToService() {
1158            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1159                    " DefaultContainerService");
1160            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1161            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1162            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1163                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1164                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1165                mBound = true;
1166                return true;
1167            }
1168            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1169            return false;
1170        }
1171
1172        private void disconnectService() {
1173            mContainerService = null;
1174            mBound = false;
1175            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1176            mContext.unbindService(mDefContainerConn);
1177            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1178        }
1179
1180        PackageHandler(Looper looper) {
1181            super(looper);
1182        }
1183
1184        public void handleMessage(Message msg) {
1185            try {
1186                doHandleMessage(msg);
1187            } finally {
1188                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1189            }
1190        }
1191
1192        void doHandleMessage(Message msg) {
1193            switch (msg.what) {
1194                case INIT_COPY: {
1195                    HandlerParams params = (HandlerParams) msg.obj;
1196                    int idx = mPendingInstalls.size();
1197                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1198                    // If a bind was already initiated we dont really
1199                    // need to do anything. The pending install
1200                    // will be processed later on.
1201                    if (!mBound) {
1202                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1203                                System.identityHashCode(mHandler));
1204                        // If this is the only one pending we might
1205                        // have to bind to the service again.
1206                        if (!connectToService()) {
1207                            Slog.e(TAG, "Failed to bind to media container service");
1208                            params.serviceError();
1209                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1210                                    System.identityHashCode(mHandler));
1211                            if (params.traceMethod != null) {
1212                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1213                                        params.traceCookie);
1214                            }
1215                            return;
1216                        } else {
1217                            // Once we bind to the service, the first
1218                            // pending request will be processed.
1219                            mPendingInstalls.add(idx, params);
1220                        }
1221                    } else {
1222                        mPendingInstalls.add(idx, params);
1223                        // Already bound to the service. Just make
1224                        // sure we trigger off processing the first request.
1225                        if (idx == 0) {
1226                            mHandler.sendEmptyMessage(MCS_BOUND);
1227                        }
1228                    }
1229                    break;
1230                }
1231                case MCS_BOUND: {
1232                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1233                    if (msg.obj != null) {
1234                        mContainerService = (IMediaContainerService) msg.obj;
1235                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1236                                System.identityHashCode(mHandler));
1237                    }
1238                    if (mContainerService == null) {
1239                        if (!mBound) {
1240                            // Something seriously wrong since we are not bound and we are not
1241                            // waiting for connection. Bail out.
1242                            Slog.e(TAG, "Cannot bind to media container service");
1243                            for (HandlerParams params : mPendingInstalls) {
1244                                // Indicate service bind error
1245                                params.serviceError();
1246                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1247                                        System.identityHashCode(params));
1248                                if (params.traceMethod != null) {
1249                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1250                                            params.traceMethod, params.traceCookie);
1251                                }
1252                                return;
1253                            }
1254                            mPendingInstalls.clear();
1255                        } else {
1256                            Slog.w(TAG, "Waiting to connect to media container service");
1257                        }
1258                    } else if (mPendingInstalls.size() > 0) {
1259                        HandlerParams params = mPendingInstalls.get(0);
1260                        if (params != null) {
1261                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1262                                    System.identityHashCode(params));
1263                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1264                            if (params.startCopy()) {
1265                                // We are done...  look for more work or to
1266                                // go idle.
1267                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1268                                        "Checking for more work or unbind...");
1269                                // Delete pending install
1270                                if (mPendingInstalls.size() > 0) {
1271                                    mPendingInstalls.remove(0);
1272                                }
1273                                if (mPendingInstalls.size() == 0) {
1274                                    if (mBound) {
1275                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1276                                                "Posting delayed MCS_UNBIND");
1277                                        removeMessages(MCS_UNBIND);
1278                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1279                                        // Unbind after a little delay, to avoid
1280                                        // continual thrashing.
1281                                        sendMessageDelayed(ubmsg, 10000);
1282                                    }
1283                                } else {
1284                                    // There are more pending requests in queue.
1285                                    // Just post MCS_BOUND message to trigger processing
1286                                    // of next pending install.
1287                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1288                                            "Posting MCS_BOUND for next work");
1289                                    mHandler.sendEmptyMessage(MCS_BOUND);
1290                                }
1291                            }
1292                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1293                        }
1294                    } else {
1295                        // Should never happen ideally.
1296                        Slog.w(TAG, "Empty queue");
1297                    }
1298                    break;
1299                }
1300                case MCS_RECONNECT: {
1301                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1302                    if (mPendingInstalls.size() > 0) {
1303                        if (mBound) {
1304                            disconnectService();
1305                        }
1306                        if (!connectToService()) {
1307                            Slog.e(TAG, "Failed to bind to media container service");
1308                            for (HandlerParams params : mPendingInstalls) {
1309                                // Indicate service bind error
1310                                params.serviceError();
1311                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1312                                        System.identityHashCode(params));
1313                            }
1314                            mPendingInstalls.clear();
1315                        }
1316                    }
1317                    break;
1318                }
1319                case MCS_UNBIND: {
1320                    // If there is no actual work left, then time to unbind.
1321                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1322
1323                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1324                        if (mBound) {
1325                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1326
1327                            disconnectService();
1328                        }
1329                    } else if (mPendingInstalls.size() > 0) {
1330                        // There are more pending requests in queue.
1331                        // Just post MCS_BOUND message to trigger processing
1332                        // of next pending install.
1333                        mHandler.sendEmptyMessage(MCS_BOUND);
1334                    }
1335
1336                    break;
1337                }
1338                case MCS_GIVE_UP: {
1339                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1340                    HandlerParams params = mPendingInstalls.remove(0);
1341                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1342                            System.identityHashCode(params));
1343                    break;
1344                }
1345                case SEND_PENDING_BROADCAST: {
1346                    String packages[];
1347                    ArrayList<String> components[];
1348                    int size = 0;
1349                    int uids[];
1350                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1351                    synchronized (mPackages) {
1352                        if (mPendingBroadcasts == null) {
1353                            return;
1354                        }
1355                        size = mPendingBroadcasts.size();
1356                        if (size <= 0) {
1357                            // Nothing to be done. Just return
1358                            return;
1359                        }
1360                        packages = new String[size];
1361                        components = new ArrayList[size];
1362                        uids = new int[size];
1363                        int i = 0;  // filling out the above arrays
1364
1365                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1366                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1367                            Iterator<Map.Entry<String, ArrayList<String>>> it
1368                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1369                                            .entrySet().iterator();
1370                            while (it.hasNext() && i < size) {
1371                                Map.Entry<String, ArrayList<String>> ent = it.next();
1372                                packages[i] = ent.getKey();
1373                                components[i] = ent.getValue();
1374                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1375                                uids[i] = (ps != null)
1376                                        ? UserHandle.getUid(packageUserId, ps.appId)
1377                                        : -1;
1378                                i++;
1379                            }
1380                        }
1381                        size = i;
1382                        mPendingBroadcasts.clear();
1383                    }
1384                    // Send broadcasts
1385                    for (int i = 0; i < size; i++) {
1386                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1387                    }
1388                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1389                    break;
1390                }
1391                case START_CLEANING_PACKAGE: {
1392                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1393                    final String packageName = (String)msg.obj;
1394                    final int userId = msg.arg1;
1395                    final boolean andCode = msg.arg2 != 0;
1396                    synchronized (mPackages) {
1397                        if (userId == UserHandle.USER_ALL) {
1398                            int[] users = sUserManager.getUserIds();
1399                            for (int user : users) {
1400                                mSettings.addPackageToCleanLPw(
1401                                        new PackageCleanItem(user, packageName, andCode));
1402                            }
1403                        } else {
1404                            mSettings.addPackageToCleanLPw(
1405                                    new PackageCleanItem(userId, packageName, andCode));
1406                        }
1407                    }
1408                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1409                    startCleaningPackages();
1410                } break;
1411                case POST_INSTALL: {
1412                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1413
1414                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1415                    final boolean didRestore = (msg.arg2 != 0);
1416                    mRunningInstalls.delete(msg.arg1);
1417
1418                    if (data != null) {
1419                        InstallArgs args = data.args;
1420                        PackageInstalledInfo parentRes = data.res;
1421
1422                        final boolean grantPermissions = (args.installFlags
1423                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1424                        final boolean killApp = (args.installFlags
1425                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1426                        final String[] grantedPermissions = args.installGrantPermissions;
1427
1428                        // Handle the parent package
1429                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1430                                grantedPermissions, didRestore, args.installerPackageName,
1431                                args.observer);
1432
1433                        // Handle the child packages
1434                        final int childCount = (parentRes.addedChildPackages != null)
1435                                ? parentRes.addedChildPackages.size() : 0;
1436                        for (int i = 0; i < childCount; i++) {
1437                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1438                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1439                                    grantedPermissions, false, args.installerPackageName,
1440                                    args.observer);
1441                        }
1442
1443                        // Log tracing if needed
1444                        if (args.traceMethod != null) {
1445                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1446                                    args.traceCookie);
1447                        }
1448                    } else {
1449                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1450                    }
1451
1452                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1453                } break;
1454                case UPDATED_MEDIA_STATUS: {
1455                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1456                    boolean reportStatus = msg.arg1 == 1;
1457                    boolean doGc = msg.arg2 == 1;
1458                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1459                    if (doGc) {
1460                        // Force a gc to clear up stale containers.
1461                        Runtime.getRuntime().gc();
1462                    }
1463                    if (msg.obj != null) {
1464                        @SuppressWarnings("unchecked")
1465                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1466                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1467                        // Unload containers
1468                        unloadAllContainers(args);
1469                    }
1470                    if (reportStatus) {
1471                        try {
1472                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1473                            PackageHelper.getMountService().finishMediaUpdate();
1474                        } catch (RemoteException e) {
1475                            Log.e(TAG, "MountService not running?");
1476                        }
1477                    }
1478                } break;
1479                case WRITE_SETTINGS: {
1480                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1481                    synchronized (mPackages) {
1482                        removeMessages(WRITE_SETTINGS);
1483                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1484                        mSettings.writeLPr();
1485                        mDirtyUsers.clear();
1486                    }
1487                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1488                } break;
1489                case WRITE_PACKAGE_RESTRICTIONS: {
1490                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1491                    synchronized (mPackages) {
1492                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1493                        for (int userId : mDirtyUsers) {
1494                            mSettings.writePackageRestrictionsLPr(userId);
1495                        }
1496                        mDirtyUsers.clear();
1497                    }
1498                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1499                } break;
1500                case WRITE_PACKAGE_LIST: {
1501                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1502                    synchronized (mPackages) {
1503                        removeMessages(WRITE_PACKAGE_LIST);
1504                        mSettings.writePackageListLPr(msg.arg1);
1505                    }
1506                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1507                } break;
1508                case CHECK_PENDING_VERIFICATION: {
1509                    final int verificationId = msg.arg1;
1510                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1511
1512                    if ((state != null) && !state.timeoutExtended()) {
1513                        final InstallArgs args = state.getInstallArgs();
1514                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1515
1516                        Slog.i(TAG, "Verification timed out for " + originUri);
1517                        mPendingVerification.remove(verificationId);
1518
1519                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1520
1521                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1522                            Slog.i(TAG, "Continuing with installation of " + originUri);
1523                            state.setVerifierResponse(Binder.getCallingUid(),
1524                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1525                            broadcastPackageVerified(verificationId, originUri,
1526                                    PackageManager.VERIFICATION_ALLOW,
1527                                    state.getInstallArgs().getUser());
1528                            try {
1529                                ret = args.copyApk(mContainerService, true);
1530                            } catch (RemoteException e) {
1531                                Slog.e(TAG, "Could not contact the ContainerService");
1532                            }
1533                        } else {
1534                            broadcastPackageVerified(verificationId, originUri,
1535                                    PackageManager.VERIFICATION_REJECT,
1536                                    state.getInstallArgs().getUser());
1537                        }
1538
1539                        Trace.asyncTraceEnd(
1540                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1541
1542                        processPendingInstall(args, ret);
1543                        mHandler.sendEmptyMessage(MCS_UNBIND);
1544                    }
1545                    break;
1546                }
1547                case PACKAGE_VERIFIED: {
1548                    final int verificationId = msg.arg1;
1549
1550                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1551                    if (state == null) {
1552                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1553                        break;
1554                    }
1555
1556                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1557
1558                    state.setVerifierResponse(response.callerUid, response.code);
1559
1560                    if (state.isVerificationComplete()) {
1561                        mPendingVerification.remove(verificationId);
1562
1563                        final InstallArgs args = state.getInstallArgs();
1564                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1565
1566                        int ret;
1567                        if (state.isInstallAllowed()) {
1568                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1569                            broadcastPackageVerified(verificationId, originUri,
1570                                    response.code, state.getInstallArgs().getUser());
1571                            try {
1572                                ret = args.copyApk(mContainerService, true);
1573                            } catch (RemoteException e) {
1574                                Slog.e(TAG, "Could not contact the ContainerService");
1575                            }
1576                        } else {
1577                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1578                        }
1579
1580                        Trace.asyncTraceEnd(
1581                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1582
1583                        processPendingInstall(args, ret);
1584                        mHandler.sendEmptyMessage(MCS_UNBIND);
1585                    }
1586
1587                    break;
1588                }
1589                case START_INTENT_FILTER_VERIFICATIONS: {
1590                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1591                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1592                            params.replacing, params.pkg);
1593                    break;
1594                }
1595                case INTENT_FILTER_VERIFIED: {
1596                    final int verificationId = msg.arg1;
1597
1598                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1599                            verificationId);
1600                    if (state == null) {
1601                        Slog.w(TAG, "Invalid IntentFilter verification token "
1602                                + verificationId + " received");
1603                        break;
1604                    }
1605
1606                    final int userId = state.getUserId();
1607
1608                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1609                            "Processing IntentFilter verification with token:"
1610                            + verificationId + " and userId:" + userId);
1611
1612                    final IntentFilterVerificationResponse response =
1613                            (IntentFilterVerificationResponse) msg.obj;
1614
1615                    state.setVerifierResponse(response.callerUid, response.code);
1616
1617                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1618                            "IntentFilter verification with token:" + verificationId
1619                            + " and userId:" + userId
1620                            + " is settings verifier response with response code:"
1621                            + response.code);
1622
1623                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1624                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1625                                + response.getFailedDomainsString());
1626                    }
1627
1628                    if (state.isVerificationComplete()) {
1629                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1630                    } else {
1631                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1632                                "IntentFilter verification with token:" + verificationId
1633                                + " was not said to be complete");
1634                    }
1635
1636                    break;
1637                }
1638            }
1639        }
1640    }
1641
1642    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1643            boolean killApp, String[] grantedPermissions,
1644            boolean launchedForRestore, String installerPackage,
1645            IPackageInstallObserver2 installObserver) {
1646        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1647            // Send the removed broadcasts
1648            if (res.removedInfo != null) {
1649                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1650            }
1651
1652            // Now that we successfully installed the package, grant runtime
1653            // permissions if requested before broadcasting the install.
1654            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1655                    >= Build.VERSION_CODES.M) {
1656                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1657            }
1658
1659            final boolean update = res.removedInfo != null
1660                    && res.removedInfo.removedPackage != null;
1661
1662            // If this is the first time we have child packages for a disabled privileged
1663            // app that had no children, we grant requested runtime permissions to the new
1664            // children if the parent on the system image had them already granted.
1665            if (res.pkg.parentPackage != null) {
1666                synchronized (mPackages) {
1667                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1668                }
1669            }
1670
1671            synchronized (mPackages) {
1672                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1673            }
1674
1675            final String packageName = res.pkg.applicationInfo.packageName;
1676
1677            // Determine the set of users who are adding this package for
1678            // the first time vs. those who are seeing an update.
1679            int[] firstUsers = EMPTY_INT_ARRAY;
1680            int[] updateUsers = EMPTY_INT_ARRAY;
1681            if (res.origUsers == null || res.origUsers.length == 0) {
1682                firstUsers = res.newUsers;
1683            } else {
1684                for (int newUser : res.newUsers) {
1685                    boolean isNew = true;
1686                    for (int origUser : res.origUsers) {
1687                        if (origUser == newUser) {
1688                            isNew = false;
1689                            break;
1690                        }
1691                    }
1692                    if (isNew) {
1693                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1694                    } else {
1695                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1696                    }
1697                }
1698            }
1699
1700            // Send installed broadcasts if the install/update is not ephemeral
1701            if (!isEphemeral(res.pkg)) {
1702                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1703
1704                // Send added for users that see the package for the first time
1705                // sendPackageAddedForNewUsers also deals with system apps
1706                int appId = UserHandle.getAppId(res.uid);
1707                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1708                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1709
1710                // Send added for users that don't see the package for the first time
1711                Bundle extras = new Bundle(1);
1712                extras.putInt(Intent.EXTRA_UID, res.uid);
1713                if (update) {
1714                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1715                }
1716                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1717                        extras, 0 /*flags*/, null /*targetPackage*/,
1718                        null /*finishedReceiver*/, updateUsers);
1719
1720                // Send replaced for users that don't see the package for the first time
1721                if (update) {
1722                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1723                            packageName, extras, 0 /*flags*/,
1724                            null /*targetPackage*/, null /*finishedReceiver*/,
1725                            updateUsers);
1726                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1727                            null /*package*/, null /*extras*/, 0 /*flags*/,
1728                            packageName /*targetPackage*/,
1729                            null /*finishedReceiver*/, updateUsers);
1730                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1731                    // First-install and we did a restore, so we're responsible for the
1732                    // first-launch broadcast.
1733                    if (DEBUG_BACKUP) {
1734                        Slog.i(TAG, "Post-restore of " + packageName
1735                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1736                    }
1737                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1738                }
1739
1740                // Send broadcast package appeared if forward locked/external for all users
1741                // treat asec-hosted packages like removable media on upgrade
1742                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1743                    if (DEBUG_INSTALL) {
1744                        Slog.i(TAG, "upgrading pkg " + res.pkg
1745                                + " is ASEC-hosted -> AVAILABLE");
1746                    }
1747                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1748                    ArrayList<String> pkgList = new ArrayList<>(1);
1749                    pkgList.add(packageName);
1750                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1751                }
1752            }
1753
1754            // Work that needs to happen on first install within each user
1755            if (firstUsers != null && firstUsers.length > 0) {
1756                synchronized (mPackages) {
1757                    for (int userId : firstUsers) {
1758                        // If this app is a browser and it's newly-installed for some
1759                        // users, clear any default-browser state in those users. The
1760                        // app's nature doesn't depend on the user, so we can just check
1761                        // its browser nature in any user and generalize.
1762                        if (packageIsBrowser(packageName, userId)) {
1763                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1764                        }
1765
1766                        // We may also need to apply pending (restored) runtime
1767                        // permission grants within these users.
1768                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1769                    }
1770                }
1771            }
1772
1773            // Log current value of "unknown sources" setting
1774            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1775                    getUnknownSourcesSettings());
1776
1777            // Force a gc to clear up things
1778            Runtime.getRuntime().gc();
1779
1780            // Remove the replaced package's older resources safely now
1781            // We delete after a gc for applications  on sdcard.
1782            if (res.removedInfo != null && res.removedInfo.args != null) {
1783                synchronized (mInstallLock) {
1784                    res.removedInfo.args.doPostDeleteLI(true);
1785                }
1786            }
1787        }
1788
1789        // If someone is watching installs - notify them
1790        if (installObserver != null) {
1791            try {
1792                Bundle extras = extrasForInstallResult(res);
1793                installObserver.onPackageInstalled(res.name, res.returnCode,
1794                        res.returnMsg, extras);
1795            } catch (RemoteException e) {
1796                Slog.i(TAG, "Observer no longer exists.");
1797            }
1798        }
1799    }
1800
1801    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1802            PackageParser.Package pkg) {
1803        if (pkg.parentPackage == null) {
1804            return;
1805        }
1806        if (pkg.requestedPermissions == null) {
1807            return;
1808        }
1809        final PackageSetting disabledSysParentPs = mSettings
1810                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1811        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1812                || !disabledSysParentPs.isPrivileged()
1813                || (disabledSysParentPs.childPackageNames != null
1814                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1815            return;
1816        }
1817        final int[] allUserIds = sUserManager.getUserIds();
1818        final int permCount = pkg.requestedPermissions.size();
1819        for (int i = 0; i < permCount; i++) {
1820            String permission = pkg.requestedPermissions.get(i);
1821            BasePermission bp = mSettings.mPermissions.get(permission);
1822            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1823                continue;
1824            }
1825            for (int userId : allUserIds) {
1826                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1827                        permission, userId)) {
1828                    grantRuntimePermission(pkg.packageName, permission, userId);
1829                }
1830            }
1831        }
1832    }
1833
1834    private StorageEventListener mStorageListener = new StorageEventListener() {
1835        @Override
1836        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1837            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1838                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1839                    final String volumeUuid = vol.getFsUuid();
1840
1841                    // Clean up any users or apps that were removed or recreated
1842                    // while this volume was missing
1843                    reconcileUsers(volumeUuid);
1844                    reconcileApps(volumeUuid);
1845
1846                    // Clean up any install sessions that expired or were
1847                    // cancelled while this volume was missing
1848                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1849
1850                    loadPrivatePackages(vol);
1851
1852                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1853                    unloadPrivatePackages(vol);
1854                }
1855            }
1856
1857            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1858                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1859                    updateExternalMediaStatus(true, false);
1860                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1861                    updateExternalMediaStatus(false, false);
1862                }
1863            }
1864        }
1865
1866        @Override
1867        public void onVolumeForgotten(String fsUuid) {
1868            if (TextUtils.isEmpty(fsUuid)) {
1869                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1870                return;
1871            }
1872
1873            // Remove any apps installed on the forgotten volume
1874            synchronized (mPackages) {
1875                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1876                for (PackageSetting ps : packages) {
1877                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1878                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1879                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1880
1881                    // Try very hard to release any references to this package
1882                    // so we don't risk the system server being killed due to
1883                    // open FDs
1884                    AttributeCache.instance().removePackage(ps.name);
1885                }
1886
1887                mSettings.onVolumeForgotten(fsUuid);
1888                mSettings.writeLPr();
1889            }
1890        }
1891    };
1892
1893    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1894            String[] grantedPermissions) {
1895        for (int userId : userIds) {
1896            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1897        }
1898
1899        // We could have touched GID membership, so flush out packages.list
1900        synchronized (mPackages) {
1901            mSettings.writePackageListLPr();
1902        }
1903    }
1904
1905    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1906            String[] grantedPermissions) {
1907        SettingBase sb = (SettingBase) pkg.mExtras;
1908        if (sb == null) {
1909            return;
1910        }
1911
1912        PermissionsState permissionsState = sb.getPermissionsState();
1913
1914        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1915                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1916
1917        for (String permission : pkg.requestedPermissions) {
1918            final BasePermission bp;
1919            synchronized (mPackages) {
1920                bp = mSettings.mPermissions.get(permission);
1921            }
1922            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1923                    && (grantedPermissions == null
1924                           || ArrayUtils.contains(grantedPermissions, permission))) {
1925                final int flags = permissionsState.getPermissionFlags(permission, userId);
1926                // Installer cannot change immutable permissions.
1927                if ((flags & immutableFlags) == 0) {
1928                    grantRuntimePermission(pkg.packageName, permission, userId);
1929                }
1930            }
1931        }
1932    }
1933
1934    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1935        Bundle extras = null;
1936        switch (res.returnCode) {
1937            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1938                extras = new Bundle();
1939                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1940                        res.origPermission);
1941                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1942                        res.origPackage);
1943                break;
1944            }
1945            case PackageManager.INSTALL_SUCCEEDED: {
1946                extras = new Bundle();
1947                extras.putBoolean(Intent.EXTRA_REPLACING,
1948                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1949                break;
1950            }
1951        }
1952        return extras;
1953    }
1954
1955    void scheduleWriteSettingsLocked() {
1956        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1957            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1958        }
1959    }
1960
1961    void scheduleWritePackageListLocked(int userId) {
1962        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1963            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1964            msg.arg1 = userId;
1965            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1966        }
1967    }
1968
1969    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1970        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1971        scheduleWritePackageRestrictionsLocked(userId);
1972    }
1973
1974    void scheduleWritePackageRestrictionsLocked(int userId) {
1975        final int[] userIds = (userId == UserHandle.USER_ALL)
1976                ? sUserManager.getUserIds() : new int[]{userId};
1977        for (int nextUserId : userIds) {
1978            if (!sUserManager.exists(nextUserId)) return;
1979            mDirtyUsers.add(nextUserId);
1980            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1981                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1982            }
1983        }
1984    }
1985
1986    public static PackageManagerService main(Context context, Installer installer,
1987            boolean factoryTest, boolean onlyCore) {
1988        // Self-check for initial settings.
1989        PackageManagerServiceCompilerMapping.checkProperties();
1990
1991        PackageManagerService m = new PackageManagerService(context, installer,
1992                factoryTest, onlyCore);
1993        m.enableSystemUserPackages();
1994        ServiceManager.addService("package", m);
1995        return m;
1996    }
1997
1998    private void enableSystemUserPackages() {
1999        if (!UserManager.isSplitSystemUser()) {
2000            return;
2001        }
2002        // For system user, enable apps based on the following conditions:
2003        // - app is whitelisted or belong to one of these groups:
2004        //   -- system app which has no launcher icons
2005        //   -- system app which has INTERACT_ACROSS_USERS permission
2006        //   -- system IME app
2007        // - app is not in the blacklist
2008        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2009        Set<String> enableApps = new ArraySet<>();
2010        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2011                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2012                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2013        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2014        enableApps.addAll(wlApps);
2015        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2016                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2017        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2018        enableApps.removeAll(blApps);
2019        Log.i(TAG, "Applications installed for system user: " + enableApps);
2020        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2021                UserHandle.SYSTEM);
2022        final int allAppsSize = allAps.size();
2023        synchronized (mPackages) {
2024            for (int i = 0; i < allAppsSize; i++) {
2025                String pName = allAps.get(i);
2026                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2027                // Should not happen, but we shouldn't be failing if it does
2028                if (pkgSetting == null) {
2029                    continue;
2030                }
2031                boolean install = enableApps.contains(pName);
2032                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2033                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2034                            + " for system user");
2035                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2036                }
2037            }
2038        }
2039    }
2040
2041    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2042        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2043                Context.DISPLAY_SERVICE);
2044        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2045    }
2046
2047    /**
2048     * Requests that files preopted on a secondary system partition be copied to the data partition
2049     * if possible.  Note that the actual copying of the files is accomplished by init for security
2050     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2051     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2052     */
2053    private static void requestCopyPreoptedFiles() {
2054        final int WAIT_TIME_MS = 100;
2055        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2056        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2057            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2058            // We will wait for up to 100 seconds.
2059            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2060            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2061                try {
2062                    Thread.sleep(WAIT_TIME_MS);
2063                } catch (InterruptedException e) {
2064                    // Do nothing
2065                }
2066                if (SystemClock.uptimeMillis() > timeEnd) {
2067                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2068                    Slog.wtf(TAG, "cppreopt did not finish!");
2069                    break;
2070                }
2071            }
2072        }
2073    }
2074
2075    public PackageManagerService(Context context, Installer installer,
2076            boolean factoryTest, boolean onlyCore) {
2077        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2078        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2079                SystemClock.uptimeMillis());
2080
2081        if (mSdkVersion <= 0) {
2082            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2083        }
2084
2085        mContext = context;
2086
2087        mPermissionReviewRequired = context.getResources().getBoolean(
2088                R.bool.config_permissionReviewRequired);
2089
2090        mFactoryTest = factoryTest;
2091        mOnlyCore = onlyCore;
2092        mMetrics = new DisplayMetrics();
2093        mSettings = new Settings(mPackages);
2094        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2095                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2096        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2097                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2098        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2099                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2100        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2101                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2102        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2103                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2104        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2105                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2106
2107        String separateProcesses = SystemProperties.get("debug.separate_processes");
2108        if (separateProcesses != null && separateProcesses.length() > 0) {
2109            if ("*".equals(separateProcesses)) {
2110                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2111                mSeparateProcesses = null;
2112                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2113            } else {
2114                mDefParseFlags = 0;
2115                mSeparateProcesses = separateProcesses.split(",");
2116                Slog.w(TAG, "Running with debug.separate_processes: "
2117                        + separateProcesses);
2118            }
2119        } else {
2120            mDefParseFlags = 0;
2121            mSeparateProcesses = null;
2122        }
2123
2124        mInstaller = installer;
2125        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2126                "*dexopt*");
2127        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2128
2129        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2130                FgThread.get().getLooper());
2131
2132        getDefaultDisplayMetrics(context, mMetrics);
2133
2134        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2135        SystemConfig systemConfig = SystemConfig.getInstance();
2136        mGlobalGids = systemConfig.getGlobalGids();
2137        mSystemPermissions = systemConfig.getSystemPermissions();
2138        mAvailableFeatures = systemConfig.getAvailableFeatures();
2139        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2140
2141        mProtectedPackages = new ProtectedPackages(mContext);
2142
2143        synchronized (mInstallLock) {
2144        // writer
2145        synchronized (mPackages) {
2146            mHandlerThread = new ServiceThread(TAG,
2147                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2148            mHandlerThread.start();
2149            mHandler = new PackageHandler(mHandlerThread.getLooper());
2150            mProcessLoggingHandler = new ProcessLoggingHandler();
2151            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2152
2153            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2154
2155            File dataDir = Environment.getDataDirectory();
2156            mAppInstallDir = new File(dataDir, "app");
2157            mAppLib32InstallDir = new File(dataDir, "app-lib");
2158            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2159            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2160            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2161
2162            sUserManager = new UserManagerService(context, this, mPackages);
2163
2164            // Propagate permission configuration in to package manager.
2165            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2166                    = systemConfig.getPermissions();
2167            for (int i=0; i<permConfig.size(); i++) {
2168                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2169                BasePermission bp = mSettings.mPermissions.get(perm.name);
2170                if (bp == null) {
2171                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2172                    mSettings.mPermissions.put(perm.name, bp);
2173                }
2174                if (perm.gids != null) {
2175                    bp.setGids(perm.gids, perm.perUser);
2176                }
2177            }
2178
2179            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2180            for (int i=0; i<libConfig.size(); i++) {
2181                mSharedLibraries.put(libConfig.keyAt(i),
2182                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2183            }
2184
2185            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2186
2187            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2188            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2189            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2190
2191            if (mFirstBoot) {
2192                requestCopyPreoptedFiles();
2193            }
2194
2195            String customResolverActivity = Resources.getSystem().getString(
2196                    R.string.config_customResolverActivity);
2197            if (TextUtils.isEmpty(customResolverActivity)) {
2198                customResolverActivity = null;
2199            } else {
2200                mCustomResolverComponentName = ComponentName.unflattenFromString(
2201                        customResolverActivity);
2202            }
2203
2204            long startTime = SystemClock.uptimeMillis();
2205
2206            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2207                    startTime);
2208
2209            // Set flag to monitor and not change apk file paths when
2210            // scanning install directories.
2211            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2212
2213            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2214            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2215
2216            if (bootClassPath == null) {
2217                Slog.w(TAG, "No BOOTCLASSPATH found!");
2218            }
2219
2220            if (systemServerClassPath == null) {
2221                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2222            }
2223
2224            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2225            final String[] dexCodeInstructionSets =
2226                    getDexCodeInstructionSets(
2227                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2228
2229            /**
2230             * Ensure all external libraries have had dexopt run on them.
2231             */
2232            if (mSharedLibraries.size() > 0) {
2233                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2234                // NOTE: For now, we're compiling these system "shared libraries"
2235                // (and framework jars) into all available architectures. It's possible
2236                // to compile them only when we come across an app that uses them (there's
2237                // already logic for that in scanPackageLI) but that adds some complexity.
2238                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2239                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2240                        final String lib = libEntry.path;
2241                        if (lib == null) {
2242                            continue;
2243                        }
2244
2245                        try {
2246                            // Shared libraries do not have profiles so we perform a full
2247                            // AOT compilation (if needed).
2248                            int dexoptNeeded = DexFile.getDexOptNeeded(
2249                                    lib, dexCodeInstructionSet,
2250                                    getCompilerFilterForReason(REASON_SHARED_APK),
2251                                    false /* newProfile */);
2252                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2253                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2254                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2255                                        getCompilerFilterForReason(REASON_SHARED_APK),
2256                                        StorageManager.UUID_PRIVATE_INTERNAL,
2257                                        SKIP_SHARED_LIBRARY_CHECK);
2258                            }
2259                        } catch (FileNotFoundException e) {
2260                            Slog.w(TAG, "Library not found: " + lib);
2261                        } catch (IOException | InstallerException e) {
2262                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2263                                    + e.getMessage());
2264                        }
2265                    }
2266                }
2267                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2268            }
2269
2270            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2271
2272            final VersionInfo ver = mSettings.getInternalVersion();
2273            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2274
2275            // when upgrading from pre-M, promote system app permissions from install to runtime
2276            mPromoteSystemApps =
2277                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2278
2279            // When upgrading from pre-N, we need to handle package extraction like first boot,
2280            // as there is no profiling data available.
2281            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2282
2283            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2284
2285            // save off the names of pre-existing system packages prior to scanning; we don't
2286            // want to automatically grant runtime permissions for new system apps
2287            if (mPromoteSystemApps) {
2288                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2289                while (pkgSettingIter.hasNext()) {
2290                    PackageSetting ps = pkgSettingIter.next();
2291                    if (isSystemApp(ps)) {
2292                        mExistingSystemPackages.add(ps.name);
2293                    }
2294                }
2295            }
2296
2297            // Collect vendor overlay packages. (Do this before scanning any apps.)
2298            // For security and version matching reason, only consider
2299            // overlay packages if they reside in the right directory.
2300            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2301            if (overlayThemeDir.isEmpty()) {
2302                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2303            }
2304            if (!overlayThemeDir.isEmpty()) {
2305                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2306                        | PackageParser.PARSE_IS_SYSTEM
2307                        | PackageParser.PARSE_IS_SYSTEM_DIR
2308                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2309            }
2310            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2311                    | PackageParser.PARSE_IS_SYSTEM
2312                    | PackageParser.PARSE_IS_SYSTEM_DIR
2313                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2314
2315            // Find base frameworks (resource packages without code).
2316            scanDirTracedLI(frameworkDir, mDefParseFlags
2317                    | PackageParser.PARSE_IS_SYSTEM
2318                    | PackageParser.PARSE_IS_SYSTEM_DIR
2319                    | PackageParser.PARSE_IS_PRIVILEGED,
2320                    scanFlags | SCAN_NO_DEX, 0);
2321
2322            // Collected privileged system packages.
2323            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2324            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2325                    | PackageParser.PARSE_IS_SYSTEM
2326                    | PackageParser.PARSE_IS_SYSTEM_DIR
2327                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2328
2329            // Collect ordinary system packages.
2330            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2331            scanDirTracedLI(systemAppDir, mDefParseFlags
2332                    | PackageParser.PARSE_IS_SYSTEM
2333                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2334
2335            // Collect all vendor packages.
2336            File vendorAppDir = new File("/vendor/app");
2337            try {
2338                vendorAppDir = vendorAppDir.getCanonicalFile();
2339            } catch (IOException e) {
2340                // failed to look up canonical path, continue with original one
2341            }
2342            scanDirTracedLI(vendorAppDir, mDefParseFlags
2343                    | PackageParser.PARSE_IS_SYSTEM
2344                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2345
2346            // Collect all OEM packages.
2347            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2348            scanDirTracedLI(oemAppDir, mDefParseFlags
2349                    | PackageParser.PARSE_IS_SYSTEM
2350                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2351
2352            // Prune any system packages that no longer exist.
2353            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2354            if (!mOnlyCore) {
2355                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2356                while (psit.hasNext()) {
2357                    PackageSetting ps = psit.next();
2358
2359                    /*
2360                     * If this is not a system app, it can't be a
2361                     * disable system app.
2362                     */
2363                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2364                        continue;
2365                    }
2366
2367                    /*
2368                     * If the package is scanned, it's not erased.
2369                     */
2370                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2371                    if (scannedPkg != null) {
2372                        /*
2373                         * If the system app is both scanned and in the
2374                         * disabled packages list, then it must have been
2375                         * added via OTA. Remove it from the currently
2376                         * scanned package so the previously user-installed
2377                         * application can be scanned.
2378                         */
2379                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2380                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2381                                    + ps.name + "; removing system app.  Last known codePath="
2382                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2383                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2384                                    + scannedPkg.mVersionCode);
2385                            removePackageLI(scannedPkg, true);
2386                            mExpectingBetter.put(ps.name, ps.codePath);
2387                        }
2388
2389                        continue;
2390                    }
2391
2392                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2393                        psit.remove();
2394                        logCriticalInfo(Log.WARN, "System package " + ps.name
2395                                + " no longer exists; it's data will be wiped");
2396                        // Actual deletion of code and data will be handled by later
2397                        // reconciliation step
2398                    } else {
2399                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2400                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2401                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2402                        }
2403                    }
2404                }
2405            }
2406
2407            //look for any incomplete package installations
2408            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2409            for (int i = 0; i < deletePkgsList.size(); i++) {
2410                // Actual deletion of code and data will be handled by later
2411                // reconciliation step
2412                final String packageName = deletePkgsList.get(i).name;
2413                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2414                synchronized (mPackages) {
2415                    mSettings.removePackageLPw(packageName);
2416                }
2417            }
2418
2419            //delete tmp files
2420            deleteTempPackageFiles();
2421
2422            // Remove any shared userIDs that have no associated packages
2423            mSettings.pruneSharedUsersLPw();
2424
2425            if (!mOnlyCore) {
2426                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2427                        SystemClock.uptimeMillis());
2428                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2429
2430                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2431                        | PackageParser.PARSE_FORWARD_LOCK,
2432                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2433
2434                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2435                        | PackageParser.PARSE_IS_EPHEMERAL,
2436                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2437
2438                /**
2439                 * Remove disable package settings for any updated system
2440                 * apps that were removed via an OTA. If they're not a
2441                 * previously-updated app, remove them completely.
2442                 * Otherwise, just revoke their system-level permissions.
2443                 */
2444                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2445                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2446                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2447
2448                    String msg;
2449                    if (deletedPkg == null) {
2450                        msg = "Updated system package " + deletedAppName
2451                                + " no longer exists; it's data will be wiped";
2452                        // Actual deletion of code and data will be handled by later
2453                        // reconciliation step
2454                    } else {
2455                        msg = "Updated system app + " + deletedAppName
2456                                + " no longer present; removing system privileges for "
2457                                + deletedAppName;
2458
2459                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2460
2461                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2462                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2463                    }
2464                    logCriticalInfo(Log.WARN, msg);
2465                }
2466
2467                /**
2468                 * Make sure all system apps that we expected to appear on
2469                 * the userdata partition actually showed up. If they never
2470                 * appeared, crawl back and revive the system version.
2471                 */
2472                for (int i = 0; i < mExpectingBetter.size(); i++) {
2473                    final String packageName = mExpectingBetter.keyAt(i);
2474                    if (!mPackages.containsKey(packageName)) {
2475                        final File scanFile = mExpectingBetter.valueAt(i);
2476
2477                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2478                                + " but never showed up; reverting to system");
2479
2480                        int reparseFlags = mDefParseFlags;
2481                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2482                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2483                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2484                                    | PackageParser.PARSE_IS_PRIVILEGED;
2485                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2486                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2487                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2488                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2489                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2490                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2491                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2492                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2493                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2494                        } else {
2495                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2496                            continue;
2497                        }
2498
2499                        mSettings.enableSystemPackageLPw(packageName);
2500
2501                        try {
2502                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2503                        } catch (PackageManagerException e) {
2504                            Slog.e(TAG, "Failed to parse original system package: "
2505                                    + e.getMessage());
2506                        }
2507                    }
2508                }
2509            }
2510            mExpectingBetter.clear();
2511
2512            // Resolve the storage manager.
2513            mStorageManagerPackage = getStorageManagerPackageName();
2514
2515            // Resolve protected action filters. Only the setup wizard is allowed to
2516            // have a high priority filter for these actions.
2517            mSetupWizardPackage = getSetupWizardPackageName();
2518            if (mProtectedFilters.size() > 0) {
2519                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2520                    Slog.i(TAG, "No setup wizard;"
2521                        + " All protected intents capped to priority 0");
2522                }
2523                for (ActivityIntentInfo filter : mProtectedFilters) {
2524                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2525                        if (DEBUG_FILTERS) {
2526                            Slog.i(TAG, "Found setup wizard;"
2527                                + " allow priority " + filter.getPriority() + ";"
2528                                + " package: " + filter.activity.info.packageName
2529                                + " activity: " + filter.activity.className
2530                                + " priority: " + filter.getPriority());
2531                        }
2532                        // skip setup wizard; allow it to keep the high priority filter
2533                        continue;
2534                    }
2535                    Slog.w(TAG, "Protected action; cap priority to 0;"
2536                            + " package: " + filter.activity.info.packageName
2537                            + " activity: " + filter.activity.className
2538                            + " origPrio: " + filter.getPriority());
2539                    filter.setPriority(0);
2540                }
2541            }
2542            mDeferProtectedFilters = false;
2543            mProtectedFilters.clear();
2544
2545            // Now that we know all of the shared libraries, update all clients to have
2546            // the correct library paths.
2547            updateAllSharedLibrariesLPw();
2548
2549            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2550                // NOTE: We ignore potential failures here during a system scan (like
2551                // the rest of the commands above) because there's precious little we
2552                // can do about it. A settings error is reported, though.
2553                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2554            }
2555
2556            // Now that we know all the packages we are keeping,
2557            // read and update their last usage times.
2558            mPackageUsage.read(mPackages);
2559            mCompilerStats.read();
2560
2561            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2562                    SystemClock.uptimeMillis());
2563            Slog.i(TAG, "Time to scan packages: "
2564                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2565                    + " seconds");
2566
2567            // If the platform SDK has changed since the last time we booted,
2568            // we need to re-grant app permission to catch any new ones that
2569            // appear.  This is really a hack, and means that apps can in some
2570            // cases get permissions that the user didn't initially explicitly
2571            // allow...  it would be nice to have some better way to handle
2572            // this situation.
2573            int updateFlags = UPDATE_PERMISSIONS_ALL;
2574            if (ver.sdkVersion != mSdkVersion) {
2575                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2576                        + mSdkVersion + "; regranting permissions for internal storage");
2577                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2578            }
2579            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2580            ver.sdkVersion = mSdkVersion;
2581
2582            // If this is the first boot or an update from pre-M, and it is a normal
2583            // boot, then we need to initialize the default preferred apps across
2584            // all defined users.
2585            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2586                for (UserInfo user : sUserManager.getUsers(true)) {
2587                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2588                    applyFactoryDefaultBrowserLPw(user.id);
2589                    primeDomainVerificationsLPw(user.id);
2590                }
2591            }
2592
2593            // Prepare storage for system user really early during boot,
2594            // since core system apps like SettingsProvider and SystemUI
2595            // can't wait for user to start
2596            final int storageFlags;
2597            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2598                storageFlags = StorageManager.FLAG_STORAGE_DE;
2599            } else {
2600                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2601            }
2602            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2603                    storageFlags, true /* migrateAppData */);
2604
2605            // If this is first boot after an OTA, and a normal boot, then
2606            // we need to clear code cache directories.
2607            // Note that we do *not* clear the application profiles. These remain valid
2608            // across OTAs and are used to drive profile verification (post OTA) and
2609            // profile compilation (without waiting to collect a fresh set of profiles).
2610            if (mIsUpgrade && !onlyCore) {
2611                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2612                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2613                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2614                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2615                        // No apps are running this early, so no need to freeze
2616                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2617                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2618                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2619                    }
2620                }
2621                ver.fingerprint = Build.FINGERPRINT;
2622            }
2623
2624            checkDefaultBrowser();
2625
2626            // clear only after permissions and other defaults have been updated
2627            mExistingSystemPackages.clear();
2628            mPromoteSystemApps = false;
2629
2630            // All the changes are done during package scanning.
2631            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2632
2633            // can downgrade to reader
2634            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2635            mSettings.writeLPr();
2636            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2637
2638            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2639            // early on (before the package manager declares itself as early) because other
2640            // components in the system server might ask for package contexts for these apps.
2641            //
2642            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2643            // (i.e, that the data partition is unavailable).
2644            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2645                long start = System.nanoTime();
2646                List<PackageParser.Package> coreApps = new ArrayList<>();
2647                for (PackageParser.Package pkg : mPackages.values()) {
2648                    if (pkg.coreApp) {
2649                        coreApps.add(pkg);
2650                    }
2651                }
2652
2653                int[] stats = performDexOptUpgrade(coreApps, false,
2654                        getCompilerFilterForReason(REASON_CORE_APP));
2655
2656                final int elapsedTimeSeconds =
2657                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2658                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2659
2660                if (DEBUG_DEXOPT) {
2661                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2662                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2663                }
2664
2665
2666                // TODO: Should we log these stats to tron too ?
2667                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2668                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2669                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2670                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2671            }
2672
2673            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2674                    SystemClock.uptimeMillis());
2675
2676            if (!mOnlyCore) {
2677                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2678                mRequiredInstallerPackage = getRequiredInstallerLPr();
2679                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2680                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2681                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2682                        mIntentFilterVerifierComponent);
2683                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2684                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2685                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2686                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2687            } else {
2688                mRequiredVerifierPackage = null;
2689                mRequiredInstallerPackage = null;
2690                mRequiredUninstallerPackage = null;
2691                mIntentFilterVerifierComponent = null;
2692                mIntentFilterVerifier = null;
2693                mServicesSystemSharedLibraryPackageName = null;
2694                mSharedSystemSharedLibraryPackageName = null;
2695            }
2696
2697            mInstallerService = new PackageInstallerService(context, this);
2698
2699            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2700            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2701            // both the installer and resolver must be present to enable ephemeral
2702            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2703                if (DEBUG_EPHEMERAL) {
2704                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2705                            + " installer:" + ephemeralInstallerComponent);
2706                }
2707                mEphemeralResolverComponent = ephemeralResolverComponent;
2708                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2709                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2710                mEphemeralResolverConnection =
2711                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2712            } else {
2713                if (DEBUG_EPHEMERAL) {
2714                    final String missingComponent =
2715                            (ephemeralResolverComponent == null)
2716                            ? (ephemeralInstallerComponent == null)
2717                                    ? "resolver and installer"
2718                                    : "resolver"
2719                            : "installer";
2720                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2721                }
2722                mEphemeralResolverComponent = null;
2723                mEphemeralInstallerComponent = null;
2724                mEphemeralResolverConnection = null;
2725            }
2726
2727            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2728        } // synchronized (mPackages)
2729        } // synchronized (mInstallLock)
2730
2731        // Now after opening every single application zip, make sure they
2732        // are all flushed.  Not really needed, but keeps things nice and
2733        // tidy.
2734        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2735        Runtime.getRuntime().gc();
2736        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2737
2738        // The initial scanning above does many calls into installd while
2739        // holding the mPackages lock, but we're mostly interested in yelling
2740        // once we have a booted system.
2741        mInstaller.setWarnIfHeld(mPackages);
2742
2743        // Expose private service for system components to use.
2744        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2745        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2746    }
2747
2748    @Override
2749    public boolean isFirstBoot() {
2750        return mFirstBoot;
2751    }
2752
2753    @Override
2754    public boolean isOnlyCoreApps() {
2755        return mOnlyCore;
2756    }
2757
2758    @Override
2759    public boolean isUpgrade() {
2760        return mIsUpgrade;
2761    }
2762
2763    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2764        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2765
2766        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2767                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2768                UserHandle.USER_SYSTEM);
2769        if (matches.size() == 1) {
2770            return matches.get(0).getComponentInfo().packageName;
2771        } else if (matches.size() == 0) {
2772            Log.e(TAG, "There should probably be a verifier, but, none were found");
2773            return null;
2774        }
2775        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2776    }
2777
2778    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2779        synchronized (mPackages) {
2780            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2781            if (libraryEntry == null) {
2782                throw new IllegalStateException("Missing required shared library:" + libraryName);
2783            }
2784            return libraryEntry.apk;
2785        }
2786    }
2787
2788    private @NonNull String getRequiredInstallerLPr() {
2789        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2790        intent.addCategory(Intent.CATEGORY_DEFAULT);
2791        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2792
2793        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2794                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2795                UserHandle.USER_SYSTEM);
2796        if (matches.size() == 1) {
2797            ResolveInfo resolveInfo = matches.get(0);
2798            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2799                throw new RuntimeException("The installer must be a privileged app");
2800            }
2801            return matches.get(0).getComponentInfo().packageName;
2802        } else {
2803            throw new RuntimeException("There must be exactly one installer; found " + matches);
2804        }
2805    }
2806
2807    private @NonNull String getRequiredUninstallerLPr() {
2808        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2809        intent.addCategory(Intent.CATEGORY_DEFAULT);
2810        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2811
2812        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2813                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2814                UserHandle.USER_SYSTEM);
2815        if (resolveInfo == null ||
2816                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2817            throw new RuntimeException("There must be exactly one uninstaller; found "
2818                    + resolveInfo);
2819        }
2820        return resolveInfo.getComponentInfo().packageName;
2821    }
2822
2823    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2824        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2825
2826        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2827                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2828                UserHandle.USER_SYSTEM);
2829        ResolveInfo best = null;
2830        final int N = matches.size();
2831        for (int i = 0; i < N; i++) {
2832            final ResolveInfo cur = matches.get(i);
2833            final String packageName = cur.getComponentInfo().packageName;
2834            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2835                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2836                continue;
2837            }
2838
2839            if (best == null || cur.priority > best.priority) {
2840                best = cur;
2841            }
2842        }
2843
2844        if (best != null) {
2845            return best.getComponentInfo().getComponentName();
2846        } else {
2847            throw new RuntimeException("There must be at least one intent filter verifier");
2848        }
2849    }
2850
2851    private @Nullable ComponentName getEphemeralResolverLPr() {
2852        final String[] packageArray =
2853                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2854        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2855            if (DEBUG_EPHEMERAL) {
2856                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2857            }
2858            return null;
2859        }
2860
2861        final int resolveFlags =
2862                MATCH_DIRECT_BOOT_AWARE
2863                | MATCH_DIRECT_BOOT_UNAWARE
2864                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2865        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2866        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2867                resolveFlags, UserHandle.USER_SYSTEM);
2868
2869        final int N = resolvers.size();
2870        if (N == 0) {
2871            if (DEBUG_EPHEMERAL) {
2872                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2873            }
2874            return null;
2875        }
2876
2877        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2878        for (int i = 0; i < N; i++) {
2879            final ResolveInfo info = resolvers.get(i);
2880
2881            if (info.serviceInfo == null) {
2882                continue;
2883            }
2884
2885            final String packageName = info.serviceInfo.packageName;
2886            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2887                if (DEBUG_EPHEMERAL) {
2888                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2889                            + " pkg: " + packageName + ", info:" + info);
2890                }
2891                continue;
2892            }
2893
2894            if (DEBUG_EPHEMERAL) {
2895                Slog.v(TAG, "Ephemeral resolver found;"
2896                        + " pkg: " + packageName + ", info:" + info);
2897            }
2898            return new ComponentName(packageName, info.serviceInfo.name);
2899        }
2900        if (DEBUG_EPHEMERAL) {
2901            Slog.v(TAG, "Ephemeral resolver NOT found");
2902        }
2903        return null;
2904    }
2905
2906    private @Nullable ComponentName getEphemeralInstallerLPr() {
2907        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2908        intent.addCategory(Intent.CATEGORY_DEFAULT);
2909        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2910
2911        final int resolveFlags =
2912                MATCH_DIRECT_BOOT_AWARE
2913                | MATCH_DIRECT_BOOT_UNAWARE
2914                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2915        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2916                resolveFlags, UserHandle.USER_SYSTEM);
2917        if (matches.size() == 0) {
2918            return null;
2919        } else if (matches.size() == 1) {
2920            return matches.get(0).getComponentInfo().getComponentName();
2921        } else {
2922            throw new RuntimeException(
2923                    "There must be at most one ephemeral installer; found " + matches);
2924        }
2925    }
2926
2927    private void primeDomainVerificationsLPw(int userId) {
2928        if (DEBUG_DOMAIN_VERIFICATION) {
2929            Slog.d(TAG, "Priming domain verifications in user " + userId);
2930        }
2931
2932        SystemConfig systemConfig = SystemConfig.getInstance();
2933        ArraySet<String> packages = systemConfig.getLinkedApps();
2934
2935        for (String packageName : packages) {
2936            PackageParser.Package pkg = mPackages.get(packageName);
2937            if (pkg != null) {
2938                if (!pkg.isSystemApp()) {
2939                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2940                    continue;
2941                }
2942
2943                ArraySet<String> domains = null;
2944                for (PackageParser.Activity a : pkg.activities) {
2945                    for (ActivityIntentInfo filter : a.intents) {
2946                        if (hasValidDomains(filter)) {
2947                            if (domains == null) {
2948                                domains = new ArraySet<String>();
2949                            }
2950                            domains.addAll(filter.getHostsList());
2951                        }
2952                    }
2953                }
2954
2955                if (domains != null && domains.size() > 0) {
2956                    if (DEBUG_DOMAIN_VERIFICATION) {
2957                        Slog.v(TAG, "      + " + packageName);
2958                    }
2959                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2960                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2961                    // and then 'always' in the per-user state actually used for intent resolution.
2962                    final IntentFilterVerificationInfo ivi;
2963                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
2964                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2965                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2966                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2967                } else {
2968                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2969                            + "' does not handle web links");
2970                }
2971            } else {
2972                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2973            }
2974        }
2975
2976        scheduleWritePackageRestrictionsLocked(userId);
2977        scheduleWriteSettingsLocked();
2978    }
2979
2980    private void applyFactoryDefaultBrowserLPw(int userId) {
2981        // The default browser app's package name is stored in a string resource,
2982        // with a product-specific overlay used for vendor customization.
2983        String browserPkg = mContext.getResources().getString(
2984                com.android.internal.R.string.default_browser);
2985        if (!TextUtils.isEmpty(browserPkg)) {
2986            // non-empty string => required to be a known package
2987            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2988            if (ps == null) {
2989                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2990                browserPkg = null;
2991            } else {
2992                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2993            }
2994        }
2995
2996        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2997        // default.  If there's more than one, just leave everything alone.
2998        if (browserPkg == null) {
2999            calculateDefaultBrowserLPw(userId);
3000        }
3001    }
3002
3003    private void calculateDefaultBrowserLPw(int userId) {
3004        List<String> allBrowsers = resolveAllBrowserApps(userId);
3005        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3006        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3007    }
3008
3009    private List<String> resolveAllBrowserApps(int userId) {
3010        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3011        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3012                PackageManager.MATCH_ALL, userId);
3013
3014        final int count = list.size();
3015        List<String> result = new ArrayList<String>(count);
3016        for (int i=0; i<count; i++) {
3017            ResolveInfo info = list.get(i);
3018            if (info.activityInfo == null
3019                    || !info.handleAllWebDataURI
3020                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3021                    || result.contains(info.activityInfo.packageName)) {
3022                continue;
3023            }
3024            result.add(info.activityInfo.packageName);
3025        }
3026
3027        return result;
3028    }
3029
3030    private boolean packageIsBrowser(String packageName, int userId) {
3031        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3032                PackageManager.MATCH_ALL, userId);
3033        final int N = list.size();
3034        for (int i = 0; i < N; i++) {
3035            ResolveInfo info = list.get(i);
3036            if (packageName.equals(info.activityInfo.packageName)) {
3037                return true;
3038            }
3039        }
3040        return false;
3041    }
3042
3043    private void checkDefaultBrowser() {
3044        final int myUserId = UserHandle.myUserId();
3045        final String packageName = getDefaultBrowserPackageName(myUserId);
3046        if (packageName != null) {
3047            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3048            if (info == null) {
3049                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3050                synchronized (mPackages) {
3051                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3052                }
3053            }
3054        }
3055    }
3056
3057    @Override
3058    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3059            throws RemoteException {
3060        try {
3061            return super.onTransact(code, data, reply, flags);
3062        } catch (RuntimeException e) {
3063            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3064                Slog.wtf(TAG, "Package Manager Crash", e);
3065            }
3066            throw e;
3067        }
3068    }
3069
3070    static int[] appendInts(int[] cur, int[] add) {
3071        if (add == null) return cur;
3072        if (cur == null) return add;
3073        final int N = add.length;
3074        for (int i=0; i<N; i++) {
3075            cur = appendInt(cur, add[i]);
3076        }
3077        return cur;
3078    }
3079
3080    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3081        if (!sUserManager.exists(userId)) return null;
3082        if (ps == null) {
3083            return null;
3084        }
3085        final PackageParser.Package p = ps.pkg;
3086        if (p == null) {
3087            return null;
3088        }
3089
3090        final PermissionsState permissionsState = ps.getPermissionsState();
3091
3092        // Compute GIDs only if requested
3093        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3094                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3095        // Compute granted permissions only if package has requested permissions
3096        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3097                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3098        final PackageUserState state = ps.readUserState(userId);
3099
3100        return PackageParser.generatePackageInfo(p, gids, flags,
3101                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3102    }
3103
3104    @Override
3105    public void checkPackageStartable(String packageName, int userId) {
3106        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3107
3108        synchronized (mPackages) {
3109            final PackageSetting ps = mSettings.mPackages.get(packageName);
3110            if (ps == null) {
3111                throw new SecurityException("Package " + packageName + " was not found!");
3112            }
3113
3114            if (!ps.getInstalled(userId)) {
3115                throw new SecurityException(
3116                        "Package " + packageName + " was not installed for user " + userId + "!");
3117            }
3118
3119            if (mSafeMode && !ps.isSystem()) {
3120                throw new SecurityException("Package " + packageName + " not a system app!");
3121            }
3122
3123            if (mFrozenPackages.contains(packageName)) {
3124                throw new SecurityException("Package " + packageName + " is currently frozen!");
3125            }
3126
3127            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3128                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3129                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3130            }
3131        }
3132    }
3133
3134    @Override
3135    public boolean isPackageAvailable(String packageName, int userId) {
3136        if (!sUserManager.exists(userId)) return false;
3137        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3138                false /* requireFullPermission */, false /* checkShell */, "is package available");
3139        synchronized (mPackages) {
3140            PackageParser.Package p = mPackages.get(packageName);
3141            if (p != null) {
3142                final PackageSetting ps = (PackageSetting) p.mExtras;
3143                if (ps != null) {
3144                    final PackageUserState state = ps.readUserState(userId);
3145                    if (state != null) {
3146                        return PackageParser.isAvailable(state);
3147                    }
3148                }
3149            }
3150        }
3151        return false;
3152    }
3153
3154    @Override
3155    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3156        if (!sUserManager.exists(userId)) return null;
3157        flags = updateFlagsForPackage(flags, userId, packageName);
3158        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3159                false /* requireFullPermission */, false /* checkShell */, "get package info");
3160        // reader
3161        synchronized (mPackages) {
3162            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3163            PackageParser.Package p = null;
3164            if (matchFactoryOnly) {
3165                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3166                if (ps != null) {
3167                    return generatePackageInfo(ps, flags, userId);
3168                }
3169            }
3170            if (p == null) {
3171                p = mPackages.get(packageName);
3172                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3173                    return null;
3174                }
3175            }
3176            if (DEBUG_PACKAGE_INFO)
3177                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3178            if (p != null) {
3179                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3180            }
3181            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3182                final PackageSetting ps = mSettings.mPackages.get(packageName);
3183                return generatePackageInfo(ps, flags, userId);
3184            }
3185        }
3186        return null;
3187    }
3188
3189    @Override
3190    public String[] currentToCanonicalPackageNames(String[] names) {
3191        String[] out = new String[names.length];
3192        // reader
3193        synchronized (mPackages) {
3194            for (int i=names.length-1; i>=0; i--) {
3195                PackageSetting ps = mSettings.mPackages.get(names[i]);
3196                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3197            }
3198        }
3199        return out;
3200    }
3201
3202    @Override
3203    public String[] canonicalToCurrentPackageNames(String[] names) {
3204        String[] out = new String[names.length];
3205        // reader
3206        synchronized (mPackages) {
3207            for (int i=names.length-1; i>=0; i--) {
3208                String cur = mSettings.getRenamedPackageLPr(names[i]);
3209                out[i] = cur != null ? cur : names[i];
3210            }
3211        }
3212        return out;
3213    }
3214
3215    @Override
3216    public int getPackageUid(String packageName, int flags, int userId) {
3217        if (!sUserManager.exists(userId)) return -1;
3218        flags = updateFlagsForPackage(flags, userId, packageName);
3219        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3220                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3221
3222        // reader
3223        synchronized (mPackages) {
3224            final PackageParser.Package p = mPackages.get(packageName);
3225            if (p != null && p.isMatch(flags)) {
3226                return UserHandle.getUid(userId, p.applicationInfo.uid);
3227            }
3228            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3229                final PackageSetting ps = mSettings.mPackages.get(packageName);
3230                if (ps != null && ps.isMatch(flags)) {
3231                    return UserHandle.getUid(userId, ps.appId);
3232                }
3233            }
3234        }
3235
3236        return -1;
3237    }
3238
3239    @Override
3240    public int[] getPackageGids(String packageName, int flags, int userId) {
3241        if (!sUserManager.exists(userId)) return null;
3242        flags = updateFlagsForPackage(flags, userId, packageName);
3243        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3244                false /* requireFullPermission */, false /* checkShell */,
3245                "getPackageGids");
3246
3247        // reader
3248        synchronized (mPackages) {
3249            final PackageParser.Package p = mPackages.get(packageName);
3250            if (p != null && p.isMatch(flags)) {
3251                PackageSetting ps = (PackageSetting) p.mExtras;
3252                return ps.getPermissionsState().computeGids(userId);
3253            }
3254            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3255                final PackageSetting ps = mSettings.mPackages.get(packageName);
3256                if (ps != null && ps.isMatch(flags)) {
3257                    return ps.getPermissionsState().computeGids(userId);
3258                }
3259            }
3260        }
3261
3262        return null;
3263    }
3264
3265    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3266        if (bp.perm != null) {
3267            return PackageParser.generatePermissionInfo(bp.perm, flags);
3268        }
3269        PermissionInfo pi = new PermissionInfo();
3270        pi.name = bp.name;
3271        pi.packageName = bp.sourcePackage;
3272        pi.nonLocalizedLabel = bp.name;
3273        pi.protectionLevel = bp.protectionLevel;
3274        return pi;
3275    }
3276
3277    @Override
3278    public PermissionInfo getPermissionInfo(String name, int flags) {
3279        // reader
3280        synchronized (mPackages) {
3281            final BasePermission p = mSettings.mPermissions.get(name);
3282            if (p != null) {
3283                return generatePermissionInfo(p, flags);
3284            }
3285            return null;
3286        }
3287    }
3288
3289    @Override
3290    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3291            int flags) {
3292        // reader
3293        synchronized (mPackages) {
3294            if (group != null && !mPermissionGroups.containsKey(group)) {
3295                // This is thrown as NameNotFoundException
3296                return null;
3297            }
3298
3299            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3300            for (BasePermission p : mSettings.mPermissions.values()) {
3301                if (group == null) {
3302                    if (p.perm == null || p.perm.info.group == null) {
3303                        out.add(generatePermissionInfo(p, flags));
3304                    }
3305                } else {
3306                    if (p.perm != null && group.equals(p.perm.info.group)) {
3307                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3308                    }
3309                }
3310            }
3311            return new ParceledListSlice<>(out);
3312        }
3313    }
3314
3315    @Override
3316    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3317        // reader
3318        synchronized (mPackages) {
3319            return PackageParser.generatePermissionGroupInfo(
3320                    mPermissionGroups.get(name), flags);
3321        }
3322    }
3323
3324    @Override
3325    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3326        // reader
3327        synchronized (mPackages) {
3328            final int N = mPermissionGroups.size();
3329            ArrayList<PermissionGroupInfo> out
3330                    = new ArrayList<PermissionGroupInfo>(N);
3331            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3332                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3333            }
3334            return new ParceledListSlice<>(out);
3335        }
3336    }
3337
3338    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3339            int userId) {
3340        if (!sUserManager.exists(userId)) return null;
3341        PackageSetting ps = mSettings.mPackages.get(packageName);
3342        if (ps != null) {
3343            if (ps.pkg == null) {
3344                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3345                if (pInfo != null) {
3346                    return pInfo.applicationInfo;
3347                }
3348                return null;
3349            }
3350            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3351                    ps.readUserState(userId), userId);
3352        }
3353        return null;
3354    }
3355
3356    @Override
3357    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3358        if (!sUserManager.exists(userId)) return null;
3359        flags = updateFlagsForApplication(flags, userId, packageName);
3360        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3361                false /* requireFullPermission */, false /* checkShell */, "get application info");
3362        // writer
3363        synchronized (mPackages) {
3364            PackageParser.Package p = mPackages.get(packageName);
3365            if (DEBUG_PACKAGE_INFO) Log.v(
3366                    TAG, "getApplicationInfo " + packageName
3367                    + ": " + p);
3368            if (p != null) {
3369                PackageSetting ps = mSettings.mPackages.get(packageName);
3370                if (ps == null) return null;
3371                // Note: isEnabledLP() does not apply here - always return info
3372                return PackageParser.generateApplicationInfo(
3373                        p, flags, ps.readUserState(userId), userId);
3374            }
3375            if ("android".equals(packageName)||"system".equals(packageName)) {
3376                return mAndroidApplication;
3377            }
3378            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3379                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3380            }
3381        }
3382        return null;
3383    }
3384
3385    @Override
3386    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3387            final IPackageDataObserver observer) {
3388        mContext.enforceCallingOrSelfPermission(
3389                android.Manifest.permission.CLEAR_APP_CACHE, null);
3390        // Queue up an async operation since clearing cache may take a little while.
3391        mHandler.post(new Runnable() {
3392            public void run() {
3393                mHandler.removeCallbacks(this);
3394                boolean success = true;
3395                synchronized (mInstallLock) {
3396                    try {
3397                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3398                    } catch (InstallerException e) {
3399                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3400                        success = false;
3401                    }
3402                }
3403                if (observer != null) {
3404                    try {
3405                        observer.onRemoveCompleted(null, success);
3406                    } catch (RemoteException e) {
3407                        Slog.w(TAG, "RemoveException when invoking call back");
3408                    }
3409                }
3410            }
3411        });
3412    }
3413
3414    @Override
3415    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3416            final IntentSender pi) {
3417        mContext.enforceCallingOrSelfPermission(
3418                android.Manifest.permission.CLEAR_APP_CACHE, null);
3419        // Queue up an async operation since clearing cache may take a little while.
3420        mHandler.post(new Runnable() {
3421            public void run() {
3422                mHandler.removeCallbacks(this);
3423                boolean success = true;
3424                synchronized (mInstallLock) {
3425                    try {
3426                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3427                    } catch (InstallerException e) {
3428                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3429                        success = false;
3430                    }
3431                }
3432                if(pi != null) {
3433                    try {
3434                        // Callback via pending intent
3435                        int code = success ? 1 : 0;
3436                        pi.sendIntent(null, code, null,
3437                                null, null);
3438                    } catch (SendIntentException e1) {
3439                        Slog.i(TAG, "Failed to send pending intent");
3440                    }
3441                }
3442            }
3443        });
3444    }
3445
3446    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3447        synchronized (mInstallLock) {
3448            try {
3449                mInstaller.freeCache(volumeUuid, freeStorageSize);
3450            } catch (InstallerException e) {
3451                throw new IOException("Failed to free enough space", e);
3452            }
3453        }
3454    }
3455
3456    /**
3457     * Update given flags based on encryption status of current user.
3458     */
3459    private int updateFlags(int flags, int userId) {
3460        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3461                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3462            // Caller expressed an explicit opinion about what encryption
3463            // aware/unaware components they want to see, so fall through and
3464            // give them what they want
3465        } else {
3466            // Caller expressed no opinion, so match based on user state
3467            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3468                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3469            } else {
3470                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3471            }
3472        }
3473        return flags;
3474    }
3475
3476    private UserManagerInternal getUserManagerInternal() {
3477        if (mUserManagerInternal == null) {
3478            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3479        }
3480        return mUserManagerInternal;
3481    }
3482
3483    /**
3484     * Update given flags when being used to request {@link PackageInfo}.
3485     */
3486    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3487        boolean triaged = true;
3488        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3489                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3490            // Caller is asking for component details, so they'd better be
3491            // asking for specific encryption matching behavior, or be triaged
3492            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3493                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3494                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3495                triaged = false;
3496            }
3497        }
3498        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3499                | PackageManager.MATCH_SYSTEM_ONLY
3500                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3501            triaged = false;
3502        }
3503        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3504            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3505                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3506        }
3507        return updateFlags(flags, userId);
3508    }
3509
3510    /**
3511     * Update given flags when being used to request {@link ApplicationInfo}.
3512     */
3513    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3514        return updateFlagsForPackage(flags, userId, cookie);
3515    }
3516
3517    /**
3518     * Update given flags when being used to request {@link ComponentInfo}.
3519     */
3520    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3521        if (cookie instanceof Intent) {
3522            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3523                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3524            }
3525        }
3526
3527        boolean triaged = true;
3528        // Caller is asking for component details, so they'd better be
3529        // asking for specific encryption matching behavior, or be triaged
3530        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3531                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3532                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3533            triaged = false;
3534        }
3535        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3536            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3537                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3538        }
3539
3540        return updateFlags(flags, userId);
3541    }
3542
3543    /**
3544     * Update given flags when being used to request {@link ResolveInfo}.
3545     */
3546    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3547        // Safe mode means we shouldn't match any third-party components
3548        if (mSafeMode) {
3549            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3550        }
3551
3552        return updateFlagsForComponent(flags, userId, cookie);
3553    }
3554
3555    @Override
3556    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3557        if (!sUserManager.exists(userId)) return null;
3558        flags = updateFlagsForComponent(flags, userId, component);
3559        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3560                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3561        synchronized (mPackages) {
3562            PackageParser.Activity a = mActivities.mActivities.get(component);
3563
3564            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3565            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3566                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3567                if (ps == null) return null;
3568                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3569                        userId);
3570            }
3571            if (mResolveComponentName.equals(component)) {
3572                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3573                        new PackageUserState(), userId);
3574            }
3575        }
3576        return null;
3577    }
3578
3579    @Override
3580    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3581            String resolvedType) {
3582        synchronized (mPackages) {
3583            if (component.equals(mResolveComponentName)) {
3584                // The resolver supports EVERYTHING!
3585                return true;
3586            }
3587            PackageParser.Activity a = mActivities.mActivities.get(component);
3588            if (a == null) {
3589                return false;
3590            }
3591            for (int i=0; i<a.intents.size(); i++) {
3592                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3593                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3594                    return true;
3595                }
3596            }
3597            return false;
3598        }
3599    }
3600
3601    @Override
3602    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3603        if (!sUserManager.exists(userId)) return null;
3604        flags = updateFlagsForComponent(flags, userId, component);
3605        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3606                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3607        synchronized (mPackages) {
3608            PackageParser.Activity a = mReceivers.mActivities.get(component);
3609            if (DEBUG_PACKAGE_INFO) Log.v(
3610                TAG, "getReceiverInfo " + component + ": " + a);
3611            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3612                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3613                if (ps == null) return null;
3614                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3615                        userId);
3616            }
3617        }
3618        return null;
3619    }
3620
3621    @Override
3622    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3623        if (!sUserManager.exists(userId)) return null;
3624        flags = updateFlagsForComponent(flags, userId, component);
3625        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3626                false /* requireFullPermission */, false /* checkShell */, "get service info");
3627        synchronized (mPackages) {
3628            PackageParser.Service s = mServices.mServices.get(component);
3629            if (DEBUG_PACKAGE_INFO) Log.v(
3630                TAG, "getServiceInfo " + component + ": " + s);
3631            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3632                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3633                if (ps == null) return null;
3634                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3635                        userId);
3636            }
3637        }
3638        return null;
3639    }
3640
3641    @Override
3642    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3643        if (!sUserManager.exists(userId)) return null;
3644        flags = updateFlagsForComponent(flags, userId, component);
3645        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3646                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3647        synchronized (mPackages) {
3648            PackageParser.Provider p = mProviders.mProviders.get(component);
3649            if (DEBUG_PACKAGE_INFO) Log.v(
3650                TAG, "getProviderInfo " + component + ": " + p);
3651            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3652                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3653                if (ps == null) return null;
3654                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3655                        userId);
3656            }
3657        }
3658        return null;
3659    }
3660
3661    @Override
3662    public String[] getSystemSharedLibraryNames() {
3663        Set<String> libSet;
3664        synchronized (mPackages) {
3665            libSet = mSharedLibraries.keySet();
3666            int size = libSet.size();
3667            if (size > 0) {
3668                String[] libs = new String[size];
3669                libSet.toArray(libs);
3670                return libs;
3671            }
3672        }
3673        return null;
3674    }
3675
3676    @Override
3677    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3678        synchronized (mPackages) {
3679            return mServicesSystemSharedLibraryPackageName;
3680        }
3681    }
3682
3683    @Override
3684    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3685        synchronized (mPackages) {
3686            return mSharedSystemSharedLibraryPackageName;
3687        }
3688    }
3689
3690    @Override
3691    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3692        synchronized (mPackages) {
3693            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3694
3695            final FeatureInfo fi = new FeatureInfo();
3696            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3697                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3698            res.add(fi);
3699
3700            return new ParceledListSlice<>(res);
3701        }
3702    }
3703
3704    @Override
3705    public boolean hasSystemFeature(String name, int version) {
3706        synchronized (mPackages) {
3707            final FeatureInfo feat = mAvailableFeatures.get(name);
3708            if (feat == null) {
3709                return false;
3710            } else {
3711                return feat.version >= version;
3712            }
3713        }
3714    }
3715
3716    @Override
3717    public int checkPermission(String permName, String pkgName, int userId) {
3718        if (!sUserManager.exists(userId)) {
3719            return PackageManager.PERMISSION_DENIED;
3720        }
3721
3722        synchronized (mPackages) {
3723            final PackageParser.Package p = mPackages.get(pkgName);
3724            if (p != null && p.mExtras != null) {
3725                final PackageSetting ps = (PackageSetting) p.mExtras;
3726                final PermissionsState permissionsState = ps.getPermissionsState();
3727                if (permissionsState.hasPermission(permName, userId)) {
3728                    return PackageManager.PERMISSION_GRANTED;
3729                }
3730                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3731                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3732                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3733                    return PackageManager.PERMISSION_GRANTED;
3734                }
3735            }
3736        }
3737
3738        return PackageManager.PERMISSION_DENIED;
3739    }
3740
3741    @Override
3742    public int checkUidPermission(String permName, int uid) {
3743        final int userId = UserHandle.getUserId(uid);
3744
3745        if (!sUserManager.exists(userId)) {
3746            return PackageManager.PERMISSION_DENIED;
3747        }
3748
3749        synchronized (mPackages) {
3750            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3751            if (obj != null) {
3752                final SettingBase ps = (SettingBase) obj;
3753                final PermissionsState permissionsState = ps.getPermissionsState();
3754                if (permissionsState.hasPermission(permName, userId)) {
3755                    return PackageManager.PERMISSION_GRANTED;
3756                }
3757                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3758                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3759                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3760                    return PackageManager.PERMISSION_GRANTED;
3761                }
3762            } else {
3763                ArraySet<String> perms = mSystemPermissions.get(uid);
3764                if (perms != null) {
3765                    if (perms.contains(permName)) {
3766                        return PackageManager.PERMISSION_GRANTED;
3767                    }
3768                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3769                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3770                        return PackageManager.PERMISSION_GRANTED;
3771                    }
3772                }
3773            }
3774        }
3775
3776        return PackageManager.PERMISSION_DENIED;
3777    }
3778
3779    @Override
3780    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3781        if (UserHandle.getCallingUserId() != userId) {
3782            mContext.enforceCallingPermission(
3783                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3784                    "isPermissionRevokedByPolicy for user " + userId);
3785        }
3786
3787        if (checkPermission(permission, packageName, userId)
3788                == PackageManager.PERMISSION_GRANTED) {
3789            return false;
3790        }
3791
3792        final long identity = Binder.clearCallingIdentity();
3793        try {
3794            final int flags = getPermissionFlags(permission, packageName, userId);
3795            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3796        } finally {
3797            Binder.restoreCallingIdentity(identity);
3798        }
3799    }
3800
3801    @Override
3802    public String getPermissionControllerPackageName() {
3803        synchronized (mPackages) {
3804            return mRequiredInstallerPackage;
3805        }
3806    }
3807
3808    /**
3809     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3810     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3811     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3812     * @param message the message to log on security exception
3813     */
3814    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3815            boolean checkShell, String message) {
3816        if (userId < 0) {
3817            throw new IllegalArgumentException("Invalid userId " + userId);
3818        }
3819        if (checkShell) {
3820            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3821        }
3822        if (userId == UserHandle.getUserId(callingUid)) return;
3823        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3824            if (requireFullPermission) {
3825                mContext.enforceCallingOrSelfPermission(
3826                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3827            } else {
3828                try {
3829                    mContext.enforceCallingOrSelfPermission(
3830                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3831                } catch (SecurityException se) {
3832                    mContext.enforceCallingOrSelfPermission(
3833                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3834                }
3835            }
3836        }
3837    }
3838
3839    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3840        if (callingUid == Process.SHELL_UID) {
3841            if (userHandle >= 0
3842                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3843                throw new SecurityException("Shell does not have permission to access user "
3844                        + userHandle);
3845            } else if (userHandle < 0) {
3846                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3847                        + Debug.getCallers(3));
3848            }
3849        }
3850    }
3851
3852    private BasePermission findPermissionTreeLP(String permName) {
3853        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3854            if (permName.startsWith(bp.name) &&
3855                    permName.length() > bp.name.length() &&
3856                    permName.charAt(bp.name.length()) == '.') {
3857                return bp;
3858            }
3859        }
3860        return null;
3861    }
3862
3863    private BasePermission checkPermissionTreeLP(String permName) {
3864        if (permName != null) {
3865            BasePermission bp = findPermissionTreeLP(permName);
3866            if (bp != null) {
3867                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3868                    return bp;
3869                }
3870                throw new SecurityException("Calling uid "
3871                        + Binder.getCallingUid()
3872                        + " is not allowed to add to permission tree "
3873                        + bp.name + " owned by uid " + bp.uid);
3874            }
3875        }
3876        throw new SecurityException("No permission tree found for " + permName);
3877    }
3878
3879    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3880        if (s1 == null) {
3881            return s2 == null;
3882        }
3883        if (s2 == null) {
3884            return false;
3885        }
3886        if (s1.getClass() != s2.getClass()) {
3887            return false;
3888        }
3889        return s1.equals(s2);
3890    }
3891
3892    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3893        if (pi1.icon != pi2.icon) return false;
3894        if (pi1.logo != pi2.logo) return false;
3895        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3896        if (!compareStrings(pi1.name, pi2.name)) return false;
3897        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3898        // We'll take care of setting this one.
3899        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3900        // These are not currently stored in settings.
3901        //if (!compareStrings(pi1.group, pi2.group)) return false;
3902        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3903        //if (pi1.labelRes != pi2.labelRes) return false;
3904        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3905        return true;
3906    }
3907
3908    int permissionInfoFootprint(PermissionInfo info) {
3909        int size = info.name.length();
3910        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3911        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3912        return size;
3913    }
3914
3915    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3916        int size = 0;
3917        for (BasePermission perm : mSettings.mPermissions.values()) {
3918            if (perm.uid == tree.uid) {
3919                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3920            }
3921        }
3922        return size;
3923    }
3924
3925    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3926        // We calculate the max size of permissions defined by this uid and throw
3927        // if that plus the size of 'info' would exceed our stated maximum.
3928        if (tree.uid != Process.SYSTEM_UID) {
3929            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3930            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3931                throw new SecurityException("Permission tree size cap exceeded");
3932            }
3933        }
3934    }
3935
3936    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3937        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3938            throw new SecurityException("Label must be specified in permission");
3939        }
3940        BasePermission tree = checkPermissionTreeLP(info.name);
3941        BasePermission bp = mSettings.mPermissions.get(info.name);
3942        boolean added = bp == null;
3943        boolean changed = true;
3944        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3945        if (added) {
3946            enforcePermissionCapLocked(info, tree);
3947            bp = new BasePermission(info.name, tree.sourcePackage,
3948                    BasePermission.TYPE_DYNAMIC);
3949        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3950            throw new SecurityException(
3951                    "Not allowed to modify non-dynamic permission "
3952                    + info.name);
3953        } else {
3954            if (bp.protectionLevel == fixedLevel
3955                    && bp.perm.owner.equals(tree.perm.owner)
3956                    && bp.uid == tree.uid
3957                    && comparePermissionInfos(bp.perm.info, info)) {
3958                changed = false;
3959            }
3960        }
3961        bp.protectionLevel = fixedLevel;
3962        info = new PermissionInfo(info);
3963        info.protectionLevel = fixedLevel;
3964        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3965        bp.perm.info.packageName = tree.perm.info.packageName;
3966        bp.uid = tree.uid;
3967        if (added) {
3968            mSettings.mPermissions.put(info.name, bp);
3969        }
3970        if (changed) {
3971            if (!async) {
3972                mSettings.writeLPr();
3973            } else {
3974                scheduleWriteSettingsLocked();
3975            }
3976        }
3977        return added;
3978    }
3979
3980    @Override
3981    public boolean addPermission(PermissionInfo info) {
3982        synchronized (mPackages) {
3983            return addPermissionLocked(info, false);
3984        }
3985    }
3986
3987    @Override
3988    public boolean addPermissionAsync(PermissionInfo info) {
3989        synchronized (mPackages) {
3990            return addPermissionLocked(info, true);
3991        }
3992    }
3993
3994    @Override
3995    public void removePermission(String name) {
3996        synchronized (mPackages) {
3997            checkPermissionTreeLP(name);
3998            BasePermission bp = mSettings.mPermissions.get(name);
3999            if (bp != null) {
4000                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4001                    throw new SecurityException(
4002                            "Not allowed to modify non-dynamic permission "
4003                            + name);
4004                }
4005                mSettings.mPermissions.remove(name);
4006                mSettings.writeLPr();
4007            }
4008        }
4009    }
4010
4011    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4012            BasePermission bp) {
4013        int index = pkg.requestedPermissions.indexOf(bp.name);
4014        if (index == -1) {
4015            throw new SecurityException("Package " + pkg.packageName
4016                    + " has not requested permission " + bp.name);
4017        }
4018        if (!bp.isRuntime() && !bp.isDevelopment()) {
4019            throw new SecurityException("Permission " + bp.name
4020                    + " is not a changeable permission type");
4021        }
4022    }
4023
4024    @Override
4025    public void grantRuntimePermission(String packageName, String name, final int userId) {
4026        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4027    }
4028
4029    private void grantRuntimePermission(String packageName, String name, final int userId,
4030            boolean overridePolicy) {
4031        if (!sUserManager.exists(userId)) {
4032            Log.e(TAG, "No such user:" + userId);
4033            return;
4034        }
4035
4036        mContext.enforceCallingOrSelfPermission(
4037                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4038                "grantRuntimePermission");
4039
4040        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4041                true /* requireFullPermission */, true /* checkShell */,
4042                "grantRuntimePermission");
4043
4044        final int uid;
4045        final SettingBase sb;
4046
4047        synchronized (mPackages) {
4048            final PackageParser.Package pkg = mPackages.get(packageName);
4049            if (pkg == null) {
4050                throw new IllegalArgumentException("Unknown package: " + packageName);
4051            }
4052
4053            final BasePermission bp = mSettings.mPermissions.get(name);
4054            if (bp == null) {
4055                throw new IllegalArgumentException("Unknown permission: " + name);
4056            }
4057
4058            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4059
4060            // If a permission review is required for legacy apps we represent
4061            // their permissions as always granted runtime ones since we need
4062            // to keep the review required permission flag per user while an
4063            // install permission's state is shared across all users.
4064            if (mPermissionReviewRequired
4065                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4066                    && bp.isRuntime()) {
4067                return;
4068            }
4069
4070            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4071            sb = (SettingBase) pkg.mExtras;
4072            if (sb == null) {
4073                throw new IllegalArgumentException("Unknown package: " + packageName);
4074            }
4075
4076            final PermissionsState permissionsState = sb.getPermissionsState();
4077
4078            final int flags = permissionsState.getPermissionFlags(name, userId);
4079            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4080                throw new SecurityException("Cannot grant system fixed permission "
4081                        + name + " for package " + packageName);
4082            }
4083            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4084                throw new SecurityException("Cannot grant policy fixed permission "
4085                        + name + " for package " + packageName);
4086            }
4087
4088            if (bp.isDevelopment()) {
4089                // Development permissions must be handled specially, since they are not
4090                // normal runtime permissions.  For now they apply to all users.
4091                if (permissionsState.grantInstallPermission(bp) !=
4092                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4093                    scheduleWriteSettingsLocked();
4094                }
4095                return;
4096            }
4097
4098            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
4099                throw new SecurityException("Cannot grant non-ephemeral permission"
4100                        + name + " for package " + packageName);
4101            }
4102
4103            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4104                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4105                return;
4106            }
4107
4108            final int result = permissionsState.grantRuntimePermission(bp, userId);
4109            switch (result) {
4110                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4111                    return;
4112                }
4113
4114                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4115                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4116                    mHandler.post(new Runnable() {
4117                        @Override
4118                        public void run() {
4119                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4120                        }
4121                    });
4122                }
4123                break;
4124            }
4125
4126            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4127
4128            // Not critical if that is lost - app has to request again.
4129            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4130        }
4131
4132        // Only need to do this if user is initialized. Otherwise it's a new user
4133        // and there are no processes running as the user yet and there's no need
4134        // to make an expensive call to remount processes for the changed permissions.
4135        if (READ_EXTERNAL_STORAGE.equals(name)
4136                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4137            final long token = Binder.clearCallingIdentity();
4138            try {
4139                if (sUserManager.isInitialized(userId)) {
4140                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4141                            MountServiceInternal.class);
4142                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4143                }
4144            } finally {
4145                Binder.restoreCallingIdentity(token);
4146            }
4147        }
4148    }
4149
4150    @Override
4151    public void revokeRuntimePermission(String packageName, String name, int userId) {
4152        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4153    }
4154
4155    private void revokeRuntimePermission(String packageName, String name, int userId,
4156            boolean overridePolicy) {
4157        if (!sUserManager.exists(userId)) {
4158            Log.e(TAG, "No such user:" + userId);
4159            return;
4160        }
4161
4162        mContext.enforceCallingOrSelfPermission(
4163                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4164                "revokeRuntimePermission");
4165
4166        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4167                true /* requireFullPermission */, true /* checkShell */,
4168                "revokeRuntimePermission");
4169
4170        final int appId;
4171
4172        synchronized (mPackages) {
4173            final PackageParser.Package pkg = mPackages.get(packageName);
4174            if (pkg == null) {
4175                throw new IllegalArgumentException("Unknown package: " + packageName);
4176            }
4177
4178            final BasePermission bp = mSettings.mPermissions.get(name);
4179            if (bp == null) {
4180                throw new IllegalArgumentException("Unknown permission: " + name);
4181            }
4182
4183            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4184
4185            // If a permission review is required for legacy apps we represent
4186            // their permissions as always granted runtime ones since we need
4187            // to keep the review required permission flag per user while an
4188            // install permission's state is shared across all users.
4189            if (mPermissionReviewRequired
4190                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4191                    && bp.isRuntime()) {
4192                return;
4193            }
4194
4195            SettingBase sb = (SettingBase) pkg.mExtras;
4196            if (sb == null) {
4197                throw new IllegalArgumentException("Unknown package: " + packageName);
4198            }
4199
4200            final PermissionsState permissionsState = sb.getPermissionsState();
4201
4202            final int flags = permissionsState.getPermissionFlags(name, userId);
4203            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4204                throw new SecurityException("Cannot revoke system fixed permission "
4205                        + name + " for package " + packageName);
4206            }
4207            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4208                throw new SecurityException("Cannot revoke policy fixed permission "
4209                        + name + " for package " + packageName);
4210            }
4211
4212            if (bp.isDevelopment()) {
4213                // Development permissions must be handled specially, since they are not
4214                // normal runtime permissions.  For now they apply to all users.
4215                if (permissionsState.revokeInstallPermission(bp) !=
4216                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4217                    scheduleWriteSettingsLocked();
4218                }
4219                return;
4220            }
4221
4222            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4223                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4224                return;
4225            }
4226
4227            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4228
4229            // Critical, after this call app should never have the permission.
4230            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4231
4232            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4233        }
4234
4235        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4236    }
4237
4238    @Override
4239    public void resetRuntimePermissions() {
4240        mContext.enforceCallingOrSelfPermission(
4241                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4242                "revokeRuntimePermission");
4243
4244        int callingUid = Binder.getCallingUid();
4245        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4246            mContext.enforceCallingOrSelfPermission(
4247                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4248                    "resetRuntimePermissions");
4249        }
4250
4251        synchronized (mPackages) {
4252            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4253            for (int userId : UserManagerService.getInstance().getUserIds()) {
4254                final int packageCount = mPackages.size();
4255                for (int i = 0; i < packageCount; i++) {
4256                    PackageParser.Package pkg = mPackages.valueAt(i);
4257                    if (!(pkg.mExtras instanceof PackageSetting)) {
4258                        continue;
4259                    }
4260                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4261                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4262                }
4263            }
4264        }
4265    }
4266
4267    @Override
4268    public int getPermissionFlags(String name, String packageName, int userId) {
4269        if (!sUserManager.exists(userId)) {
4270            return 0;
4271        }
4272
4273        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4274
4275        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4276                true /* requireFullPermission */, false /* checkShell */,
4277                "getPermissionFlags");
4278
4279        synchronized (mPackages) {
4280            final PackageParser.Package pkg = mPackages.get(packageName);
4281            if (pkg == null) {
4282                return 0;
4283            }
4284
4285            final BasePermission bp = mSettings.mPermissions.get(name);
4286            if (bp == null) {
4287                return 0;
4288            }
4289
4290            SettingBase sb = (SettingBase) pkg.mExtras;
4291            if (sb == null) {
4292                return 0;
4293            }
4294
4295            PermissionsState permissionsState = sb.getPermissionsState();
4296            return permissionsState.getPermissionFlags(name, userId);
4297        }
4298    }
4299
4300    @Override
4301    public void updatePermissionFlags(String name, String packageName, int flagMask,
4302            int flagValues, int userId) {
4303        if (!sUserManager.exists(userId)) {
4304            return;
4305        }
4306
4307        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4308
4309        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4310                true /* requireFullPermission */, true /* checkShell */,
4311                "updatePermissionFlags");
4312
4313        // Only the system can change these flags and nothing else.
4314        if (getCallingUid() != Process.SYSTEM_UID) {
4315            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4316            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4317            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4318            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4319            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4320        }
4321
4322        synchronized (mPackages) {
4323            final PackageParser.Package pkg = mPackages.get(packageName);
4324            if (pkg == null) {
4325                throw new IllegalArgumentException("Unknown package: " + packageName);
4326            }
4327
4328            final BasePermission bp = mSettings.mPermissions.get(name);
4329            if (bp == null) {
4330                throw new IllegalArgumentException("Unknown permission: " + name);
4331            }
4332
4333            SettingBase sb = (SettingBase) pkg.mExtras;
4334            if (sb == null) {
4335                throw new IllegalArgumentException("Unknown package: " + packageName);
4336            }
4337
4338            PermissionsState permissionsState = sb.getPermissionsState();
4339
4340            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4341
4342            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4343                // Install and runtime permissions are stored in different places,
4344                // so figure out what permission changed and persist the change.
4345                if (permissionsState.getInstallPermissionState(name) != null) {
4346                    scheduleWriteSettingsLocked();
4347                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4348                        || hadState) {
4349                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4350                }
4351            }
4352        }
4353    }
4354
4355    /**
4356     * Update the permission flags for all packages and runtime permissions of a user in order
4357     * to allow device or profile owner to remove POLICY_FIXED.
4358     */
4359    @Override
4360    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4361        if (!sUserManager.exists(userId)) {
4362            return;
4363        }
4364
4365        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4366
4367        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4368                true /* requireFullPermission */, true /* checkShell */,
4369                "updatePermissionFlagsForAllApps");
4370
4371        // Only the system can change system fixed flags.
4372        if (getCallingUid() != Process.SYSTEM_UID) {
4373            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4374            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4375        }
4376
4377        synchronized (mPackages) {
4378            boolean changed = false;
4379            final int packageCount = mPackages.size();
4380            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4381                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4382                SettingBase sb = (SettingBase) pkg.mExtras;
4383                if (sb == null) {
4384                    continue;
4385                }
4386                PermissionsState permissionsState = sb.getPermissionsState();
4387                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4388                        userId, flagMask, flagValues);
4389            }
4390            if (changed) {
4391                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4392            }
4393        }
4394    }
4395
4396    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4397        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4398                != PackageManager.PERMISSION_GRANTED
4399            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4400                != PackageManager.PERMISSION_GRANTED) {
4401            throw new SecurityException(message + " requires "
4402                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4403                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4404        }
4405    }
4406
4407    @Override
4408    public boolean shouldShowRequestPermissionRationale(String permissionName,
4409            String packageName, int userId) {
4410        if (UserHandle.getCallingUserId() != userId) {
4411            mContext.enforceCallingPermission(
4412                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4413                    "canShowRequestPermissionRationale for user " + userId);
4414        }
4415
4416        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4417        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4418            return false;
4419        }
4420
4421        if (checkPermission(permissionName, packageName, userId)
4422                == PackageManager.PERMISSION_GRANTED) {
4423            return false;
4424        }
4425
4426        final int flags;
4427
4428        final long identity = Binder.clearCallingIdentity();
4429        try {
4430            flags = getPermissionFlags(permissionName,
4431                    packageName, userId);
4432        } finally {
4433            Binder.restoreCallingIdentity(identity);
4434        }
4435
4436        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4437                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4438                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4439
4440        if ((flags & fixedFlags) != 0) {
4441            return false;
4442        }
4443
4444        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4445    }
4446
4447    @Override
4448    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4449        mContext.enforceCallingOrSelfPermission(
4450                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4451                "addOnPermissionsChangeListener");
4452
4453        synchronized (mPackages) {
4454            mOnPermissionChangeListeners.addListenerLocked(listener);
4455        }
4456    }
4457
4458    @Override
4459    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4460        synchronized (mPackages) {
4461            mOnPermissionChangeListeners.removeListenerLocked(listener);
4462        }
4463    }
4464
4465    @Override
4466    public boolean isProtectedBroadcast(String actionName) {
4467        synchronized (mPackages) {
4468            if (mProtectedBroadcasts.contains(actionName)) {
4469                return true;
4470            } else if (actionName != null) {
4471                // TODO: remove these terrible hacks
4472                if (actionName.startsWith("android.net.netmon.lingerExpired")
4473                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4474                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4475                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4476                    return true;
4477                }
4478            }
4479        }
4480        return false;
4481    }
4482
4483    @Override
4484    public int checkSignatures(String pkg1, String pkg2) {
4485        synchronized (mPackages) {
4486            final PackageParser.Package p1 = mPackages.get(pkg1);
4487            final PackageParser.Package p2 = mPackages.get(pkg2);
4488            if (p1 == null || p1.mExtras == null
4489                    || p2 == null || p2.mExtras == null) {
4490                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4491            }
4492            return compareSignatures(p1.mSignatures, p2.mSignatures);
4493        }
4494    }
4495
4496    @Override
4497    public int checkUidSignatures(int uid1, int uid2) {
4498        // Map to base uids.
4499        uid1 = UserHandle.getAppId(uid1);
4500        uid2 = UserHandle.getAppId(uid2);
4501        // reader
4502        synchronized (mPackages) {
4503            Signature[] s1;
4504            Signature[] s2;
4505            Object obj = mSettings.getUserIdLPr(uid1);
4506            if (obj != null) {
4507                if (obj instanceof SharedUserSetting) {
4508                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4509                } else if (obj instanceof PackageSetting) {
4510                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4511                } else {
4512                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4513                }
4514            } else {
4515                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4516            }
4517            obj = mSettings.getUserIdLPr(uid2);
4518            if (obj != null) {
4519                if (obj instanceof SharedUserSetting) {
4520                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4521                } else if (obj instanceof PackageSetting) {
4522                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4523                } else {
4524                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4525                }
4526            } else {
4527                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4528            }
4529            return compareSignatures(s1, s2);
4530        }
4531    }
4532
4533    /**
4534     * This method should typically only be used when granting or revoking
4535     * permissions, since the app may immediately restart after this call.
4536     * <p>
4537     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4538     * guard your work against the app being relaunched.
4539     */
4540    private void killUid(int appId, int userId, String reason) {
4541        final long identity = Binder.clearCallingIdentity();
4542        try {
4543            IActivityManager am = ActivityManager.getService();
4544            if (am != null) {
4545                try {
4546                    am.killUid(appId, userId, reason);
4547                } catch (RemoteException e) {
4548                    /* ignore - same process */
4549                }
4550            }
4551        } finally {
4552            Binder.restoreCallingIdentity(identity);
4553        }
4554    }
4555
4556    /**
4557     * Compares two sets of signatures. Returns:
4558     * <br />
4559     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4560     * <br />
4561     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4562     * <br />
4563     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4564     * <br />
4565     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4566     * <br />
4567     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4568     */
4569    static int compareSignatures(Signature[] s1, Signature[] s2) {
4570        if (s1 == null) {
4571            return s2 == null
4572                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4573                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4574        }
4575
4576        if (s2 == null) {
4577            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4578        }
4579
4580        if (s1.length != s2.length) {
4581            return PackageManager.SIGNATURE_NO_MATCH;
4582        }
4583
4584        // Since both signature sets are of size 1, we can compare without HashSets.
4585        if (s1.length == 1) {
4586            return s1[0].equals(s2[0]) ?
4587                    PackageManager.SIGNATURE_MATCH :
4588                    PackageManager.SIGNATURE_NO_MATCH;
4589        }
4590
4591        ArraySet<Signature> set1 = new ArraySet<Signature>();
4592        for (Signature sig : s1) {
4593            set1.add(sig);
4594        }
4595        ArraySet<Signature> set2 = new ArraySet<Signature>();
4596        for (Signature sig : s2) {
4597            set2.add(sig);
4598        }
4599        // Make sure s2 contains all signatures in s1.
4600        if (set1.equals(set2)) {
4601            return PackageManager.SIGNATURE_MATCH;
4602        }
4603        return PackageManager.SIGNATURE_NO_MATCH;
4604    }
4605
4606    /**
4607     * If the database version for this type of package (internal storage or
4608     * external storage) is less than the version where package signatures
4609     * were updated, return true.
4610     */
4611    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4612        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4613        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4614    }
4615
4616    /**
4617     * Used for backward compatibility to make sure any packages with
4618     * certificate chains get upgraded to the new style. {@code existingSigs}
4619     * will be in the old format (since they were stored on disk from before the
4620     * system upgrade) and {@code scannedSigs} will be in the newer format.
4621     */
4622    private int compareSignaturesCompat(PackageSignatures existingSigs,
4623            PackageParser.Package scannedPkg) {
4624        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4625            return PackageManager.SIGNATURE_NO_MATCH;
4626        }
4627
4628        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4629        for (Signature sig : existingSigs.mSignatures) {
4630            existingSet.add(sig);
4631        }
4632        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4633        for (Signature sig : scannedPkg.mSignatures) {
4634            try {
4635                Signature[] chainSignatures = sig.getChainSignatures();
4636                for (Signature chainSig : chainSignatures) {
4637                    scannedCompatSet.add(chainSig);
4638                }
4639            } catch (CertificateEncodingException e) {
4640                scannedCompatSet.add(sig);
4641            }
4642        }
4643        /*
4644         * Make sure the expanded scanned set contains all signatures in the
4645         * existing one.
4646         */
4647        if (scannedCompatSet.equals(existingSet)) {
4648            // Migrate the old signatures to the new scheme.
4649            existingSigs.assignSignatures(scannedPkg.mSignatures);
4650            // The new KeySets will be re-added later in the scanning process.
4651            synchronized (mPackages) {
4652                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4653            }
4654            return PackageManager.SIGNATURE_MATCH;
4655        }
4656        return PackageManager.SIGNATURE_NO_MATCH;
4657    }
4658
4659    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4660        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4661        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4662    }
4663
4664    private int compareSignaturesRecover(PackageSignatures existingSigs,
4665            PackageParser.Package scannedPkg) {
4666        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4667            return PackageManager.SIGNATURE_NO_MATCH;
4668        }
4669
4670        String msg = null;
4671        try {
4672            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4673                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4674                        + scannedPkg.packageName);
4675                return PackageManager.SIGNATURE_MATCH;
4676            }
4677        } catch (CertificateException e) {
4678            msg = e.getMessage();
4679        }
4680
4681        logCriticalInfo(Log.INFO,
4682                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4683        return PackageManager.SIGNATURE_NO_MATCH;
4684    }
4685
4686    @Override
4687    public List<String> getAllPackages() {
4688        synchronized (mPackages) {
4689            return new ArrayList<String>(mPackages.keySet());
4690        }
4691    }
4692
4693    @Override
4694    public String[] getPackagesForUid(int uid) {
4695        final int userId = UserHandle.getUserId(uid);
4696        uid = UserHandle.getAppId(uid);
4697        // reader
4698        synchronized (mPackages) {
4699            Object obj = mSettings.getUserIdLPr(uid);
4700            if (obj instanceof SharedUserSetting) {
4701                final SharedUserSetting sus = (SharedUserSetting) obj;
4702                final int N = sus.packages.size();
4703                String[] res = new String[N];
4704                final Iterator<PackageSetting> it = sus.packages.iterator();
4705                int i = 0;
4706                while (it.hasNext()) {
4707                    PackageSetting ps = it.next();
4708                    if (ps.getInstalled(userId)) {
4709                        res[i++] = ps.name;
4710                    } else {
4711                        res = ArrayUtils.removeElement(String.class, res, res[i]);
4712                    }
4713                }
4714                return res;
4715            } else if (obj instanceof PackageSetting) {
4716                final PackageSetting ps = (PackageSetting) obj;
4717                return new String[] { ps.name };
4718            }
4719        }
4720        return null;
4721    }
4722
4723    @Override
4724    public String getNameForUid(int uid) {
4725        // reader
4726        synchronized (mPackages) {
4727            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4728            if (obj instanceof SharedUserSetting) {
4729                final SharedUserSetting sus = (SharedUserSetting) obj;
4730                return sus.name + ":" + sus.userId;
4731            } else if (obj instanceof PackageSetting) {
4732                final PackageSetting ps = (PackageSetting) obj;
4733                return ps.name;
4734            }
4735        }
4736        return null;
4737    }
4738
4739    @Override
4740    public int getUidForSharedUser(String sharedUserName) {
4741        if(sharedUserName == null) {
4742            return -1;
4743        }
4744        // reader
4745        synchronized (mPackages) {
4746            SharedUserSetting suid;
4747            try {
4748                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4749                if (suid != null) {
4750                    return suid.userId;
4751                }
4752            } catch (PackageManagerException ignore) {
4753                // can't happen, but, still need to catch it
4754            }
4755            return -1;
4756        }
4757    }
4758
4759    @Override
4760    public int getFlagsForUid(int uid) {
4761        synchronized (mPackages) {
4762            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4763            if (obj instanceof SharedUserSetting) {
4764                final SharedUserSetting sus = (SharedUserSetting) obj;
4765                return sus.pkgFlags;
4766            } else if (obj instanceof PackageSetting) {
4767                final PackageSetting ps = (PackageSetting) obj;
4768                return ps.pkgFlags;
4769            }
4770        }
4771        return 0;
4772    }
4773
4774    @Override
4775    public int getPrivateFlagsForUid(int uid) {
4776        synchronized (mPackages) {
4777            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4778            if (obj instanceof SharedUserSetting) {
4779                final SharedUserSetting sus = (SharedUserSetting) obj;
4780                return sus.pkgPrivateFlags;
4781            } else if (obj instanceof PackageSetting) {
4782                final PackageSetting ps = (PackageSetting) obj;
4783                return ps.pkgPrivateFlags;
4784            }
4785        }
4786        return 0;
4787    }
4788
4789    @Override
4790    public boolean isUidPrivileged(int uid) {
4791        uid = UserHandle.getAppId(uid);
4792        // reader
4793        synchronized (mPackages) {
4794            Object obj = mSettings.getUserIdLPr(uid);
4795            if (obj instanceof SharedUserSetting) {
4796                final SharedUserSetting sus = (SharedUserSetting) obj;
4797                final Iterator<PackageSetting> it = sus.packages.iterator();
4798                while (it.hasNext()) {
4799                    if (it.next().isPrivileged()) {
4800                        return true;
4801                    }
4802                }
4803            } else if (obj instanceof PackageSetting) {
4804                final PackageSetting ps = (PackageSetting) obj;
4805                return ps.isPrivileged();
4806            }
4807        }
4808        return false;
4809    }
4810
4811    @Override
4812    public String[] getAppOpPermissionPackages(String permissionName) {
4813        synchronized (mPackages) {
4814            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4815            if (pkgs == null) {
4816                return null;
4817            }
4818            return pkgs.toArray(new String[pkgs.size()]);
4819        }
4820    }
4821
4822    @Override
4823    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4824            int flags, int userId) {
4825        try {
4826            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4827
4828            if (!sUserManager.exists(userId)) return null;
4829            flags = updateFlagsForResolve(flags, userId, intent);
4830            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4831                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4832
4833            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4834            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4835                    flags, userId);
4836            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4837
4838            final ResolveInfo bestChoice =
4839                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4840            return bestChoice;
4841        } finally {
4842            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4843        }
4844    }
4845
4846    @Override
4847    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4848            IntentFilter filter, int match, ComponentName activity) {
4849        final int userId = UserHandle.getCallingUserId();
4850        if (DEBUG_PREFERRED) {
4851            Log.v(TAG, "setLastChosenActivity intent=" + intent
4852                + " resolvedType=" + resolvedType
4853                + " flags=" + flags
4854                + " filter=" + filter
4855                + " match=" + match
4856                + " activity=" + activity);
4857            filter.dump(new PrintStreamPrinter(System.out), "    ");
4858        }
4859        intent.setComponent(null);
4860        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4861                userId);
4862        // Find any earlier preferred or last chosen entries and nuke them
4863        findPreferredActivity(intent, resolvedType,
4864                flags, query, 0, false, true, false, userId);
4865        // Add the new activity as the last chosen for this filter
4866        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4867                "Setting last chosen");
4868    }
4869
4870    @Override
4871    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4872        final int userId = UserHandle.getCallingUserId();
4873        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4874        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4875                userId);
4876        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4877                false, false, false, userId);
4878    }
4879
4880    private boolean isEphemeralDisabled() {
4881        // ephemeral apps have been disabled across the board
4882        if (DISABLE_EPHEMERAL_APPS) {
4883            return true;
4884        }
4885        // system isn't up yet; can't read settings, so, assume no ephemeral apps
4886        if (!mSystemReady) {
4887            return true;
4888        }
4889        // we can't get a content resolver until the system is ready; these checks must happen last
4890        final ContentResolver resolver = mContext.getContentResolver();
4891        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
4892            return true;
4893        }
4894        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
4895    }
4896
4897    private boolean isEphemeralAllowed(
4898            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4899            boolean skipPackageCheck) {
4900        // Short circuit and return early if possible.
4901        if (isEphemeralDisabled()) {
4902            return false;
4903        }
4904        final int callingUser = UserHandle.getCallingUserId();
4905        if (callingUser != UserHandle.USER_SYSTEM) {
4906            return false;
4907        }
4908        if (mEphemeralResolverConnection == null) {
4909            return false;
4910        }
4911        if (intent.getComponent() != null) {
4912            return false;
4913        }
4914        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4915            return false;
4916        }
4917        if (!skipPackageCheck && intent.getPackage() != null) {
4918            return false;
4919        }
4920        final boolean isWebUri = hasWebURI(intent);
4921        if (!isWebUri || intent.getData().getHost() == null) {
4922            return false;
4923        }
4924        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4925        synchronized (mPackages) {
4926            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4927            for (int n = 0; n < count; n++) {
4928                ResolveInfo info = resolvedActivities.get(n);
4929                String packageName = info.activityInfo.packageName;
4930                PackageSetting ps = mSettings.mPackages.get(packageName);
4931                if (ps != null) {
4932                    // Try to get the status from User settings first
4933                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4934                    int status = (int) (packedStatus >> 32);
4935                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4936                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4937                        if (DEBUG_EPHEMERAL) {
4938                            Slog.v(TAG, "DENY ephemeral apps;"
4939                                + " pkg: " + packageName + ", status: " + status);
4940                        }
4941                        return false;
4942                    }
4943                }
4944            }
4945        }
4946        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4947        return true;
4948    }
4949
4950    private static EphemeralResolveIntentInfo getEphemeralIntentInfo(
4951            Context context, EphemeralResolverConnection resolverConnection, Intent intent,
4952            String resolvedType, int userId, String packageName) {
4953        final EphemeralDigest digest =
4954                new EphemeralDigest(intent.getData().getHost(), 5 /*maxDigests*/);
4955        final int[] shaPrefix = digest.getDigestPrefix();
4956        final byte[][] digestBytes = digest.getDigestBytes();
4957        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4958                resolverConnection.getEphemeralResolveInfoList(shaPrefix);
4959        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4960            // No hash prefix match; there are no ephemeral apps for this domain.
4961            return null;
4962        }
4963
4964        // Go in reverse order so we match the narrowest scope first.
4965        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4966            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4967                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4968                    continue;
4969                }
4970                final List<EphemeralIntentFilter> ephemeralFilters =
4971                        ephemeralApplication.getIntentFilters();
4972                // No filters; this should never happen.
4973                if (ephemeralFilters.isEmpty()) {
4974                    continue;
4975                }
4976                if (packageName != null
4977                        && !packageName.equals(ephemeralApplication.getPackageName())) {
4978                    continue;
4979                }
4980                // We have a domain match; resolve the filters to see if anything matches.
4981                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4982                for (int j = ephemeralFilters.size() - 1; j >= 0; --j) {
4983                    final EphemeralIntentFilter ephemeralFilter = ephemeralFilters.get(j);
4984                    final List<IntentFilter> splitFilters = ephemeralFilter.getFilters();
4985                    if (splitFilters == null || splitFilters.isEmpty()) {
4986                        continue;
4987                    }
4988                    for (int k = splitFilters.size() - 1; k >= 0; --k) {
4989                        final EphemeralResolveIntentInfo intentInfo =
4990                                new EphemeralResolveIntentInfo(splitFilters.get(k),
4991                                        ephemeralApplication, ephemeralFilter.getSplitName());
4992                        ephemeralResolver.addFilter(intentInfo);
4993                    }
4994                }
4995                List<EphemeralResolveIntentInfo> matchedResolveInfoList = ephemeralResolver
4996                        .queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
4997                if (!matchedResolveInfoList.isEmpty()) {
4998                    return matchedResolveInfoList.get(0);
4999                }
5000            }
5001        }
5002        // Hash or filter mis-match; no ephemeral apps for this domain.
5003        return null;
5004    }
5005
5006    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5007            int flags, List<ResolveInfo> query, int userId) {
5008        if (query != null) {
5009            final int N = query.size();
5010            if (N == 1) {
5011                return query.get(0);
5012            } else if (N > 1) {
5013                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5014                // If there is more than one activity with the same priority,
5015                // then let the user decide between them.
5016                ResolveInfo r0 = query.get(0);
5017                ResolveInfo r1 = query.get(1);
5018                if (DEBUG_INTENT_MATCHING || debug) {
5019                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5020                            + r1.activityInfo.name + "=" + r1.priority);
5021                }
5022                // If the first activity has a higher priority, or a different
5023                // default, then it is always desirable to pick it.
5024                if (r0.priority != r1.priority
5025                        || r0.preferredOrder != r1.preferredOrder
5026                        || r0.isDefault != r1.isDefault) {
5027                    return query.get(0);
5028                }
5029                // If we have saved a preference for a preferred activity for
5030                // this Intent, use that.
5031                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5032                        flags, query, r0.priority, true, false, debug, userId);
5033                if (ri != null) {
5034                    return ri;
5035                }
5036                ri = new ResolveInfo(mResolveInfo);
5037                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5038                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5039                // If all of the options come from the same package, show the application's
5040                // label and icon instead of the generic resolver's.
5041                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5042                // and then throw away the ResolveInfo itself, meaning that the caller loses
5043                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5044                // a fallback for this case; we only set the target package's resources on
5045                // the ResolveInfo, not the ActivityInfo.
5046                final String intentPackage = intent.getPackage();
5047                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5048                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5049                    ri.resolvePackageName = intentPackage;
5050                    if (userNeedsBadging(userId)) {
5051                        ri.noResourceId = true;
5052                    } else {
5053                        ri.icon = appi.icon;
5054                    }
5055                    ri.iconResourceId = appi.icon;
5056                    ri.labelRes = appi.labelRes;
5057                }
5058                ri.activityInfo.applicationInfo = new ApplicationInfo(
5059                        ri.activityInfo.applicationInfo);
5060                if (userId != 0) {
5061                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5062                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5063                }
5064                // Make sure that the resolver is displayable in car mode
5065                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5066                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5067                return ri;
5068            }
5069        }
5070        return null;
5071    }
5072
5073    /**
5074     * Return true if the given list is not empty and all of its contents have
5075     * an activityInfo with the given package name.
5076     */
5077    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5078        if (ArrayUtils.isEmpty(list)) {
5079            return false;
5080        }
5081        for (int i = 0, N = list.size(); i < N; i++) {
5082            final ResolveInfo ri = list.get(i);
5083            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5084            if (ai == null || !packageName.equals(ai.packageName)) {
5085                return false;
5086            }
5087        }
5088        return true;
5089    }
5090
5091    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5092            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5093        final int N = query.size();
5094        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5095                .get(userId);
5096        // Get the list of persistent preferred activities that handle the intent
5097        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5098        List<PersistentPreferredActivity> pprefs = ppir != null
5099                ? ppir.queryIntent(intent, resolvedType,
5100                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5101                : null;
5102        if (pprefs != null && pprefs.size() > 0) {
5103            final int M = pprefs.size();
5104            for (int i=0; i<M; i++) {
5105                final PersistentPreferredActivity ppa = pprefs.get(i);
5106                if (DEBUG_PREFERRED || debug) {
5107                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5108                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5109                            + "\n  component=" + ppa.mComponent);
5110                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5111                }
5112                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5113                        flags | MATCH_DISABLED_COMPONENTS, userId);
5114                if (DEBUG_PREFERRED || debug) {
5115                    Slog.v(TAG, "Found persistent preferred activity:");
5116                    if (ai != null) {
5117                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5118                    } else {
5119                        Slog.v(TAG, "  null");
5120                    }
5121                }
5122                if (ai == null) {
5123                    // This previously registered persistent preferred activity
5124                    // component is no longer known. Ignore it and do NOT remove it.
5125                    continue;
5126                }
5127                for (int j=0; j<N; j++) {
5128                    final ResolveInfo ri = query.get(j);
5129                    if (!ri.activityInfo.applicationInfo.packageName
5130                            .equals(ai.applicationInfo.packageName)) {
5131                        continue;
5132                    }
5133                    if (!ri.activityInfo.name.equals(ai.name)) {
5134                        continue;
5135                    }
5136                    //  Found a persistent preference that can handle the intent.
5137                    if (DEBUG_PREFERRED || debug) {
5138                        Slog.v(TAG, "Returning persistent preferred activity: " +
5139                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5140                    }
5141                    return ri;
5142                }
5143            }
5144        }
5145        return null;
5146    }
5147
5148    // TODO: handle preferred activities missing while user has amnesia
5149    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5150            List<ResolveInfo> query, int priority, boolean always,
5151            boolean removeMatches, boolean debug, int userId) {
5152        if (!sUserManager.exists(userId)) return null;
5153        flags = updateFlagsForResolve(flags, userId, intent);
5154        // writer
5155        synchronized (mPackages) {
5156            if (intent.getSelector() != null) {
5157                intent = intent.getSelector();
5158            }
5159            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5160
5161            // Try to find a matching persistent preferred activity.
5162            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5163                    debug, userId);
5164
5165            // If a persistent preferred activity matched, use it.
5166            if (pri != null) {
5167                return pri;
5168            }
5169
5170            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5171            // Get the list of preferred activities that handle the intent
5172            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5173            List<PreferredActivity> prefs = pir != null
5174                    ? pir.queryIntent(intent, resolvedType,
5175                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5176                    : null;
5177            if (prefs != null && prefs.size() > 0) {
5178                boolean changed = false;
5179                try {
5180                    // First figure out how good the original match set is.
5181                    // We will only allow preferred activities that came
5182                    // from the same match quality.
5183                    int match = 0;
5184
5185                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5186
5187                    final int N = query.size();
5188                    for (int j=0; j<N; j++) {
5189                        final ResolveInfo ri = query.get(j);
5190                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5191                                + ": 0x" + Integer.toHexString(match));
5192                        if (ri.match > match) {
5193                            match = ri.match;
5194                        }
5195                    }
5196
5197                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5198                            + Integer.toHexString(match));
5199
5200                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5201                    final int M = prefs.size();
5202                    for (int i=0; i<M; i++) {
5203                        final PreferredActivity pa = prefs.get(i);
5204                        if (DEBUG_PREFERRED || debug) {
5205                            Slog.v(TAG, "Checking PreferredActivity ds="
5206                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5207                                    + "\n  component=" + pa.mPref.mComponent);
5208                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5209                        }
5210                        if (pa.mPref.mMatch != match) {
5211                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5212                                    + Integer.toHexString(pa.mPref.mMatch));
5213                            continue;
5214                        }
5215                        // If it's not an "always" type preferred activity and that's what we're
5216                        // looking for, skip it.
5217                        if (always && !pa.mPref.mAlways) {
5218                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5219                            continue;
5220                        }
5221                        final ActivityInfo ai = getActivityInfo(
5222                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5223                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5224                                userId);
5225                        if (DEBUG_PREFERRED || debug) {
5226                            Slog.v(TAG, "Found preferred activity:");
5227                            if (ai != null) {
5228                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5229                            } else {
5230                                Slog.v(TAG, "  null");
5231                            }
5232                        }
5233                        if (ai == null) {
5234                            // This previously registered preferred activity
5235                            // component is no longer known.  Most likely an update
5236                            // to the app was installed and in the new version this
5237                            // component no longer exists.  Clean it up by removing
5238                            // it from the preferred activities list, and skip it.
5239                            Slog.w(TAG, "Removing dangling preferred activity: "
5240                                    + pa.mPref.mComponent);
5241                            pir.removeFilter(pa);
5242                            changed = true;
5243                            continue;
5244                        }
5245                        for (int j=0; j<N; j++) {
5246                            final ResolveInfo ri = query.get(j);
5247                            if (!ri.activityInfo.applicationInfo.packageName
5248                                    .equals(ai.applicationInfo.packageName)) {
5249                                continue;
5250                            }
5251                            if (!ri.activityInfo.name.equals(ai.name)) {
5252                                continue;
5253                            }
5254
5255                            if (removeMatches) {
5256                                pir.removeFilter(pa);
5257                                changed = true;
5258                                if (DEBUG_PREFERRED) {
5259                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5260                                }
5261                                break;
5262                            }
5263
5264                            // Okay we found a previously set preferred or last chosen app.
5265                            // If the result set is different from when this
5266                            // was created, we need to clear it and re-ask the
5267                            // user their preference, if we're looking for an "always" type entry.
5268                            if (always && !pa.mPref.sameSet(query)) {
5269                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5270                                        + intent + " type " + resolvedType);
5271                                if (DEBUG_PREFERRED) {
5272                                    Slog.v(TAG, "Removing preferred activity since set changed "
5273                                            + pa.mPref.mComponent);
5274                                }
5275                                pir.removeFilter(pa);
5276                                // Re-add the filter as a "last chosen" entry (!always)
5277                                PreferredActivity lastChosen = new PreferredActivity(
5278                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5279                                pir.addFilter(lastChosen);
5280                                changed = true;
5281                                return null;
5282                            }
5283
5284                            // Yay! Either the set matched or we're looking for the last chosen
5285                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5286                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5287                            return ri;
5288                        }
5289                    }
5290                } finally {
5291                    if (changed) {
5292                        if (DEBUG_PREFERRED) {
5293                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5294                        }
5295                        scheduleWritePackageRestrictionsLocked(userId);
5296                    }
5297                }
5298            }
5299        }
5300        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5301        return null;
5302    }
5303
5304    /*
5305     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5306     */
5307    @Override
5308    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5309            int targetUserId) {
5310        mContext.enforceCallingOrSelfPermission(
5311                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5312        List<CrossProfileIntentFilter> matches =
5313                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5314        if (matches != null) {
5315            int size = matches.size();
5316            for (int i = 0; i < size; i++) {
5317                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5318            }
5319        }
5320        if (hasWebURI(intent)) {
5321            // cross-profile app linking works only towards the parent.
5322            final UserInfo parent = getProfileParent(sourceUserId);
5323            synchronized(mPackages) {
5324                int flags = updateFlagsForResolve(0, parent.id, intent);
5325                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5326                        intent, resolvedType, flags, sourceUserId, parent.id);
5327                return xpDomainInfo != null;
5328            }
5329        }
5330        return false;
5331    }
5332
5333    private UserInfo getProfileParent(int userId) {
5334        final long identity = Binder.clearCallingIdentity();
5335        try {
5336            return sUserManager.getProfileParent(userId);
5337        } finally {
5338            Binder.restoreCallingIdentity(identity);
5339        }
5340    }
5341
5342    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5343            String resolvedType, int userId) {
5344        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5345        if (resolver != null) {
5346            return resolver.queryIntent(intent, resolvedType, false, userId);
5347        }
5348        return null;
5349    }
5350
5351    @Override
5352    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5353            String resolvedType, int flags, int userId) {
5354        try {
5355            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5356
5357            return new ParceledListSlice<>(
5358                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5359        } finally {
5360            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5361        }
5362    }
5363
5364    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5365            String resolvedType, int flags, int userId) {
5366        if (!sUserManager.exists(userId)) return Collections.emptyList();
5367        flags = updateFlagsForResolve(flags, userId, intent);
5368        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5369                false /* requireFullPermission */, false /* checkShell */,
5370                "query intent activities");
5371        ComponentName comp = intent.getComponent();
5372        if (comp == null) {
5373            if (intent.getSelector() != null) {
5374                intent = intent.getSelector();
5375                comp = intent.getComponent();
5376            }
5377        }
5378
5379        if (comp != null) {
5380            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5381            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5382            if (ai != null) {
5383                final ResolveInfo ri = new ResolveInfo();
5384                ri.activityInfo = ai;
5385                list.add(ri);
5386            }
5387            return list;
5388        }
5389
5390        // reader
5391        boolean sortResult = false;
5392        boolean addEphemeral = false;
5393        boolean matchEphemeralPackage = false;
5394        List<ResolveInfo> result;
5395        final String pkgName = intent.getPackage();
5396        synchronized (mPackages) {
5397            if (pkgName == null) {
5398                List<CrossProfileIntentFilter> matchingFilters =
5399                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5400                // Check for results that need to skip the current profile.
5401                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5402                        resolvedType, flags, userId);
5403                if (xpResolveInfo != null) {
5404                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5405                    xpResult.add(xpResolveInfo);
5406                    return filterIfNotSystemUser(xpResult, userId);
5407                }
5408
5409                // Check for results in the current profile.
5410                result = filterIfNotSystemUser(mActivities.queryIntent(
5411                        intent, resolvedType, flags, userId), userId);
5412                addEphemeral =
5413                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5414
5415                // Check for cross profile results.
5416                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5417                xpResolveInfo = queryCrossProfileIntents(
5418                        matchingFilters, intent, resolvedType, flags, userId,
5419                        hasNonNegativePriorityResult);
5420                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5421                    boolean isVisibleToUser = filterIfNotSystemUser(
5422                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5423                    if (isVisibleToUser) {
5424                        result.add(xpResolveInfo);
5425                        sortResult = true;
5426                    }
5427                }
5428                if (hasWebURI(intent)) {
5429                    CrossProfileDomainInfo xpDomainInfo = null;
5430                    final UserInfo parent = getProfileParent(userId);
5431                    if (parent != null) {
5432                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5433                                flags, userId, parent.id);
5434                    }
5435                    if (xpDomainInfo != null) {
5436                        if (xpResolveInfo != null) {
5437                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5438                            // in the result.
5439                            result.remove(xpResolveInfo);
5440                        }
5441                        if (result.size() == 0 && !addEphemeral) {
5442                            // No result in current profile, but found candidate in parent user.
5443                            // And we are not going to add emphemeral app, so we can return the
5444                            // result straight away.
5445                            result.add(xpDomainInfo.resolveInfo);
5446                            return result;
5447                        }
5448                    } else if (result.size() <= 1 && !addEphemeral) {
5449                        // No result in parent user and <= 1 result in current profile, and we
5450                        // are not going to add emphemeral app, so we can return the result without
5451                        // further processing.
5452                        return result;
5453                    }
5454                    // We have more than one candidate (combining results from current and parent
5455                    // profile), so we need filtering and sorting.
5456                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
5457                            intent, flags, result, xpDomainInfo, userId);
5458                    sortResult = true;
5459                }
5460            } else {
5461                final PackageParser.Package pkg = mPackages.get(pkgName);
5462                if (pkg != null) {
5463                    result = filterIfNotSystemUser(
5464                            mActivities.queryIntentForPackage(
5465                                    intent, resolvedType, flags, pkg.activities, userId),
5466                            userId);
5467                } else {
5468                    // the caller wants to resolve for a particular package; however, there
5469                    // were no installed results, so, try to find an ephemeral result
5470                    addEphemeral = isEphemeralAllowed(
5471                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5472                    matchEphemeralPackage = true;
5473                    result = new ArrayList<ResolveInfo>();
5474                }
5475            }
5476        }
5477        if (addEphemeral) {
5478            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5479            final EphemeralResolveIntentInfo intentInfo = getEphemeralIntentInfo(
5480                    mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5481                    matchEphemeralPackage ? pkgName : null);
5482            if (intentInfo != null) {
5483                if (DEBUG_EPHEMERAL) {
5484                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5485                }
5486                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5487                ephemeralInstaller.ephemeralIntentInfo = intentInfo;
5488                // make sure this resolver is the default
5489                ephemeralInstaller.isDefault = true;
5490                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5491                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5492                // add a non-generic filter
5493                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5494                ephemeralInstaller.filter.addDataPath(
5495                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5496                result.add(ephemeralInstaller);
5497            }
5498            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5499        }
5500        if (sortResult) {
5501            Collections.sort(result, mResolvePrioritySorter);
5502        }
5503        return result;
5504    }
5505
5506    private static class CrossProfileDomainInfo {
5507        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5508        ResolveInfo resolveInfo;
5509        /* Best domain verification status of the activities found in the other profile */
5510        int bestDomainVerificationStatus;
5511    }
5512
5513    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5514            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5515        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5516                sourceUserId)) {
5517            return null;
5518        }
5519        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5520                resolvedType, flags, parentUserId);
5521
5522        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5523            return null;
5524        }
5525        CrossProfileDomainInfo result = null;
5526        int size = resultTargetUser.size();
5527        for (int i = 0; i < size; i++) {
5528            ResolveInfo riTargetUser = resultTargetUser.get(i);
5529            // Intent filter verification is only for filters that specify a host. So don't return
5530            // those that handle all web uris.
5531            if (riTargetUser.handleAllWebDataURI) {
5532                continue;
5533            }
5534            String packageName = riTargetUser.activityInfo.packageName;
5535            PackageSetting ps = mSettings.mPackages.get(packageName);
5536            if (ps == null) {
5537                continue;
5538            }
5539            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5540            int status = (int)(verificationState >> 32);
5541            if (result == null) {
5542                result = new CrossProfileDomainInfo();
5543                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5544                        sourceUserId, parentUserId);
5545                result.bestDomainVerificationStatus = status;
5546            } else {
5547                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5548                        result.bestDomainVerificationStatus);
5549            }
5550        }
5551        // Don't consider matches with status NEVER across profiles.
5552        if (result != null && result.bestDomainVerificationStatus
5553                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5554            return null;
5555        }
5556        return result;
5557    }
5558
5559    /**
5560     * Verification statuses are ordered from the worse to the best, except for
5561     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5562     */
5563    private int bestDomainVerificationStatus(int status1, int status2) {
5564        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5565            return status2;
5566        }
5567        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5568            return status1;
5569        }
5570        return (int) MathUtils.max(status1, status2);
5571    }
5572
5573    private boolean isUserEnabled(int userId) {
5574        long callingId = Binder.clearCallingIdentity();
5575        try {
5576            UserInfo userInfo = sUserManager.getUserInfo(userId);
5577            return userInfo != null && userInfo.isEnabled();
5578        } finally {
5579            Binder.restoreCallingIdentity(callingId);
5580        }
5581    }
5582
5583    /**
5584     * Filter out activities with systemUserOnly flag set, when current user is not System.
5585     *
5586     * @return filtered list
5587     */
5588    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5589        if (userId == UserHandle.USER_SYSTEM) {
5590            return resolveInfos;
5591        }
5592        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5593            ResolveInfo info = resolveInfos.get(i);
5594            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5595                resolveInfos.remove(i);
5596            }
5597        }
5598        return resolveInfos;
5599    }
5600
5601    /**
5602     * @param resolveInfos list of resolve infos in descending priority order
5603     * @return if the list contains a resolve info with non-negative priority
5604     */
5605    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5606        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5607    }
5608
5609    private static boolean hasWebURI(Intent intent) {
5610        if (intent.getData() == null) {
5611            return false;
5612        }
5613        final String scheme = intent.getScheme();
5614        if (TextUtils.isEmpty(scheme)) {
5615            return false;
5616        }
5617        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5618    }
5619
5620    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5621            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5622            int userId) {
5623        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5624
5625        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5626            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5627                    candidates.size());
5628        }
5629
5630        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5631        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5632        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5633        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5634        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5635        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5636
5637        synchronized (mPackages) {
5638            final int count = candidates.size();
5639            // First, try to use linked apps. Partition the candidates into four lists:
5640            // one for the final results, one for the "do not use ever", one for "undefined status"
5641            // and finally one for "browser app type".
5642            for (int n=0; n<count; n++) {
5643                ResolveInfo info = candidates.get(n);
5644                String packageName = info.activityInfo.packageName;
5645                PackageSetting ps = mSettings.mPackages.get(packageName);
5646                if (ps != null) {
5647                    // Add to the special match all list (Browser use case)
5648                    if (info.handleAllWebDataURI) {
5649                        matchAllList.add(info);
5650                        continue;
5651                    }
5652                    // Try to get the status from User settings first
5653                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5654                    int status = (int)(packedStatus >> 32);
5655                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5656                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5657                        if (DEBUG_DOMAIN_VERIFICATION) {
5658                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5659                                    + " : linkgen=" + linkGeneration);
5660                        }
5661                        // Use link-enabled generation as preferredOrder, i.e.
5662                        // prefer newly-enabled over earlier-enabled.
5663                        info.preferredOrder = linkGeneration;
5664                        alwaysList.add(info);
5665                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5666                        if (DEBUG_DOMAIN_VERIFICATION) {
5667                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5668                        }
5669                        neverList.add(info);
5670                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5671                        if (DEBUG_DOMAIN_VERIFICATION) {
5672                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5673                        }
5674                        alwaysAskList.add(info);
5675                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5676                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5677                        if (DEBUG_DOMAIN_VERIFICATION) {
5678                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5679                        }
5680                        undefinedList.add(info);
5681                    }
5682                }
5683            }
5684
5685            // We'll want to include browser possibilities in a few cases
5686            boolean includeBrowser = false;
5687
5688            // First try to add the "always" resolution(s) for the current user, if any
5689            if (alwaysList.size() > 0) {
5690                result.addAll(alwaysList);
5691            } else {
5692                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5693                result.addAll(undefinedList);
5694                // Maybe add one for the other profile.
5695                if (xpDomainInfo != null && (
5696                        xpDomainInfo.bestDomainVerificationStatus
5697                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5698                    result.add(xpDomainInfo.resolveInfo);
5699                }
5700                includeBrowser = true;
5701            }
5702
5703            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5704            // If there were 'always' entries their preferred order has been set, so we also
5705            // back that off to make the alternatives equivalent
5706            if (alwaysAskList.size() > 0) {
5707                for (ResolveInfo i : result) {
5708                    i.preferredOrder = 0;
5709                }
5710                result.addAll(alwaysAskList);
5711                includeBrowser = true;
5712            }
5713
5714            if (includeBrowser) {
5715                // Also add browsers (all of them or only the default one)
5716                if (DEBUG_DOMAIN_VERIFICATION) {
5717                    Slog.v(TAG, "   ...including browsers in candidate set");
5718                }
5719                if ((matchFlags & MATCH_ALL) != 0) {
5720                    result.addAll(matchAllList);
5721                } else {
5722                    // Browser/generic handling case.  If there's a default browser, go straight
5723                    // to that (but only if there is no other higher-priority match).
5724                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5725                    int maxMatchPrio = 0;
5726                    ResolveInfo defaultBrowserMatch = null;
5727                    final int numCandidates = matchAllList.size();
5728                    for (int n = 0; n < numCandidates; n++) {
5729                        ResolveInfo info = matchAllList.get(n);
5730                        // track the highest overall match priority...
5731                        if (info.priority > maxMatchPrio) {
5732                            maxMatchPrio = info.priority;
5733                        }
5734                        // ...and the highest-priority default browser match
5735                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5736                            if (defaultBrowserMatch == null
5737                                    || (defaultBrowserMatch.priority < info.priority)) {
5738                                if (debug) {
5739                                    Slog.v(TAG, "Considering default browser match " + info);
5740                                }
5741                                defaultBrowserMatch = info;
5742                            }
5743                        }
5744                    }
5745                    if (defaultBrowserMatch != null
5746                            && defaultBrowserMatch.priority >= maxMatchPrio
5747                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5748                    {
5749                        if (debug) {
5750                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5751                        }
5752                        result.add(defaultBrowserMatch);
5753                    } else {
5754                        result.addAll(matchAllList);
5755                    }
5756                }
5757
5758                // If there is nothing selected, add all candidates and remove the ones that the user
5759                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5760                if (result.size() == 0) {
5761                    result.addAll(candidates);
5762                    result.removeAll(neverList);
5763                }
5764            }
5765        }
5766        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5767            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5768                    result.size());
5769            for (ResolveInfo info : result) {
5770                Slog.v(TAG, "  + " + info.activityInfo);
5771            }
5772        }
5773        return result;
5774    }
5775
5776    // Returns a packed value as a long:
5777    //
5778    // high 'int'-sized word: link status: undefined/ask/never/always.
5779    // low 'int'-sized word: relative priority among 'always' results.
5780    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5781        long result = ps.getDomainVerificationStatusForUser(userId);
5782        // if none available, get the master status
5783        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5784            if (ps.getIntentFilterVerificationInfo() != null) {
5785                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5786            }
5787        }
5788        return result;
5789    }
5790
5791    private ResolveInfo querySkipCurrentProfileIntents(
5792            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5793            int flags, int sourceUserId) {
5794        if (matchingFilters != null) {
5795            int size = matchingFilters.size();
5796            for (int i = 0; i < size; i ++) {
5797                CrossProfileIntentFilter filter = matchingFilters.get(i);
5798                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5799                    // Checking if there are activities in the target user that can handle the
5800                    // intent.
5801                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5802                            resolvedType, flags, sourceUserId);
5803                    if (resolveInfo != null) {
5804                        return resolveInfo;
5805                    }
5806                }
5807            }
5808        }
5809        return null;
5810    }
5811
5812    // Return matching ResolveInfo in target user if any.
5813    private ResolveInfo queryCrossProfileIntents(
5814            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5815            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5816        if (matchingFilters != null) {
5817            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5818            // match the same intent. For performance reasons, it is better not to
5819            // run queryIntent twice for the same userId
5820            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5821            int size = matchingFilters.size();
5822            for (int i = 0; i < size; i++) {
5823                CrossProfileIntentFilter filter = matchingFilters.get(i);
5824                int targetUserId = filter.getTargetUserId();
5825                boolean skipCurrentProfile =
5826                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5827                boolean skipCurrentProfileIfNoMatchFound =
5828                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5829                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5830                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5831                    // Checking if there are activities in the target user that can handle the
5832                    // intent.
5833                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5834                            resolvedType, flags, sourceUserId);
5835                    if (resolveInfo != null) return resolveInfo;
5836                    alreadyTriedUserIds.put(targetUserId, true);
5837                }
5838            }
5839        }
5840        return null;
5841    }
5842
5843    /**
5844     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5845     * will forward the intent to the filter's target user.
5846     * Otherwise, returns null.
5847     */
5848    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5849            String resolvedType, int flags, int sourceUserId) {
5850        int targetUserId = filter.getTargetUserId();
5851        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5852                resolvedType, flags, targetUserId);
5853        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5854            // If all the matches in the target profile are suspended, return null.
5855            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5856                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5857                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5858                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5859                            targetUserId);
5860                }
5861            }
5862        }
5863        return null;
5864    }
5865
5866    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5867            int sourceUserId, int targetUserId) {
5868        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5869        long ident = Binder.clearCallingIdentity();
5870        boolean targetIsProfile;
5871        try {
5872            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5873        } finally {
5874            Binder.restoreCallingIdentity(ident);
5875        }
5876        String className;
5877        if (targetIsProfile) {
5878            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5879        } else {
5880            className = FORWARD_INTENT_TO_PARENT;
5881        }
5882        ComponentName forwardingActivityComponentName = new ComponentName(
5883                mAndroidApplication.packageName, className);
5884        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5885                sourceUserId);
5886        if (!targetIsProfile) {
5887            forwardingActivityInfo.showUserIcon = targetUserId;
5888            forwardingResolveInfo.noResourceId = true;
5889        }
5890        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5891        forwardingResolveInfo.priority = 0;
5892        forwardingResolveInfo.preferredOrder = 0;
5893        forwardingResolveInfo.match = 0;
5894        forwardingResolveInfo.isDefault = true;
5895        forwardingResolveInfo.filter = filter;
5896        forwardingResolveInfo.targetUserId = targetUserId;
5897        return forwardingResolveInfo;
5898    }
5899
5900    @Override
5901    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5902            Intent[] specifics, String[] specificTypes, Intent intent,
5903            String resolvedType, int flags, int userId) {
5904        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5905                specificTypes, intent, resolvedType, flags, userId));
5906    }
5907
5908    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5909            Intent[] specifics, String[] specificTypes, Intent intent,
5910            String resolvedType, int flags, int userId) {
5911        if (!sUserManager.exists(userId)) return Collections.emptyList();
5912        flags = updateFlagsForResolve(flags, userId, intent);
5913        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5914                false /* requireFullPermission */, false /* checkShell */,
5915                "query intent activity options");
5916        final String resultsAction = intent.getAction();
5917
5918        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5919                | PackageManager.GET_RESOLVED_FILTER, userId);
5920
5921        if (DEBUG_INTENT_MATCHING) {
5922            Log.v(TAG, "Query " + intent + ": " + results);
5923        }
5924
5925        int specificsPos = 0;
5926        int N;
5927
5928        // todo: note that the algorithm used here is O(N^2).  This
5929        // isn't a problem in our current environment, but if we start running
5930        // into situations where we have more than 5 or 10 matches then this
5931        // should probably be changed to something smarter...
5932
5933        // First we go through and resolve each of the specific items
5934        // that were supplied, taking care of removing any corresponding
5935        // duplicate items in the generic resolve list.
5936        if (specifics != null) {
5937            for (int i=0; i<specifics.length; i++) {
5938                final Intent sintent = specifics[i];
5939                if (sintent == null) {
5940                    continue;
5941                }
5942
5943                if (DEBUG_INTENT_MATCHING) {
5944                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5945                }
5946
5947                String action = sintent.getAction();
5948                if (resultsAction != null && resultsAction.equals(action)) {
5949                    // If this action was explicitly requested, then don't
5950                    // remove things that have it.
5951                    action = null;
5952                }
5953
5954                ResolveInfo ri = null;
5955                ActivityInfo ai = null;
5956
5957                ComponentName comp = sintent.getComponent();
5958                if (comp == null) {
5959                    ri = resolveIntent(
5960                        sintent,
5961                        specificTypes != null ? specificTypes[i] : null,
5962                            flags, userId);
5963                    if (ri == null) {
5964                        continue;
5965                    }
5966                    if (ri == mResolveInfo) {
5967                        // ACK!  Must do something better with this.
5968                    }
5969                    ai = ri.activityInfo;
5970                    comp = new ComponentName(ai.applicationInfo.packageName,
5971                            ai.name);
5972                } else {
5973                    ai = getActivityInfo(comp, flags, userId);
5974                    if (ai == null) {
5975                        continue;
5976                    }
5977                }
5978
5979                // Look for any generic query activities that are duplicates
5980                // of this specific one, and remove them from the results.
5981                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5982                N = results.size();
5983                int j;
5984                for (j=specificsPos; j<N; j++) {
5985                    ResolveInfo sri = results.get(j);
5986                    if ((sri.activityInfo.name.equals(comp.getClassName())
5987                            && sri.activityInfo.applicationInfo.packageName.equals(
5988                                    comp.getPackageName()))
5989                        || (action != null && sri.filter.matchAction(action))) {
5990                        results.remove(j);
5991                        if (DEBUG_INTENT_MATCHING) Log.v(
5992                            TAG, "Removing duplicate item from " + j
5993                            + " due to specific " + specificsPos);
5994                        if (ri == null) {
5995                            ri = sri;
5996                        }
5997                        j--;
5998                        N--;
5999                    }
6000                }
6001
6002                // Add this specific item to its proper place.
6003                if (ri == null) {
6004                    ri = new ResolveInfo();
6005                    ri.activityInfo = ai;
6006                }
6007                results.add(specificsPos, ri);
6008                ri.specificIndex = i;
6009                specificsPos++;
6010            }
6011        }
6012
6013        // Now we go through the remaining generic results and remove any
6014        // duplicate actions that are found here.
6015        N = results.size();
6016        for (int i=specificsPos; i<N-1; i++) {
6017            final ResolveInfo rii = results.get(i);
6018            if (rii.filter == null) {
6019                continue;
6020            }
6021
6022            // Iterate over all of the actions of this result's intent
6023            // filter...  typically this should be just one.
6024            final Iterator<String> it = rii.filter.actionsIterator();
6025            if (it == null) {
6026                continue;
6027            }
6028            while (it.hasNext()) {
6029                final String action = it.next();
6030                if (resultsAction != null && resultsAction.equals(action)) {
6031                    // If this action was explicitly requested, then don't
6032                    // remove things that have it.
6033                    continue;
6034                }
6035                for (int j=i+1; j<N; j++) {
6036                    final ResolveInfo rij = results.get(j);
6037                    if (rij.filter != null && rij.filter.hasAction(action)) {
6038                        results.remove(j);
6039                        if (DEBUG_INTENT_MATCHING) Log.v(
6040                            TAG, "Removing duplicate item from " + j
6041                            + " due to action " + action + " at " + i);
6042                        j--;
6043                        N--;
6044                    }
6045                }
6046            }
6047
6048            // If the caller didn't request filter information, drop it now
6049            // so we don't have to marshall/unmarshall it.
6050            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6051                rii.filter = null;
6052            }
6053        }
6054
6055        // Filter out the caller activity if so requested.
6056        if (caller != null) {
6057            N = results.size();
6058            for (int i=0; i<N; i++) {
6059                ActivityInfo ainfo = results.get(i).activityInfo;
6060                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6061                        && caller.getClassName().equals(ainfo.name)) {
6062                    results.remove(i);
6063                    break;
6064                }
6065            }
6066        }
6067
6068        // If the caller didn't request filter information,
6069        // drop them now so we don't have to
6070        // marshall/unmarshall it.
6071        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6072            N = results.size();
6073            for (int i=0; i<N; i++) {
6074                results.get(i).filter = null;
6075            }
6076        }
6077
6078        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6079        return results;
6080    }
6081
6082    @Override
6083    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6084            String resolvedType, int flags, int userId) {
6085        return new ParceledListSlice<>(
6086                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6087    }
6088
6089    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6090            String resolvedType, int flags, int userId) {
6091        if (!sUserManager.exists(userId)) return Collections.emptyList();
6092        flags = updateFlagsForResolve(flags, userId, intent);
6093        ComponentName comp = intent.getComponent();
6094        if (comp == null) {
6095            if (intent.getSelector() != null) {
6096                intent = intent.getSelector();
6097                comp = intent.getComponent();
6098            }
6099        }
6100        if (comp != null) {
6101            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6102            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6103            if (ai != null) {
6104                ResolveInfo ri = new ResolveInfo();
6105                ri.activityInfo = ai;
6106                list.add(ri);
6107            }
6108            return list;
6109        }
6110
6111        // reader
6112        synchronized (mPackages) {
6113            String pkgName = intent.getPackage();
6114            if (pkgName == null) {
6115                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6116            }
6117            final PackageParser.Package pkg = mPackages.get(pkgName);
6118            if (pkg != null) {
6119                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6120                        userId);
6121            }
6122            return Collections.emptyList();
6123        }
6124    }
6125
6126    @Override
6127    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6128        if (!sUserManager.exists(userId)) return null;
6129        flags = updateFlagsForResolve(flags, userId, intent);
6130        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6131        if (query != null) {
6132            if (query.size() >= 1) {
6133                // If there is more than one service with the same priority,
6134                // just arbitrarily pick the first one.
6135                return query.get(0);
6136            }
6137        }
6138        return null;
6139    }
6140
6141    @Override
6142    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6143            String resolvedType, int flags, int userId) {
6144        return new ParceledListSlice<>(
6145                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6146    }
6147
6148    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6149            String resolvedType, int flags, int userId) {
6150        if (!sUserManager.exists(userId)) return Collections.emptyList();
6151        flags = updateFlagsForResolve(flags, userId, intent);
6152        ComponentName comp = intent.getComponent();
6153        if (comp == null) {
6154            if (intent.getSelector() != null) {
6155                intent = intent.getSelector();
6156                comp = intent.getComponent();
6157            }
6158        }
6159        if (comp != null) {
6160            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6161            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6162            if (si != null) {
6163                final ResolveInfo ri = new ResolveInfo();
6164                ri.serviceInfo = si;
6165                list.add(ri);
6166            }
6167            return list;
6168        }
6169
6170        // reader
6171        synchronized (mPackages) {
6172            String pkgName = intent.getPackage();
6173            if (pkgName == null) {
6174                return mServices.queryIntent(intent, resolvedType, flags, userId);
6175            }
6176            final PackageParser.Package pkg = mPackages.get(pkgName);
6177            if (pkg != null) {
6178                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6179                        userId);
6180            }
6181            return Collections.emptyList();
6182        }
6183    }
6184
6185    @Override
6186    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6187            String resolvedType, int flags, int userId) {
6188        return new ParceledListSlice<>(
6189                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6190    }
6191
6192    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6193            Intent intent, String resolvedType, int flags, int userId) {
6194        if (!sUserManager.exists(userId)) return Collections.emptyList();
6195        flags = updateFlagsForResolve(flags, userId, intent);
6196        ComponentName comp = intent.getComponent();
6197        if (comp == null) {
6198            if (intent.getSelector() != null) {
6199                intent = intent.getSelector();
6200                comp = intent.getComponent();
6201            }
6202        }
6203        if (comp != null) {
6204            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6205            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6206            if (pi != null) {
6207                final ResolveInfo ri = new ResolveInfo();
6208                ri.providerInfo = pi;
6209                list.add(ri);
6210            }
6211            return list;
6212        }
6213
6214        // reader
6215        synchronized (mPackages) {
6216            String pkgName = intent.getPackage();
6217            if (pkgName == null) {
6218                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6219            }
6220            final PackageParser.Package pkg = mPackages.get(pkgName);
6221            if (pkg != null) {
6222                return mProviders.queryIntentForPackage(
6223                        intent, resolvedType, flags, pkg.providers, userId);
6224            }
6225            return Collections.emptyList();
6226        }
6227    }
6228
6229    @Override
6230    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6231        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6232        flags = updateFlagsForPackage(flags, userId, null);
6233        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6234        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6235                true /* requireFullPermission */, false /* checkShell */,
6236                "get installed packages");
6237
6238        // writer
6239        synchronized (mPackages) {
6240            ArrayList<PackageInfo> list;
6241            if (listUninstalled) {
6242                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6243                for (PackageSetting ps : mSettings.mPackages.values()) {
6244                    final PackageInfo pi;
6245                    if (ps.pkg != null) {
6246                        pi = generatePackageInfo(ps, flags, userId);
6247                    } else {
6248                        pi = generatePackageInfo(ps, flags, userId);
6249                    }
6250                    if (pi != null) {
6251                        list.add(pi);
6252                    }
6253                }
6254            } else {
6255                list = new ArrayList<PackageInfo>(mPackages.size());
6256                for (PackageParser.Package p : mPackages.values()) {
6257                    final PackageInfo pi =
6258                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6259                    if (pi != null) {
6260                        list.add(pi);
6261                    }
6262                }
6263            }
6264
6265            return new ParceledListSlice<PackageInfo>(list);
6266        }
6267    }
6268
6269    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6270            String[] permissions, boolean[] tmp, int flags, int userId) {
6271        int numMatch = 0;
6272        final PermissionsState permissionsState = ps.getPermissionsState();
6273        for (int i=0; i<permissions.length; i++) {
6274            final String permission = permissions[i];
6275            if (permissionsState.hasPermission(permission, userId)) {
6276                tmp[i] = true;
6277                numMatch++;
6278            } else {
6279                tmp[i] = false;
6280            }
6281        }
6282        if (numMatch == 0) {
6283            return;
6284        }
6285        final PackageInfo pi;
6286        if (ps.pkg != null) {
6287            pi = generatePackageInfo(ps, flags, userId);
6288        } else {
6289            pi = generatePackageInfo(ps, flags, userId);
6290        }
6291        // The above might return null in cases of uninstalled apps or install-state
6292        // skew across users/profiles.
6293        if (pi != null) {
6294            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6295                if (numMatch == permissions.length) {
6296                    pi.requestedPermissions = permissions;
6297                } else {
6298                    pi.requestedPermissions = new String[numMatch];
6299                    numMatch = 0;
6300                    for (int i=0; i<permissions.length; i++) {
6301                        if (tmp[i]) {
6302                            pi.requestedPermissions[numMatch] = permissions[i];
6303                            numMatch++;
6304                        }
6305                    }
6306                }
6307            }
6308            list.add(pi);
6309        }
6310    }
6311
6312    @Override
6313    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6314            String[] permissions, int flags, int userId) {
6315        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6316        flags = updateFlagsForPackage(flags, userId, permissions);
6317        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6318
6319        // writer
6320        synchronized (mPackages) {
6321            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6322            boolean[] tmpBools = new boolean[permissions.length];
6323            if (listUninstalled) {
6324                for (PackageSetting ps : mSettings.mPackages.values()) {
6325                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6326                }
6327            } else {
6328                for (PackageParser.Package pkg : mPackages.values()) {
6329                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6330                    if (ps != null) {
6331                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6332                                userId);
6333                    }
6334                }
6335            }
6336
6337            return new ParceledListSlice<PackageInfo>(list);
6338        }
6339    }
6340
6341    @Override
6342    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6343        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6344        flags = updateFlagsForApplication(flags, userId, null);
6345        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6346
6347        // writer
6348        synchronized (mPackages) {
6349            ArrayList<ApplicationInfo> list;
6350            if (listUninstalled) {
6351                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6352                for (PackageSetting ps : mSettings.mPackages.values()) {
6353                    ApplicationInfo ai;
6354                    if (ps.pkg != null) {
6355                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6356                                ps.readUserState(userId), userId);
6357                    } else {
6358                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6359                    }
6360                    if (ai != null) {
6361                        list.add(ai);
6362                    }
6363                }
6364            } else {
6365                list = new ArrayList<ApplicationInfo>(mPackages.size());
6366                for (PackageParser.Package p : mPackages.values()) {
6367                    if (p.mExtras != null) {
6368                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6369                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6370                        if (ai != null) {
6371                            list.add(ai);
6372                        }
6373                    }
6374                }
6375            }
6376
6377            return new ParceledListSlice<ApplicationInfo>(list);
6378        }
6379    }
6380
6381    @Override
6382    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6383        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6384            return null;
6385        }
6386
6387        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6388                "getEphemeralApplications");
6389        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6390                true /* requireFullPermission */, false /* checkShell */,
6391                "getEphemeralApplications");
6392        synchronized (mPackages) {
6393            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6394                    .getEphemeralApplicationsLPw(userId);
6395            if (ephemeralApps != null) {
6396                return new ParceledListSlice<>(ephemeralApps);
6397            }
6398        }
6399        return null;
6400    }
6401
6402    @Override
6403    public boolean isEphemeralApplication(String packageName, int userId) {
6404        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6405                true /* requireFullPermission */, false /* checkShell */,
6406                "isEphemeral");
6407        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6408            return false;
6409        }
6410
6411        if (!isCallerSameApp(packageName)) {
6412            return false;
6413        }
6414        synchronized (mPackages) {
6415            PackageParser.Package pkg = mPackages.get(packageName);
6416            if (pkg != null) {
6417                return pkg.applicationInfo.isEphemeralApp();
6418            }
6419        }
6420        return false;
6421    }
6422
6423    @Override
6424    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6425        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6426            return null;
6427        }
6428
6429        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6430                true /* requireFullPermission */, false /* checkShell */,
6431                "getCookie");
6432        if (!isCallerSameApp(packageName)) {
6433            return null;
6434        }
6435        synchronized (mPackages) {
6436            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6437                    packageName, userId);
6438        }
6439    }
6440
6441    @Override
6442    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6443        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6444            return true;
6445        }
6446
6447        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6448                true /* requireFullPermission */, true /* checkShell */,
6449                "setCookie");
6450        if (!isCallerSameApp(packageName)) {
6451            return false;
6452        }
6453        synchronized (mPackages) {
6454            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6455                    packageName, cookie, userId);
6456        }
6457    }
6458
6459    @Override
6460    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6461        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6462            return null;
6463        }
6464
6465        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6466                "getEphemeralApplicationIcon");
6467        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6468                true /* requireFullPermission */, false /* checkShell */,
6469                "getEphemeralApplicationIcon");
6470        synchronized (mPackages) {
6471            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6472                    packageName, userId);
6473        }
6474    }
6475
6476    private boolean isCallerSameApp(String packageName) {
6477        PackageParser.Package pkg = mPackages.get(packageName);
6478        return pkg != null
6479                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6480    }
6481
6482    @Override
6483    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6484        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6485    }
6486
6487    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6488        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6489
6490        // reader
6491        synchronized (mPackages) {
6492            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6493            final int userId = UserHandle.getCallingUserId();
6494            while (i.hasNext()) {
6495                final PackageParser.Package p = i.next();
6496                if (p.applicationInfo == null) continue;
6497
6498                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6499                        && !p.applicationInfo.isDirectBootAware();
6500                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6501                        && p.applicationInfo.isDirectBootAware();
6502
6503                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6504                        && (!mSafeMode || isSystemApp(p))
6505                        && (matchesUnaware || matchesAware)) {
6506                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6507                    if (ps != null) {
6508                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6509                                ps.readUserState(userId), userId);
6510                        if (ai != null) {
6511                            finalList.add(ai);
6512                        }
6513                    }
6514                }
6515            }
6516        }
6517
6518        return finalList;
6519    }
6520
6521    @Override
6522    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6523        if (!sUserManager.exists(userId)) return null;
6524        flags = updateFlagsForComponent(flags, userId, name);
6525        // reader
6526        synchronized (mPackages) {
6527            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6528            PackageSetting ps = provider != null
6529                    ? mSettings.mPackages.get(provider.owner.packageName)
6530                    : null;
6531            return ps != null
6532                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6533                    ? PackageParser.generateProviderInfo(provider, flags,
6534                            ps.readUserState(userId), userId)
6535                    : null;
6536        }
6537    }
6538
6539    /**
6540     * @deprecated
6541     */
6542    @Deprecated
6543    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6544        // reader
6545        synchronized (mPackages) {
6546            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6547                    .entrySet().iterator();
6548            final int userId = UserHandle.getCallingUserId();
6549            while (i.hasNext()) {
6550                Map.Entry<String, PackageParser.Provider> entry = i.next();
6551                PackageParser.Provider p = entry.getValue();
6552                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6553
6554                if (ps != null && p.syncable
6555                        && (!mSafeMode || (p.info.applicationInfo.flags
6556                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6557                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6558                            ps.readUserState(userId), userId);
6559                    if (info != null) {
6560                        outNames.add(entry.getKey());
6561                        outInfo.add(info);
6562                    }
6563                }
6564            }
6565        }
6566    }
6567
6568    @Override
6569    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6570            int uid, int flags) {
6571        final int userId = processName != null ? UserHandle.getUserId(uid)
6572                : UserHandle.getCallingUserId();
6573        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6574        flags = updateFlagsForComponent(flags, userId, processName);
6575
6576        ArrayList<ProviderInfo> finalList = null;
6577        // reader
6578        synchronized (mPackages) {
6579            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6580            while (i.hasNext()) {
6581                final PackageParser.Provider p = i.next();
6582                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6583                if (ps != null && p.info.authority != null
6584                        && (processName == null
6585                                || (p.info.processName.equals(processName)
6586                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6587                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6588                    if (finalList == null) {
6589                        finalList = new ArrayList<ProviderInfo>(3);
6590                    }
6591                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6592                            ps.readUserState(userId), userId);
6593                    if (info != null) {
6594                        finalList.add(info);
6595                    }
6596                }
6597            }
6598        }
6599
6600        if (finalList != null) {
6601            Collections.sort(finalList, mProviderInitOrderSorter);
6602            return new ParceledListSlice<ProviderInfo>(finalList);
6603        }
6604
6605        return ParceledListSlice.emptyList();
6606    }
6607
6608    @Override
6609    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6610        // reader
6611        synchronized (mPackages) {
6612            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6613            return PackageParser.generateInstrumentationInfo(i, flags);
6614        }
6615    }
6616
6617    @Override
6618    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6619            String targetPackage, int flags) {
6620        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6621    }
6622
6623    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6624            int flags) {
6625        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6626
6627        // reader
6628        synchronized (mPackages) {
6629            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6630            while (i.hasNext()) {
6631                final PackageParser.Instrumentation p = i.next();
6632                if (targetPackage == null
6633                        || targetPackage.equals(p.info.targetPackage)) {
6634                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6635                            flags);
6636                    if (ii != null) {
6637                        finalList.add(ii);
6638                    }
6639                }
6640            }
6641        }
6642
6643        return finalList;
6644    }
6645
6646    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6647        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6648        if (overlays == null) {
6649            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6650            return;
6651        }
6652        for (PackageParser.Package opkg : overlays.values()) {
6653            // Not much to do if idmap fails: we already logged the error
6654            // and we certainly don't want to abort installation of pkg simply
6655            // because an overlay didn't fit properly. For these reasons,
6656            // ignore the return value of createIdmapForPackagePairLI.
6657            createIdmapForPackagePairLI(pkg, opkg);
6658        }
6659    }
6660
6661    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6662            PackageParser.Package opkg) {
6663        if (!opkg.mTrustedOverlay) {
6664            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6665                    opkg.baseCodePath + ": overlay not trusted");
6666            return false;
6667        }
6668        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6669        if (overlaySet == null) {
6670            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6671                    opkg.baseCodePath + " but target package has no known overlays");
6672            return false;
6673        }
6674        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6675        // TODO: generate idmap for split APKs
6676        try {
6677            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6678        } catch (InstallerException e) {
6679            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6680                    + opkg.baseCodePath);
6681            return false;
6682        }
6683        PackageParser.Package[] overlayArray =
6684            overlaySet.values().toArray(new PackageParser.Package[0]);
6685        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6686            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6687                return p1.mOverlayPriority - p2.mOverlayPriority;
6688            }
6689        };
6690        Arrays.sort(overlayArray, cmp);
6691
6692        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6693        int i = 0;
6694        for (PackageParser.Package p : overlayArray) {
6695            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6696        }
6697        return true;
6698    }
6699
6700    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6701        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
6702        try {
6703            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6704        } finally {
6705            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6706        }
6707    }
6708
6709    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6710        final File[] files = dir.listFiles();
6711        if (ArrayUtils.isEmpty(files)) {
6712            Log.d(TAG, "No files in app dir " + dir);
6713            return;
6714        }
6715
6716        if (DEBUG_PACKAGE_SCANNING) {
6717            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6718                    + " flags=0x" + Integer.toHexString(parseFlags));
6719        }
6720
6721        for (File file : files) {
6722            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6723                    && !PackageInstallerService.isStageName(file.getName());
6724            if (!isPackage) {
6725                // Ignore entries which are not packages
6726                continue;
6727            }
6728            try {
6729                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6730                        scanFlags, currentTime, null);
6731            } catch (PackageManagerException e) {
6732                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6733
6734                // Delete invalid userdata apps
6735                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6736                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6737                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6738                    removeCodePathLI(file);
6739                }
6740            }
6741        }
6742    }
6743
6744    private static File getSettingsProblemFile() {
6745        File dataDir = Environment.getDataDirectory();
6746        File systemDir = new File(dataDir, "system");
6747        File fname = new File(systemDir, "uiderrors.txt");
6748        return fname;
6749    }
6750
6751    static void reportSettingsProblem(int priority, String msg) {
6752        logCriticalInfo(priority, msg);
6753    }
6754
6755    static void logCriticalInfo(int priority, String msg) {
6756        Slog.println(priority, TAG, msg);
6757        EventLogTags.writePmCriticalInfo(msg);
6758        try {
6759            File fname = getSettingsProblemFile();
6760            FileOutputStream out = new FileOutputStream(fname, true);
6761            PrintWriter pw = new FastPrintWriter(out);
6762            SimpleDateFormat formatter = new SimpleDateFormat();
6763            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6764            pw.println(dateString + ": " + msg);
6765            pw.close();
6766            FileUtils.setPermissions(
6767                    fname.toString(),
6768                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6769                    -1, -1);
6770        } catch (java.io.IOException e) {
6771        }
6772    }
6773
6774    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6775        if (srcFile.isDirectory()) {
6776            final File baseFile = new File(pkg.baseCodePath);
6777            long maxModifiedTime = baseFile.lastModified();
6778            if (pkg.splitCodePaths != null) {
6779                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6780                    final File splitFile = new File(pkg.splitCodePaths[i]);
6781                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6782                }
6783            }
6784            return maxModifiedTime;
6785        }
6786        return srcFile.lastModified();
6787    }
6788
6789    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6790            final int policyFlags) throws PackageManagerException {
6791        // When upgrading from pre-N MR1, verify the package time stamp using the package
6792        // directory and not the APK file.
6793        final long lastModifiedTime = mIsPreNMR1Upgrade
6794                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6795        if (ps != null
6796                && ps.codePath.equals(srcFile)
6797                && ps.timeStamp == lastModifiedTime
6798                && !isCompatSignatureUpdateNeeded(pkg)
6799                && !isRecoverSignatureUpdateNeeded(pkg)) {
6800            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6801            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6802            ArraySet<PublicKey> signingKs;
6803            synchronized (mPackages) {
6804                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6805            }
6806            if (ps.signatures.mSignatures != null
6807                    && ps.signatures.mSignatures.length != 0
6808                    && signingKs != null) {
6809                // Optimization: reuse the existing cached certificates
6810                // if the package appears to be unchanged.
6811                pkg.mSignatures = ps.signatures.mSignatures;
6812                pkg.mSigningKeys = signingKs;
6813                return;
6814            }
6815
6816            Slog.w(TAG, "PackageSetting for " + ps.name
6817                    + " is missing signatures.  Collecting certs again to recover them.");
6818        } else {
6819            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6820        }
6821
6822        try {
6823            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
6824            PackageParser.collectCertificates(pkg, policyFlags);
6825        } catch (PackageParserException e) {
6826            throw PackageManagerException.from(e);
6827        } finally {
6828            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6829        }
6830    }
6831
6832    /**
6833     *  Traces a package scan.
6834     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6835     */
6836    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6837            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6838        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
6839        try {
6840            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6841        } finally {
6842            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6843        }
6844    }
6845
6846    /**
6847     *  Scans a package and returns the newly parsed package.
6848     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6849     */
6850    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6851            long currentTime, UserHandle user) throws PackageManagerException {
6852        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6853        PackageParser pp = new PackageParser();
6854        pp.setSeparateProcesses(mSeparateProcesses);
6855        pp.setOnlyCoreApps(mOnlyCore);
6856        pp.setDisplayMetrics(mMetrics);
6857
6858        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6859            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6860        }
6861
6862        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6863        final PackageParser.Package pkg;
6864        try {
6865            pkg = pp.parsePackage(scanFile, parseFlags);
6866        } catch (PackageParserException e) {
6867            throw PackageManagerException.from(e);
6868        } finally {
6869            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6870        }
6871
6872        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6873    }
6874
6875    /**
6876     *  Scans a package and returns the newly parsed package.
6877     *  @throws PackageManagerException on a parse error.
6878     */
6879    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6880            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6881            throws PackageManagerException {
6882        // If the package has children and this is the first dive in the function
6883        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6884        // packages (parent and children) would be successfully scanned before the
6885        // actual scan since scanning mutates internal state and we want to atomically
6886        // install the package and its children.
6887        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6888            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6889                scanFlags |= SCAN_CHECK_ONLY;
6890            }
6891        } else {
6892            scanFlags &= ~SCAN_CHECK_ONLY;
6893        }
6894
6895        // Scan the parent
6896        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6897                scanFlags, currentTime, user);
6898
6899        // Scan the children
6900        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6901        for (int i = 0; i < childCount; i++) {
6902            PackageParser.Package childPackage = pkg.childPackages.get(i);
6903            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6904                    currentTime, user);
6905        }
6906
6907
6908        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6909            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6910        }
6911
6912        return scannedPkg;
6913    }
6914
6915    /**
6916     *  Scans a package and returns the newly parsed package.
6917     *  @throws PackageManagerException on a parse error.
6918     */
6919    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6920            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6921            throws PackageManagerException {
6922        PackageSetting ps = null;
6923        PackageSetting updatedPkg;
6924        // reader
6925        synchronized (mPackages) {
6926            // Look to see if we already know about this package.
6927            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
6928            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6929                // This package has been renamed to its original name.  Let's
6930                // use that.
6931                ps = mSettings.getPackageLPr(oldName);
6932            }
6933            // If there was no original package, see one for the real package name.
6934            if (ps == null) {
6935                ps = mSettings.getPackageLPr(pkg.packageName);
6936            }
6937            // Check to see if this package could be hiding/updating a system
6938            // package.  Must look for it either under the original or real
6939            // package name depending on our state.
6940            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6941            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6942
6943            // If this is a package we don't know about on the system partition, we
6944            // may need to remove disabled child packages on the system partition
6945            // or may need to not add child packages if the parent apk is updated
6946            // on the data partition and no longer defines this child package.
6947            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6948                // If this is a parent package for an updated system app and this system
6949                // app got an OTA update which no longer defines some of the child packages
6950                // we have to prune them from the disabled system packages.
6951                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6952                if (disabledPs != null) {
6953                    final int scannedChildCount = (pkg.childPackages != null)
6954                            ? pkg.childPackages.size() : 0;
6955                    final int disabledChildCount = disabledPs.childPackageNames != null
6956                            ? disabledPs.childPackageNames.size() : 0;
6957                    for (int i = 0; i < disabledChildCount; i++) {
6958                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6959                        boolean disabledPackageAvailable = false;
6960                        for (int j = 0; j < scannedChildCount; j++) {
6961                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6962                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6963                                disabledPackageAvailable = true;
6964                                break;
6965                            }
6966                         }
6967                         if (!disabledPackageAvailable) {
6968                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6969                         }
6970                    }
6971                }
6972            }
6973        }
6974
6975        boolean updatedPkgBetter = false;
6976        // First check if this is a system package that may involve an update
6977        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6978            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6979            // it needs to drop FLAG_PRIVILEGED.
6980            if (locationIsPrivileged(scanFile)) {
6981                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6982            } else {
6983                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6984            }
6985
6986            if (ps != null && !ps.codePath.equals(scanFile)) {
6987                // The path has changed from what was last scanned...  check the
6988                // version of the new path against what we have stored to determine
6989                // what to do.
6990                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6991                if (pkg.mVersionCode <= ps.versionCode) {
6992                    // The system package has been updated and the code path does not match
6993                    // Ignore entry. Skip it.
6994                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6995                            + " ignored: updated version " + ps.versionCode
6996                            + " better than this " + pkg.mVersionCode);
6997                    if (!updatedPkg.codePath.equals(scanFile)) {
6998                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6999                                + ps.name + " changing from " + updatedPkg.codePathString
7000                                + " to " + scanFile);
7001                        updatedPkg.codePath = scanFile;
7002                        updatedPkg.codePathString = scanFile.toString();
7003                        updatedPkg.resourcePath = scanFile;
7004                        updatedPkg.resourcePathString = scanFile.toString();
7005                    }
7006                    updatedPkg.pkg = pkg;
7007                    updatedPkg.versionCode = pkg.mVersionCode;
7008
7009                    // Update the disabled system child packages to point to the package too.
7010                    final int childCount = updatedPkg.childPackageNames != null
7011                            ? updatedPkg.childPackageNames.size() : 0;
7012                    for (int i = 0; i < childCount; i++) {
7013                        String childPackageName = updatedPkg.childPackageNames.get(i);
7014                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7015                                childPackageName);
7016                        if (updatedChildPkg != null) {
7017                            updatedChildPkg.pkg = pkg;
7018                            updatedChildPkg.versionCode = pkg.mVersionCode;
7019                        }
7020                    }
7021
7022                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7023                            + scanFile + " ignored: updated version " + ps.versionCode
7024                            + " better than this " + pkg.mVersionCode);
7025                } else {
7026                    // The current app on the system partition is better than
7027                    // what we have updated to on the data partition; switch
7028                    // back to the system partition version.
7029                    // At this point, its safely assumed that package installation for
7030                    // apps in system partition will go through. If not there won't be a working
7031                    // version of the app
7032                    // writer
7033                    synchronized (mPackages) {
7034                        // Just remove the loaded entries from package lists.
7035                        mPackages.remove(ps.name);
7036                    }
7037
7038                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7039                            + " reverting from " + ps.codePathString
7040                            + ": new version " + pkg.mVersionCode
7041                            + " better than installed " + ps.versionCode);
7042
7043                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7044                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7045                    synchronized (mInstallLock) {
7046                        args.cleanUpResourcesLI();
7047                    }
7048                    synchronized (mPackages) {
7049                        mSettings.enableSystemPackageLPw(ps.name);
7050                    }
7051                    updatedPkgBetter = true;
7052                }
7053            }
7054        }
7055
7056        if (updatedPkg != null) {
7057            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7058            // initially
7059            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7060
7061            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7062            // flag set initially
7063            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7064                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7065            }
7066        }
7067
7068        // Verify certificates against what was last scanned
7069        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7070
7071        /*
7072         * A new system app appeared, but we already had a non-system one of the
7073         * same name installed earlier.
7074         */
7075        boolean shouldHideSystemApp = false;
7076        if (updatedPkg == null && ps != null
7077                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7078            /*
7079             * Check to make sure the signatures match first. If they don't,
7080             * wipe the installed application and its data.
7081             */
7082            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7083                    != PackageManager.SIGNATURE_MATCH) {
7084                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7085                        + " signatures don't match existing userdata copy; removing");
7086                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7087                        "scanPackageInternalLI")) {
7088                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7089                }
7090                ps = null;
7091            } else {
7092                /*
7093                 * If the newly-added system app is an older version than the
7094                 * already installed version, hide it. It will be scanned later
7095                 * and re-added like an update.
7096                 */
7097                if (pkg.mVersionCode <= ps.versionCode) {
7098                    shouldHideSystemApp = true;
7099                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7100                            + " but new version " + pkg.mVersionCode + " better than installed "
7101                            + ps.versionCode + "; hiding system");
7102                } else {
7103                    /*
7104                     * The newly found system app is a newer version that the
7105                     * one previously installed. Simply remove the
7106                     * already-installed application and replace it with our own
7107                     * while keeping the application data.
7108                     */
7109                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7110                            + " reverting from " + ps.codePathString + ": new version "
7111                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7112                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7113                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7114                    synchronized (mInstallLock) {
7115                        args.cleanUpResourcesLI();
7116                    }
7117                }
7118            }
7119        }
7120
7121        // The apk is forward locked (not public) if its code and resources
7122        // are kept in different files. (except for app in either system or
7123        // vendor path).
7124        // TODO grab this value from PackageSettings
7125        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7126            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7127                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7128            }
7129        }
7130
7131        // TODO: extend to support forward-locked splits
7132        String resourcePath = null;
7133        String baseResourcePath = null;
7134        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7135            if (ps != null && ps.resourcePathString != null) {
7136                resourcePath = ps.resourcePathString;
7137                baseResourcePath = ps.resourcePathString;
7138            } else {
7139                // Should not happen at all. Just log an error.
7140                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7141            }
7142        } else {
7143            resourcePath = pkg.codePath;
7144            baseResourcePath = pkg.baseCodePath;
7145        }
7146
7147        // Set application objects path explicitly.
7148        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7149        pkg.setApplicationInfoCodePath(pkg.codePath);
7150        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7151        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7152        pkg.setApplicationInfoResourcePath(resourcePath);
7153        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7154        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7155
7156        // Note that we invoke the following method only if we are about to unpack an application
7157        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7158                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7159
7160        /*
7161         * If the system app should be overridden by a previously installed
7162         * data, hide the system app now and let the /data/app scan pick it up
7163         * again.
7164         */
7165        if (shouldHideSystemApp) {
7166            synchronized (mPackages) {
7167                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7168            }
7169        }
7170
7171        return scannedPkg;
7172    }
7173
7174    private static String fixProcessName(String defProcessName,
7175            String processName) {
7176        if (processName == null) {
7177            return defProcessName;
7178        }
7179        return processName;
7180    }
7181
7182    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7183            throws PackageManagerException {
7184        if (pkgSetting.signatures.mSignatures != null) {
7185            // Already existing package. Make sure signatures match
7186            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7187                    == PackageManager.SIGNATURE_MATCH;
7188            if (!match) {
7189                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7190                        == PackageManager.SIGNATURE_MATCH;
7191            }
7192            if (!match) {
7193                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7194                        == PackageManager.SIGNATURE_MATCH;
7195            }
7196            if (!match) {
7197                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7198                        + pkg.packageName + " signatures do not match the "
7199                        + "previously installed version; ignoring!");
7200            }
7201        }
7202
7203        // Check for shared user signatures
7204        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7205            // Already existing package. Make sure signatures match
7206            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7207                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7208            if (!match) {
7209                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7210                        == PackageManager.SIGNATURE_MATCH;
7211            }
7212            if (!match) {
7213                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7214                        == PackageManager.SIGNATURE_MATCH;
7215            }
7216            if (!match) {
7217                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7218                        "Package " + pkg.packageName
7219                        + " has no signatures that match those in shared user "
7220                        + pkgSetting.sharedUser.name + "; ignoring!");
7221            }
7222        }
7223    }
7224
7225    /**
7226     * Enforces that only the system UID or root's UID can call a method exposed
7227     * via Binder.
7228     *
7229     * @param message used as message if SecurityException is thrown
7230     * @throws SecurityException if the caller is not system or root
7231     */
7232    private static final void enforceSystemOrRoot(String message) {
7233        final int uid = Binder.getCallingUid();
7234        if (uid != Process.SYSTEM_UID && uid != 0) {
7235            throw new SecurityException(message);
7236        }
7237    }
7238
7239    @Override
7240    public void performFstrimIfNeeded() {
7241        enforceSystemOrRoot("Only the system can request fstrim");
7242
7243        // Before everything else, see whether we need to fstrim.
7244        try {
7245            IMountService ms = PackageHelper.getMountService();
7246            if (ms != null) {
7247                boolean doTrim = false;
7248                final long interval = android.provider.Settings.Global.getLong(
7249                        mContext.getContentResolver(),
7250                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7251                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7252                if (interval > 0) {
7253                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7254                    if (timeSinceLast > interval) {
7255                        doTrim = true;
7256                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7257                                + "; running immediately");
7258                    }
7259                }
7260                if (doTrim) {
7261                    final boolean dexOptDialogShown;
7262                    synchronized (mPackages) {
7263                        dexOptDialogShown = mDexOptDialogShown;
7264                    }
7265                    if (!isFirstBoot() && dexOptDialogShown) {
7266                        try {
7267                            ActivityManager.getService().showBootMessage(
7268                                    mContext.getResources().getString(
7269                                            R.string.android_upgrading_fstrim), true);
7270                        } catch (RemoteException e) {
7271                        }
7272                    }
7273                    ms.runMaintenance();
7274                }
7275            } else {
7276                Slog.e(TAG, "Mount service unavailable!");
7277            }
7278        } catch (RemoteException e) {
7279            // Can't happen; MountService is local
7280        }
7281    }
7282
7283    @Override
7284    public void updatePackagesIfNeeded() {
7285        enforceSystemOrRoot("Only the system can request package update");
7286
7287        // We need to re-extract after an OTA.
7288        boolean causeUpgrade = isUpgrade();
7289
7290        // First boot or factory reset.
7291        // Note: we also handle devices that are upgrading to N right now as if it is their
7292        //       first boot, as they do not have profile data.
7293        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7294
7295        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7296        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7297
7298        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7299            return;
7300        }
7301
7302        List<PackageParser.Package> pkgs;
7303        synchronized (mPackages) {
7304            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7305        }
7306
7307        final long startTime = System.nanoTime();
7308        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7309                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7310
7311        final int elapsedTimeSeconds =
7312                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7313
7314        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7315        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7316        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7317        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7318        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7319    }
7320
7321    /**
7322     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7323     * containing statistics about the invocation. The array consists of three elements,
7324     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7325     * and {@code numberOfPackagesFailed}.
7326     */
7327    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7328            String compilerFilter) {
7329
7330        int numberOfPackagesVisited = 0;
7331        int numberOfPackagesOptimized = 0;
7332        int numberOfPackagesSkipped = 0;
7333        int numberOfPackagesFailed = 0;
7334        final int numberOfPackagesToDexopt = pkgs.size();
7335
7336        for (PackageParser.Package pkg : pkgs) {
7337            numberOfPackagesVisited++;
7338
7339            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7340                if (DEBUG_DEXOPT) {
7341                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7342                }
7343                numberOfPackagesSkipped++;
7344                continue;
7345            }
7346
7347            if (DEBUG_DEXOPT) {
7348                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7349                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7350            }
7351
7352            if (showDialog) {
7353                try {
7354                    ActivityManager.getService().showBootMessage(
7355                            mContext.getResources().getString(R.string.android_upgrading_apk,
7356                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7357                } catch (RemoteException e) {
7358                }
7359                synchronized (mPackages) {
7360                    mDexOptDialogShown = true;
7361                }
7362            }
7363
7364            // If the OTA updates a system app which was previously preopted to a non-preopted state
7365            // the app might end up being verified at runtime. That's because by default the apps
7366            // are verify-profile but for preopted apps there's no profile.
7367            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7368            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7369            // filter (by default interpret-only).
7370            // Note that at this stage unused apps are already filtered.
7371            if (isSystemApp(pkg) &&
7372                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7373                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7374                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7375            }
7376
7377            // If the OTA updates a system app which was previously preopted to a non-preopted state
7378            // the app might end up being verified at runtime. That's because by default the apps
7379            // are verify-profile but for preopted apps there's no profile.
7380            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7381            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7382            // filter (by default interpret-only).
7383            // Note that at this stage unused apps are already filtered.
7384            if (isSystemApp(pkg) &&
7385                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7386                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7387                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7388            }
7389
7390            // checkProfiles is false to avoid merging profiles during boot which
7391            // might interfere with background compilation (b/28612421).
7392            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7393            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7394            // trade-off worth doing to save boot time work.
7395            int dexOptStatus = performDexOptTraced(pkg.packageName,
7396                    false /* checkProfiles */,
7397                    compilerFilter,
7398                    false /* force */);
7399            switch (dexOptStatus) {
7400                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7401                    numberOfPackagesOptimized++;
7402                    break;
7403                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7404                    numberOfPackagesSkipped++;
7405                    break;
7406                case PackageDexOptimizer.DEX_OPT_FAILED:
7407                    numberOfPackagesFailed++;
7408                    break;
7409                default:
7410                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7411                    break;
7412            }
7413        }
7414
7415        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7416                numberOfPackagesFailed };
7417    }
7418
7419    @Override
7420    public void notifyPackageUse(String packageName, int reason) {
7421        synchronized (mPackages) {
7422            PackageParser.Package p = mPackages.get(packageName);
7423            if (p == null) {
7424                return;
7425            }
7426            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7427        }
7428    }
7429
7430    // TODO: this is not used nor needed. Delete it.
7431    @Override
7432    public boolean performDexOptIfNeeded(String packageName) {
7433        int dexOptStatus = performDexOptTraced(packageName,
7434                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7435        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7436    }
7437
7438    @Override
7439    public boolean performDexOpt(String packageName,
7440            boolean checkProfiles, int compileReason, boolean force) {
7441        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7442                getCompilerFilterForReason(compileReason), force);
7443        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7444    }
7445
7446    @Override
7447    public boolean performDexOptMode(String packageName,
7448            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7449        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7450                targetCompilerFilter, force);
7451        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7452    }
7453
7454    private int performDexOptTraced(String packageName,
7455                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7456        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7457        try {
7458            return performDexOptInternal(packageName, checkProfiles,
7459                    targetCompilerFilter, force);
7460        } finally {
7461            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7462        }
7463    }
7464
7465    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7466    // if the package can now be considered up to date for the given filter.
7467    private int performDexOptInternal(String packageName,
7468                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7469        PackageParser.Package p;
7470        synchronized (mPackages) {
7471            p = mPackages.get(packageName);
7472            if (p == null) {
7473                // Package could not be found. Report failure.
7474                return PackageDexOptimizer.DEX_OPT_FAILED;
7475            }
7476            mPackageUsage.maybeWriteAsync(mPackages);
7477            mCompilerStats.maybeWriteAsync();
7478        }
7479        long callingId = Binder.clearCallingIdentity();
7480        try {
7481            synchronized (mInstallLock) {
7482                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7483                        targetCompilerFilter, force);
7484            }
7485        } finally {
7486            Binder.restoreCallingIdentity(callingId);
7487        }
7488    }
7489
7490    public ArraySet<String> getOptimizablePackages() {
7491        ArraySet<String> pkgs = new ArraySet<String>();
7492        synchronized (mPackages) {
7493            for (PackageParser.Package p : mPackages.values()) {
7494                if (PackageDexOptimizer.canOptimizePackage(p)) {
7495                    pkgs.add(p.packageName);
7496                }
7497            }
7498        }
7499        return pkgs;
7500    }
7501
7502    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7503            boolean checkProfiles, String targetCompilerFilter,
7504            boolean force) {
7505        // Select the dex optimizer based on the force parameter.
7506        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7507        //       allocate an object here.
7508        PackageDexOptimizer pdo = force
7509                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7510                : mPackageDexOptimizer;
7511
7512        // Optimize all dependencies first. Note: we ignore the return value and march on
7513        // on errors.
7514        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7515        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7516        if (!deps.isEmpty()) {
7517            for (PackageParser.Package depPackage : deps) {
7518                // TODO: Analyze and investigate if we (should) profile libraries.
7519                // Currently this will do a full compilation of the library by default.
7520                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7521                        false /* checkProfiles */,
7522                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7523                        getOrCreateCompilerPackageStats(depPackage));
7524            }
7525        }
7526        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7527                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7528    }
7529
7530    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7531        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7532            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7533            Set<String> collectedNames = new HashSet<>();
7534            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7535
7536            retValue.remove(p);
7537
7538            return retValue;
7539        } else {
7540            return Collections.emptyList();
7541        }
7542    }
7543
7544    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7545            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7546        if (!collectedNames.contains(p.packageName)) {
7547            collectedNames.add(p.packageName);
7548            collected.add(p);
7549
7550            if (p.usesLibraries != null) {
7551                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7552            }
7553            if (p.usesOptionalLibraries != null) {
7554                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7555                        collectedNames);
7556            }
7557        }
7558    }
7559
7560    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7561            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7562        for (String libName : libs) {
7563            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7564            if (libPkg != null) {
7565                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7566            }
7567        }
7568    }
7569
7570    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7571        synchronized (mPackages) {
7572            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7573            if (lib != null && lib.apk != null) {
7574                return mPackages.get(lib.apk);
7575            }
7576        }
7577        return null;
7578    }
7579
7580    public void shutdown() {
7581        mPackageUsage.writeNow(mPackages);
7582        mCompilerStats.writeNow();
7583    }
7584
7585    @Override
7586    public void dumpProfiles(String packageName) {
7587        PackageParser.Package pkg;
7588        synchronized (mPackages) {
7589            pkg = mPackages.get(packageName);
7590            if (pkg == null) {
7591                throw new IllegalArgumentException("Unknown package: " + packageName);
7592            }
7593        }
7594        /* Only the shell, root, or the app user should be able to dump profiles. */
7595        int callingUid = Binder.getCallingUid();
7596        if (callingUid != Process.SHELL_UID &&
7597            callingUid != Process.ROOT_UID &&
7598            callingUid != pkg.applicationInfo.uid) {
7599            throw new SecurityException("dumpProfiles");
7600        }
7601
7602        synchronized (mInstallLock) {
7603            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7604            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7605            try {
7606                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7607                String gid = Integer.toString(sharedGid);
7608                String codePaths = TextUtils.join(";", allCodePaths);
7609                mInstaller.dumpProfiles(gid, packageName, codePaths);
7610            } catch (InstallerException e) {
7611                Slog.w(TAG, "Failed to dump profiles", e);
7612            }
7613            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7614        }
7615    }
7616
7617    @Override
7618    public void forceDexOpt(String packageName) {
7619        enforceSystemOrRoot("forceDexOpt");
7620
7621        PackageParser.Package pkg;
7622        synchronized (mPackages) {
7623            pkg = mPackages.get(packageName);
7624            if (pkg == null) {
7625                throw new IllegalArgumentException("Unknown package: " + packageName);
7626            }
7627        }
7628
7629        synchronized (mInstallLock) {
7630            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7631
7632            // Whoever is calling forceDexOpt wants a fully compiled package.
7633            // Don't use profiles since that may cause compilation to be skipped.
7634            final int res = performDexOptInternalWithDependenciesLI(pkg,
7635                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7636                    true /* force */);
7637
7638            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7639            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7640                throw new IllegalStateException("Failed to dexopt: " + res);
7641            }
7642        }
7643    }
7644
7645    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7646        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7647            Slog.w(TAG, "Unable to update from " + oldPkg.name
7648                    + " to " + newPkg.packageName
7649                    + ": old package not in system partition");
7650            return false;
7651        } else if (mPackages.get(oldPkg.name) != null) {
7652            Slog.w(TAG, "Unable to update from " + oldPkg.name
7653                    + " to " + newPkg.packageName
7654                    + ": old package still exists");
7655            return false;
7656        }
7657        return true;
7658    }
7659
7660    void removeCodePathLI(File codePath) {
7661        if (codePath.isDirectory()) {
7662            try {
7663                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7664            } catch (InstallerException e) {
7665                Slog.w(TAG, "Failed to remove code path", e);
7666            }
7667        } else {
7668            codePath.delete();
7669        }
7670    }
7671
7672    private int[] resolveUserIds(int userId) {
7673        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7674    }
7675
7676    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7677        if (pkg == null) {
7678            Slog.wtf(TAG, "Package was null!", new Throwable());
7679            return;
7680        }
7681        clearAppDataLeafLIF(pkg, userId, flags);
7682        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7683        for (int i = 0; i < childCount; i++) {
7684            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7685        }
7686    }
7687
7688    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7689        final PackageSetting ps;
7690        synchronized (mPackages) {
7691            ps = mSettings.mPackages.get(pkg.packageName);
7692        }
7693        for (int realUserId : resolveUserIds(userId)) {
7694            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7695            try {
7696                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7697                        ceDataInode);
7698            } catch (InstallerException e) {
7699                Slog.w(TAG, String.valueOf(e));
7700            }
7701        }
7702    }
7703
7704    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7705        if (pkg == null) {
7706            Slog.wtf(TAG, "Package was null!", new Throwable());
7707            return;
7708        }
7709        destroyAppDataLeafLIF(pkg, userId, flags);
7710        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7711        for (int i = 0; i < childCount; i++) {
7712            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7713        }
7714    }
7715
7716    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7717        final PackageSetting ps;
7718        synchronized (mPackages) {
7719            ps = mSettings.mPackages.get(pkg.packageName);
7720        }
7721        for (int realUserId : resolveUserIds(userId)) {
7722            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7723            try {
7724                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7725                        ceDataInode);
7726            } catch (InstallerException e) {
7727                Slog.w(TAG, String.valueOf(e));
7728            }
7729        }
7730    }
7731
7732    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7733        if (pkg == null) {
7734            Slog.wtf(TAG, "Package was null!", new Throwable());
7735            return;
7736        }
7737        destroyAppProfilesLeafLIF(pkg);
7738        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7739        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7740        for (int i = 0; i < childCount; i++) {
7741            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7742            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7743                    true /* removeBaseMarker */);
7744        }
7745    }
7746
7747    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7748            boolean removeBaseMarker) {
7749        if (pkg.isForwardLocked()) {
7750            return;
7751        }
7752
7753        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7754            try {
7755                path = PackageManagerServiceUtils.realpath(new File(path));
7756            } catch (IOException e) {
7757                // TODO: Should we return early here ?
7758                Slog.w(TAG, "Failed to get canonical path", e);
7759                continue;
7760            }
7761
7762            final String useMarker = path.replace('/', '@');
7763            for (int realUserId : resolveUserIds(userId)) {
7764                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7765                if (removeBaseMarker) {
7766                    File foreignUseMark = new File(profileDir, useMarker);
7767                    if (foreignUseMark.exists()) {
7768                        if (!foreignUseMark.delete()) {
7769                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7770                                    + pkg.packageName);
7771                        }
7772                    }
7773                }
7774
7775                File[] markers = profileDir.listFiles();
7776                if (markers != null) {
7777                    final String searchString = "@" + pkg.packageName + "@";
7778                    // We also delete all markers that contain the package name we're
7779                    // uninstalling. These are associated with secondary dex-files belonging
7780                    // to the package. Reconstructing the path of these dex files is messy
7781                    // in general.
7782                    for (File marker : markers) {
7783                        if (marker.getName().indexOf(searchString) > 0) {
7784                            if (!marker.delete()) {
7785                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7786                                    + pkg.packageName);
7787                            }
7788                        }
7789                    }
7790                }
7791            }
7792        }
7793    }
7794
7795    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7796        try {
7797            mInstaller.destroyAppProfiles(pkg.packageName);
7798        } catch (InstallerException e) {
7799            Slog.w(TAG, String.valueOf(e));
7800        }
7801    }
7802
7803    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7804        if (pkg == null) {
7805            Slog.wtf(TAG, "Package was null!", new Throwable());
7806            return;
7807        }
7808        clearAppProfilesLeafLIF(pkg);
7809        // We don't remove the base foreign use marker when clearing profiles because
7810        // we will rename it when the app is updated. Unlike the actual profile contents,
7811        // the foreign use marker is good across installs.
7812        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7813        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7814        for (int i = 0; i < childCount; i++) {
7815            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7816        }
7817    }
7818
7819    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7820        try {
7821            mInstaller.clearAppProfiles(pkg.packageName);
7822        } catch (InstallerException e) {
7823            Slog.w(TAG, String.valueOf(e));
7824        }
7825    }
7826
7827    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7828            long lastUpdateTime) {
7829        // Set parent install/update time
7830        PackageSetting ps = (PackageSetting) pkg.mExtras;
7831        if (ps != null) {
7832            ps.firstInstallTime = firstInstallTime;
7833            ps.lastUpdateTime = lastUpdateTime;
7834        }
7835        // Set children install/update time
7836        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7837        for (int i = 0; i < childCount; i++) {
7838            PackageParser.Package childPkg = pkg.childPackages.get(i);
7839            ps = (PackageSetting) childPkg.mExtras;
7840            if (ps != null) {
7841                ps.firstInstallTime = firstInstallTime;
7842                ps.lastUpdateTime = lastUpdateTime;
7843            }
7844        }
7845    }
7846
7847    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7848            PackageParser.Package changingLib) {
7849        if (file.path != null) {
7850            usesLibraryFiles.add(file.path);
7851            return;
7852        }
7853        PackageParser.Package p = mPackages.get(file.apk);
7854        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7855            // If we are doing this while in the middle of updating a library apk,
7856            // then we need to make sure to use that new apk for determining the
7857            // dependencies here.  (We haven't yet finished committing the new apk
7858            // to the package manager state.)
7859            if (p == null || p.packageName.equals(changingLib.packageName)) {
7860                p = changingLib;
7861            }
7862        }
7863        if (p != null) {
7864            usesLibraryFiles.addAll(p.getAllCodePaths());
7865        }
7866    }
7867
7868    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
7869            PackageParser.Package changingLib) throws PackageManagerException {
7870        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7871            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7872            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7873            for (int i=0; i<N; i++) {
7874                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7875                if (file == null) {
7876                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7877                            "Package " + pkg.packageName + " requires unavailable shared library "
7878                            + pkg.usesLibraries.get(i) + "; failing!");
7879                }
7880                addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
7881            }
7882            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7883            for (int i=0; i<N; i++) {
7884                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7885                if (file == null) {
7886                    Slog.w(TAG, "Package " + pkg.packageName
7887                            + " desires unavailable shared library "
7888                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7889                } else {
7890                    addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
7891                }
7892            }
7893            N = usesLibraryFiles.size();
7894            if (N > 0) {
7895                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7896            } else {
7897                pkg.usesLibraryFiles = null;
7898            }
7899        }
7900    }
7901
7902    private static boolean hasString(List<String> list, List<String> which) {
7903        if (list == null) {
7904            return false;
7905        }
7906        for (int i=list.size()-1; i>=0; i--) {
7907            for (int j=which.size()-1; j>=0; j--) {
7908                if (which.get(j).equals(list.get(i))) {
7909                    return true;
7910                }
7911            }
7912        }
7913        return false;
7914    }
7915
7916    private void updateAllSharedLibrariesLPw() {
7917        for (PackageParser.Package pkg : mPackages.values()) {
7918            try {
7919                updateSharedLibrariesLPr(pkg, null);
7920            } catch (PackageManagerException e) {
7921                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7922            }
7923        }
7924    }
7925
7926    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7927            PackageParser.Package changingPkg) {
7928        ArrayList<PackageParser.Package> res = null;
7929        for (PackageParser.Package pkg : mPackages.values()) {
7930            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7931                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7932                if (res == null) {
7933                    res = new ArrayList<PackageParser.Package>();
7934                }
7935                res.add(pkg);
7936                try {
7937                    updateSharedLibrariesLPr(pkg, changingPkg);
7938                } catch (PackageManagerException e) {
7939                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7940                }
7941            }
7942        }
7943        return res;
7944    }
7945
7946    /**
7947     * Derive the value of the {@code cpuAbiOverride} based on the provided
7948     * value and an optional stored value from the package settings.
7949     */
7950    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7951        String cpuAbiOverride = null;
7952
7953        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7954            cpuAbiOverride = null;
7955        } else if (abiOverride != null) {
7956            cpuAbiOverride = abiOverride;
7957        } else if (settings != null) {
7958            cpuAbiOverride = settings.cpuAbiOverrideString;
7959        }
7960
7961        return cpuAbiOverride;
7962    }
7963
7964    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7965            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7966                    throws PackageManagerException {
7967        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7968        // If the package has children and this is the first dive in the function
7969        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7970        // whether all packages (parent and children) would be successfully scanned
7971        // before the actual scan since scanning mutates internal state and we want
7972        // to atomically install the package and its children.
7973        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7974            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7975                scanFlags |= SCAN_CHECK_ONLY;
7976            }
7977        } else {
7978            scanFlags &= ~SCAN_CHECK_ONLY;
7979        }
7980
7981        final PackageParser.Package scannedPkg;
7982        try {
7983            // Scan the parent
7984            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7985            // Scan the children
7986            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7987            for (int i = 0; i < childCount; i++) {
7988                PackageParser.Package childPkg = pkg.childPackages.get(i);
7989                scanPackageLI(childPkg, policyFlags,
7990                        scanFlags, currentTime, user);
7991            }
7992        } finally {
7993            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7994        }
7995
7996        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7997            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7998        }
7999
8000        return scannedPkg;
8001    }
8002
8003    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8004            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8005        boolean success = false;
8006        try {
8007            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8008                    currentTime, user);
8009            success = true;
8010            return res;
8011        } finally {
8012            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8013                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8014                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8015                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8016                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8017            }
8018        }
8019    }
8020
8021    /**
8022     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8023     */
8024    private static boolean apkHasCode(String fileName) {
8025        StrictJarFile jarFile = null;
8026        try {
8027            jarFile = new StrictJarFile(fileName,
8028                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8029            return jarFile.findEntry("classes.dex") != null;
8030        } catch (IOException ignore) {
8031        } finally {
8032            try {
8033                if (jarFile != null) {
8034                    jarFile.close();
8035                }
8036            } catch (IOException ignore) {}
8037        }
8038        return false;
8039    }
8040
8041    /**
8042     * Enforces code policy for the package. This ensures that if an APK has
8043     * declared hasCode="true" in its manifest that the APK actually contains
8044     * code.
8045     *
8046     * @throws PackageManagerException If bytecode could not be found when it should exist
8047     */
8048    private static void assertCodePolicy(PackageParser.Package pkg)
8049            throws PackageManagerException {
8050        final boolean shouldHaveCode =
8051                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8052        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8053            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8054                    "Package " + pkg.baseCodePath + " code is missing");
8055        }
8056
8057        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8058            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8059                final boolean splitShouldHaveCode =
8060                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8061                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8062                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8063                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8064                }
8065            }
8066        }
8067    }
8068
8069    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8070            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8071                    throws PackageManagerException {
8072        if (DEBUG_PACKAGE_SCANNING) {
8073            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8074                Log.d(TAG, "Scanning package " + pkg.packageName);
8075        }
8076
8077        applyPolicy(pkg, policyFlags);
8078
8079        assertPackageIsValid(pkg, policyFlags);
8080
8081        // Initialize package source and resource directories
8082        final File scanFile = new File(pkg.codePath);
8083        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8084        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8085
8086        SharedUserSetting suid = null;
8087        PackageSetting pkgSetting = null;
8088
8089        // Getting the package setting may have a side-effect, so if we
8090        // are only checking if scan would succeed, stash a copy of the
8091        // old setting to restore at the end.
8092        PackageSetting nonMutatedPs = null;
8093
8094        // writer
8095        synchronized (mPackages) {
8096            if (pkg.mSharedUserId != null) {
8097                // SIDE EFFECTS; may potentially allocate a new shared user
8098                suid = mSettings.getSharedUserLPw(
8099                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
8100                if (DEBUG_PACKAGE_SCANNING) {
8101                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8102                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8103                                + "): packages=" + suid.packages);
8104                }
8105            }
8106
8107            // Check if we are renaming from an original package name.
8108            PackageSetting origPackage = null;
8109            String realName = null;
8110            if (pkg.mOriginalPackages != null) {
8111                // This package may need to be renamed to a previously
8112                // installed name.  Let's check on that...
8113                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8114                if (pkg.mOriginalPackages.contains(renamed)) {
8115                    // This package had originally been installed as the
8116                    // original name, and we have already taken care of
8117                    // transitioning to the new one.  Just update the new
8118                    // one to continue using the old name.
8119                    realName = pkg.mRealPackage;
8120                    if (!pkg.packageName.equals(renamed)) {
8121                        // Callers into this function may have already taken
8122                        // care of renaming the package; only do it here if
8123                        // it is not already done.
8124                        pkg.setPackageName(renamed);
8125                    }
8126                } else {
8127                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8128                        if ((origPackage = mSettings.getPackageLPr(
8129                                pkg.mOriginalPackages.get(i))) != null) {
8130                            // We do have the package already installed under its
8131                            // original name...  should we use it?
8132                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8133                                // New package is not compatible with original.
8134                                origPackage = null;
8135                                continue;
8136                            } else if (origPackage.sharedUser != null) {
8137                                // Make sure uid is compatible between packages.
8138                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8139                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8140                                            + " to " + pkg.packageName + ": old uid "
8141                                            + origPackage.sharedUser.name
8142                                            + " differs from " + pkg.mSharedUserId);
8143                                    origPackage = null;
8144                                    continue;
8145                                }
8146                                // TODO: Add case when shared user id is added [b/28144775]
8147                            } else {
8148                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8149                                        + pkg.packageName + " to old name " + origPackage.name);
8150                            }
8151                            break;
8152                        }
8153                    }
8154                }
8155            }
8156
8157            if (mTransferedPackages.contains(pkg.packageName)) {
8158                Slog.w(TAG, "Package " + pkg.packageName
8159                        + " was transferred to another, but its .apk remains");
8160            }
8161
8162            // See comments in nonMutatedPs declaration
8163            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8164                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8165                if (foundPs != null) {
8166                    nonMutatedPs = new PackageSetting(foundPs);
8167                }
8168            }
8169
8170            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8171            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
8172                PackageManagerService.reportSettingsProblem(Log.WARN,
8173                        "Package " + pkg.packageName + " shared user changed from "
8174                                + (pkgSetting.sharedUser != null
8175                                        ? pkgSetting.sharedUser.name : "<nothing>")
8176                                + " to "
8177                                + (suid != null ? suid.name : "<nothing>")
8178                                + "; replacing with new");
8179                pkgSetting = null;
8180            }
8181            final PackageSetting oldPkgSetting =
8182                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
8183            final PackageSetting disabledPkgSetting =
8184                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8185            if (pkgSetting == null) {
8186                final String parentPackageName = (pkg.parentPackage != null)
8187                        ? pkg.parentPackage.packageName : null;
8188                // REMOVE SharedUserSetting from method; update in a separate call
8189                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
8190                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
8191                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
8192                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
8193                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
8194                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
8195                        UserManagerService.getInstance());
8196                // SIDE EFFECTS; updates system state; move elsewhere
8197                if (origPackage != null) {
8198                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
8199                }
8200                mSettings.addUserToSettingLPw(pkgSetting);
8201            } else {
8202                // REMOVE SharedUserSetting from method; update in a separate call
8203                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
8204                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
8205                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
8206                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
8207                        UserManagerService.getInstance());
8208            }
8209            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
8210            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
8211
8212            // SIDE EFFECTS; modifies system state; move elsewhere
8213            if (pkgSetting.origPackage != null) {
8214                // If we are first transitioning from an original package,
8215                // fix up the new package's name now.  We need to do this after
8216                // looking up the package under its new name, so getPackageLP
8217                // can take care of fiddling things correctly.
8218                pkg.setPackageName(origPackage.name);
8219
8220                // File a report about this.
8221                String msg = "New package " + pkgSetting.realName
8222                        + " renamed to replace old package " + pkgSetting.name;
8223                reportSettingsProblem(Log.WARN, msg);
8224
8225                // Make a note of it.
8226                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8227                    mTransferedPackages.add(origPackage.name);
8228                }
8229
8230                // No longer need to retain this.
8231                pkgSetting.origPackage = null;
8232            }
8233
8234            // SIDE EFFECTS; modifies system state; move elsewhere
8235            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8236                // Make a note of it.
8237                mTransferedPackages.add(pkg.packageName);
8238            }
8239
8240            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8241                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8242            }
8243
8244            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8245                // Check all shared libraries and map to their actual file path.
8246                // We only do this here for apps not on a system dir, because those
8247                // are the only ones that can fail an install due to this.  We
8248                // will take care of the system apps by updating all of their
8249                // library paths after the scan is done.
8250                updateSharedLibrariesLPr(pkg, null);
8251            }
8252
8253            if (mFoundPolicyFile) {
8254                SELinuxMMAC.assignSeinfoValue(pkg);
8255            }
8256
8257            pkg.applicationInfo.uid = pkgSetting.appId;
8258            pkg.mExtras = pkgSetting;
8259            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8260                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8261                    // We just determined the app is signed correctly, so bring
8262                    // over the latest parsed certs.
8263                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8264                } else {
8265                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8266                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8267                                "Package " + pkg.packageName + " upgrade keys do not match the "
8268                                + "previously installed version");
8269                    } else {
8270                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8271                        String msg = "System package " + pkg.packageName
8272                                + " signature changed; retaining data.";
8273                        reportSettingsProblem(Log.WARN, msg);
8274                    }
8275                }
8276            } else {
8277                try {
8278                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
8279                    verifySignaturesLP(pkgSetting, pkg);
8280                    // We just determined the app is signed correctly, so bring
8281                    // over the latest parsed certs.
8282                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8283                } catch (PackageManagerException e) {
8284                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8285                        throw e;
8286                    }
8287                    // The signature has changed, but this package is in the system
8288                    // image...  let's recover!
8289                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8290                    // However...  if this package is part of a shared user, but it
8291                    // doesn't match the signature of the shared user, let's fail.
8292                    // What this means is that you can't change the signatures
8293                    // associated with an overall shared user, which doesn't seem all
8294                    // that unreasonable.
8295                    if (pkgSetting.sharedUser != null) {
8296                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8297                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8298                            throw new PackageManagerException(
8299                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8300                                    "Signature mismatch for shared user: "
8301                                            + pkgSetting.sharedUser);
8302                        }
8303                    }
8304                    // File a report about this.
8305                    String msg = "System package " + pkg.packageName
8306                            + " signature changed; retaining data.";
8307                    reportSettingsProblem(Log.WARN, msg);
8308                }
8309            }
8310
8311            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8312                // This package wants to adopt ownership of permissions from
8313                // another package.
8314                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8315                    final String origName = pkg.mAdoptPermissions.get(i);
8316                    final PackageSetting orig = mSettings.getPackageLPr(origName);
8317                    if (orig != null) {
8318                        if (verifyPackageUpdateLPr(orig, pkg)) {
8319                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8320                                    + pkg.packageName);
8321                            // SIDE EFFECTS; updates permissions system state; move elsewhere
8322                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8323                        }
8324                    }
8325                }
8326            }
8327        }
8328
8329        pkg.applicationInfo.processName = fixProcessName(
8330                pkg.applicationInfo.packageName,
8331                pkg.applicationInfo.processName);
8332
8333        if (pkg != mPlatformPackage) {
8334            // Get all of our default paths setup
8335            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8336        }
8337
8338        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8339
8340        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8341            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
8342            derivePackageAbi(
8343                    pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
8344            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8345
8346            // Some system apps still use directory structure for native libraries
8347            // in which case we might end up not detecting abi solely based on apk
8348            // structure. Try to detect abi based on directory structure.
8349            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8350                    pkg.applicationInfo.primaryCpuAbi == null) {
8351                setBundledAppAbisAndRoots(pkg, pkgSetting);
8352                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8353            }
8354        } else {
8355            if ((scanFlags & SCAN_MOVE) != 0) {
8356                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8357                // but we already have this packages package info in the PackageSetting. We just
8358                // use that and derive the native library path based on the new codepath.
8359                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8360                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8361            }
8362
8363            // Set native library paths again. For moves, the path will be updated based on the
8364            // ABIs we've determined above. For non-moves, the path will be updated based on the
8365            // ABIs we determined during compilation, but the path will depend on the final
8366            // package path (after the rename away from the stage path).
8367            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8368        }
8369
8370        // This is a special case for the "system" package, where the ABI is
8371        // dictated by the zygote configuration (and init.rc). We should keep track
8372        // of this ABI so that we can deal with "normal" applications that run under
8373        // the same UID correctly.
8374        if (mPlatformPackage == pkg) {
8375            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8376                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8377        }
8378
8379        // If there's a mismatch between the abi-override in the package setting
8380        // and the abiOverride specified for the install. Warn about this because we
8381        // would've already compiled the app without taking the package setting into
8382        // account.
8383        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8384            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8385                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8386                        " for package " + pkg.packageName);
8387            }
8388        }
8389
8390        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8391        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8392        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8393
8394        // Copy the derived override back to the parsed package, so that we can
8395        // update the package settings accordingly.
8396        pkg.cpuAbiOverride = cpuAbiOverride;
8397
8398        if (DEBUG_ABI_SELECTION) {
8399            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8400                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8401                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8402        }
8403
8404        // Push the derived path down into PackageSettings so we know what to
8405        // clean up at uninstall time.
8406        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8407
8408        if (DEBUG_ABI_SELECTION) {
8409            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8410                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8411                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8412        }
8413
8414        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
8415        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8416            // We don't do this here during boot because we can do it all
8417            // at once after scanning all existing packages.
8418            //
8419            // We also do this *before* we perform dexopt on this package, so that
8420            // we can avoid redundant dexopts, and also to make sure we've got the
8421            // code and package path correct.
8422            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
8423        }
8424
8425        if (mFactoryTest && pkg.requestedPermissions.contains(
8426                android.Manifest.permission.FACTORY_TEST)) {
8427            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8428        }
8429
8430        if (isSystemApp(pkg)) {
8431            pkgSetting.isOrphaned = true;
8432        }
8433
8434        // Take care of first install / last update times.
8435        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8436        if (currentTime != 0) {
8437            if (pkgSetting.firstInstallTime == 0) {
8438                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8439            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
8440                pkgSetting.lastUpdateTime = currentTime;
8441            }
8442        } else if (pkgSetting.firstInstallTime == 0) {
8443            // We need *something*.  Take time time stamp of the file.
8444            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8445        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8446            if (scanFileTime != pkgSetting.timeStamp) {
8447                // A package on the system image has changed; consider this
8448                // to be an update.
8449                pkgSetting.lastUpdateTime = scanFileTime;
8450            }
8451        }
8452        pkgSetting.setTimeStamp(scanFileTime);
8453
8454        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8455            if (nonMutatedPs != null) {
8456                synchronized (mPackages) {
8457                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8458                }
8459            }
8460        } else {
8461            // Modify state for the given package setting
8462            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
8463                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
8464        }
8465        return pkg;
8466    }
8467
8468    /**
8469     * Applies policy to the parsed package based upon the given policy flags.
8470     * Ensures the package is in a good state.
8471     * <p>
8472     * Implementation detail: This method must NOT have any side effect. It would
8473     * ideally be static, but, it requires locks to read system state.
8474     */
8475    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
8476        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8477            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8478            if (pkg.applicationInfo.isDirectBootAware()) {
8479                // we're direct boot aware; set for all components
8480                for (PackageParser.Service s : pkg.services) {
8481                    s.info.encryptionAware = s.info.directBootAware = true;
8482                }
8483                for (PackageParser.Provider p : pkg.providers) {
8484                    p.info.encryptionAware = p.info.directBootAware = true;
8485                }
8486                for (PackageParser.Activity a : pkg.activities) {
8487                    a.info.encryptionAware = a.info.directBootAware = true;
8488                }
8489                for (PackageParser.Activity r : pkg.receivers) {
8490                    r.info.encryptionAware = r.info.directBootAware = true;
8491                }
8492            }
8493        } else {
8494            // Only allow system apps to be flagged as core apps.
8495            pkg.coreApp = false;
8496            // clear flags not applicable to regular apps
8497            pkg.applicationInfo.privateFlags &=
8498                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8499            pkg.applicationInfo.privateFlags &=
8500                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8501        }
8502        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8503
8504        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8505            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8506        }
8507
8508        if (!isSystemApp(pkg)) {
8509            // Only system apps can use these features.
8510            pkg.mOriginalPackages = null;
8511            pkg.mRealPackage = null;
8512            pkg.mAdoptPermissions = null;
8513        }
8514    }
8515
8516    /**
8517     * Asserts the parsed package is valid according to teh given policy. If the
8518     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
8519     * <p>
8520     * Implementation detail: This method must NOT have any side effects. It would
8521     * ideally be static, but, it requires locks to read system state.
8522     *
8523     * @throws PackageManagerException If the package fails any of the validation checks
8524     */
8525    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags)
8526            throws PackageManagerException {
8527        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8528            assertCodePolicy(pkg);
8529        }
8530
8531        if (pkg.applicationInfo.getCodePath() == null ||
8532                pkg.applicationInfo.getResourcePath() == null) {
8533            // Bail out. The resource and code paths haven't been set.
8534            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8535                    "Code and resource paths haven't been set correctly");
8536        }
8537
8538        // Make sure we're not adding any bogus keyset info
8539        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8540        ksms.assertScannedPackageValid(pkg);
8541
8542        synchronized (mPackages) {
8543            // The special "android" package can only be defined once
8544            if (pkg.packageName.equals("android")) {
8545                if (mAndroidApplication != null) {
8546                    Slog.w(TAG, "*************************************************");
8547                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8548                    Slog.w(TAG, " codePath=" + pkg.codePath);
8549                    Slog.w(TAG, "*************************************************");
8550                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8551                            "Core android package being redefined.  Skipping.");
8552                }
8553            }
8554
8555            // A package name must be unique; don't allow duplicates
8556            if (mPackages.containsKey(pkg.packageName)
8557                    || mSharedLibraries.containsKey(pkg.packageName)) {
8558                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8559                        "Application package " + pkg.packageName
8560                        + " already installed.  Skipping duplicate.");
8561            }
8562
8563            // Only privileged apps and updated privileged apps can add child packages.
8564            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8565                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8566                    throw new PackageManagerException("Only privileged apps can add child "
8567                            + "packages. Ignoring package " + pkg.packageName);
8568                }
8569                final int childCount = pkg.childPackages.size();
8570                for (int i = 0; i < childCount; i++) {
8571                    PackageParser.Package childPkg = pkg.childPackages.get(i);
8572                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8573                            childPkg.packageName)) {
8574                        throw new PackageManagerException("Can't override child of "
8575                                + "another disabled app. Ignoring package " + pkg.packageName);
8576                    }
8577                }
8578            }
8579
8580            // If we're only installing presumed-existing packages, require that the
8581            // scanned APK is both already known and at the path previously established
8582            // for it.  Previously unknown packages we pick up normally, but if we have an
8583            // a priori expectation about this package's install presence, enforce it.
8584            // With a singular exception for new system packages. When an OTA contains
8585            // a new system package, we allow the codepath to change from a system location
8586            // to the user-installed location. If we don't allow this change, any newer,
8587            // user-installed version of the application will be ignored.
8588            if ((policyFlags & SCAN_REQUIRE_KNOWN) != 0) {
8589                if (mExpectingBetter.containsKey(pkg.packageName)) {
8590                    logCriticalInfo(Log.WARN,
8591                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8592                } else {
8593                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
8594                    if (known != null) {
8595                        if (DEBUG_PACKAGE_SCANNING) {
8596                            Log.d(TAG, "Examining " + pkg.codePath
8597                                    + " and requiring known paths " + known.codePathString
8598                                    + " & " + known.resourcePathString);
8599                        }
8600                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8601                                || !pkg.applicationInfo.getResourcePath().equals(
8602                                        known.resourcePathString)) {
8603                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8604                                    "Application package " + pkg.packageName
8605                                    + " found at " + pkg.applicationInfo.getCodePath()
8606                                    + " but expected at " + known.codePathString
8607                                    + "; ignoring.");
8608                        }
8609                    }
8610                }
8611            }
8612
8613            // Verify that this new package doesn't have any content providers
8614            // that conflict with existing packages.  Only do this if the
8615            // package isn't already installed, since we don't want to break
8616            // things that are installed.
8617            if ((policyFlags & SCAN_NEW_INSTALL) != 0) {
8618                final int N = pkg.providers.size();
8619                int i;
8620                for (i=0; i<N; i++) {
8621                    PackageParser.Provider p = pkg.providers.get(i);
8622                    if (p.info.authority != null) {
8623                        String names[] = p.info.authority.split(";");
8624                        for (int j = 0; j < names.length; j++) {
8625                            if (mProvidersByAuthority.containsKey(names[j])) {
8626                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8627                                final String otherPackageName =
8628                                        ((other != null && other.getComponentName() != null) ?
8629                                                other.getComponentName().getPackageName() : "?");
8630                                throw new PackageManagerException(
8631                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8632                                        "Can't install because provider name " + names[j]
8633                                                + " (in package " + pkg.applicationInfo.packageName
8634                                                + ") is already used by " + otherPackageName);
8635                            }
8636                        }
8637                    }
8638                }
8639            }
8640        }
8641    }
8642
8643    /**
8644     * Adds a scanned package to the system. When this method is finished, the package will
8645     * be available for query, resolution, etc...
8646     */
8647    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
8648            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
8649        final String pkgName = pkg.packageName;
8650        if (mCustomResolverComponentName != null &&
8651                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8652            setUpCustomResolverActivity(pkg);
8653        }
8654
8655        if (pkg.packageName.equals("android")) {
8656            synchronized (mPackages) {
8657                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8658                    // Set up information for our fall-back user intent resolution activity.
8659                    mPlatformPackage = pkg;
8660                    pkg.mVersionCode = mSdkVersion;
8661                    mAndroidApplication = pkg.applicationInfo;
8662
8663                    if (!mResolverReplaced) {
8664                        mResolveActivity.applicationInfo = mAndroidApplication;
8665                        mResolveActivity.name = ResolverActivity.class.getName();
8666                        mResolveActivity.packageName = mAndroidApplication.packageName;
8667                        mResolveActivity.processName = "system:ui";
8668                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8669                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8670                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8671                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8672                        mResolveActivity.exported = true;
8673                        mResolveActivity.enabled = true;
8674                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8675                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8676                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8677                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8678                                | ActivityInfo.CONFIG_ORIENTATION
8679                                | ActivityInfo.CONFIG_KEYBOARD
8680                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8681                        mResolveInfo.activityInfo = mResolveActivity;
8682                        mResolveInfo.priority = 0;
8683                        mResolveInfo.preferredOrder = 0;
8684                        mResolveInfo.match = 0;
8685                        mResolveComponentName = new ComponentName(
8686                                mAndroidApplication.packageName, mResolveActivity.name);
8687                    }
8688                }
8689            }
8690        }
8691
8692        ArrayList<PackageParser.Package> clientLibPkgs = null;
8693        // writer
8694        synchronized (mPackages) {
8695            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8696                // Only system apps can add new shared libraries.
8697                if (pkg.libraryNames != null) {
8698                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8699                        String name = pkg.libraryNames.get(i);
8700                        boolean allowed = false;
8701                        if (pkg.isUpdatedSystemApp()) {
8702                            // New library entries can only be added through the
8703                            // system image.  This is important to get rid of a lot
8704                            // of nasty edge cases: for example if we allowed a non-
8705                            // system update of the app to add a library, then uninstalling
8706                            // the update would make the library go away, and assumptions
8707                            // we made such as through app install filtering would now
8708                            // have allowed apps on the device which aren't compatible
8709                            // with it.  Better to just have the restriction here, be
8710                            // conservative, and create many fewer cases that can negatively
8711                            // impact the user experience.
8712                            final PackageSetting sysPs = mSettings
8713                                    .getDisabledSystemPkgLPr(pkg.packageName);
8714                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8715                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8716                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8717                                        allowed = true;
8718                                        break;
8719                                    }
8720                                }
8721                            }
8722                        } else {
8723                            allowed = true;
8724                        }
8725                        if (allowed) {
8726                            if (!mSharedLibraries.containsKey(name)) {
8727                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8728                            } else if (!name.equals(pkg.packageName)) {
8729                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8730                                        + name + " already exists; skipping");
8731                            }
8732                        } else {
8733                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8734                                    + name + " that is not declared on system image; skipping");
8735                        }
8736                    }
8737                    if ((scanFlags & SCAN_BOOTING) == 0) {
8738                        // If we are not booting, we need to update any applications
8739                        // that are clients of our shared library.  If we are booting,
8740                        // this will all be done once the scan is complete.
8741                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8742                    }
8743                }
8744            }
8745        }
8746
8747        if ((scanFlags & SCAN_BOOTING) != 0) {
8748            // No apps can run during boot scan, so they don't need to be frozen
8749        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8750            // Caller asked to not kill app, so it's probably not frozen
8751        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8752            // Caller asked us to ignore frozen check for some reason; they
8753            // probably didn't know the package name
8754        } else {
8755            // We're doing major surgery on this package, so it better be frozen
8756            // right now to keep it from launching
8757            checkPackageFrozen(pkgName);
8758        }
8759
8760        // Also need to kill any apps that are dependent on the library.
8761        if (clientLibPkgs != null) {
8762            for (int i=0; i<clientLibPkgs.size(); i++) {
8763                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8764                killApplication(clientPkg.applicationInfo.packageName,
8765                        clientPkg.applicationInfo.uid, "update lib");
8766            }
8767        }
8768
8769        // writer
8770        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8771
8772        boolean createIdmapFailed = false;
8773        synchronized (mPackages) {
8774            // We don't expect installation to fail beyond this point
8775
8776            if (pkgSetting.pkg != null) {
8777                // Note that |user| might be null during the initial boot scan. If a codePath
8778                // for an app has changed during a boot scan, it's due to an app update that's
8779                // part of the system partition and marker changes must be applied to all users.
8780                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
8781                final int[] userIds = resolveUserIds(userId);
8782                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
8783            }
8784
8785            // Add the new setting to mSettings
8786            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8787            // Add the new setting to mPackages
8788            mPackages.put(pkg.applicationInfo.packageName, pkg);
8789            // Make sure we don't accidentally delete its data.
8790            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8791            while (iter.hasNext()) {
8792                PackageCleanItem item = iter.next();
8793                if (pkgName.equals(item.packageName)) {
8794                    iter.remove();
8795                }
8796            }
8797
8798            // Add the package's KeySets to the global KeySetManagerService
8799            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8800            ksms.addScannedPackageLPw(pkg);
8801
8802            int N = pkg.providers.size();
8803            StringBuilder r = null;
8804            int i;
8805            for (i=0; i<N; i++) {
8806                PackageParser.Provider p = pkg.providers.get(i);
8807                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8808                        p.info.processName);
8809                mProviders.addProvider(p);
8810                p.syncable = p.info.isSyncable;
8811                if (p.info.authority != null) {
8812                    String names[] = p.info.authority.split(";");
8813                    p.info.authority = null;
8814                    for (int j = 0; j < names.length; j++) {
8815                        if (j == 1 && p.syncable) {
8816                            // We only want the first authority for a provider to possibly be
8817                            // syncable, so if we already added this provider using a different
8818                            // authority clear the syncable flag. We copy the provider before
8819                            // changing it because the mProviders object contains a reference
8820                            // to a provider that we don't want to change.
8821                            // Only do this for the second authority since the resulting provider
8822                            // object can be the same for all future authorities for this provider.
8823                            p = new PackageParser.Provider(p);
8824                            p.syncable = false;
8825                        }
8826                        if (!mProvidersByAuthority.containsKey(names[j])) {
8827                            mProvidersByAuthority.put(names[j], p);
8828                            if (p.info.authority == null) {
8829                                p.info.authority = names[j];
8830                            } else {
8831                                p.info.authority = p.info.authority + ";" + names[j];
8832                            }
8833                            if (DEBUG_PACKAGE_SCANNING) {
8834                                if (chatty)
8835                                    Log.d(TAG, "Registered content provider: " + names[j]
8836                                            + ", className = " + p.info.name + ", isSyncable = "
8837                                            + p.info.isSyncable);
8838                            }
8839                        } else {
8840                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8841                            Slog.w(TAG, "Skipping provider name " + names[j] +
8842                                    " (in package " + pkg.applicationInfo.packageName +
8843                                    "): name already used by "
8844                                    + ((other != null && other.getComponentName() != null)
8845                                            ? other.getComponentName().getPackageName() : "?"));
8846                        }
8847                    }
8848                }
8849                if (chatty) {
8850                    if (r == null) {
8851                        r = new StringBuilder(256);
8852                    } else {
8853                        r.append(' ');
8854                    }
8855                    r.append(p.info.name);
8856                }
8857            }
8858            if (r != null) {
8859                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8860            }
8861
8862            N = pkg.services.size();
8863            r = null;
8864            for (i=0; i<N; i++) {
8865                PackageParser.Service s = pkg.services.get(i);
8866                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8867                        s.info.processName);
8868                mServices.addService(s);
8869                if (chatty) {
8870                    if (r == null) {
8871                        r = new StringBuilder(256);
8872                    } else {
8873                        r.append(' ');
8874                    }
8875                    r.append(s.info.name);
8876                }
8877            }
8878            if (r != null) {
8879                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8880            }
8881
8882            N = pkg.receivers.size();
8883            r = null;
8884            for (i=0; i<N; i++) {
8885                PackageParser.Activity a = pkg.receivers.get(i);
8886                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8887                        a.info.processName);
8888                mReceivers.addActivity(a, "receiver");
8889                if (chatty) {
8890                    if (r == null) {
8891                        r = new StringBuilder(256);
8892                    } else {
8893                        r.append(' ');
8894                    }
8895                    r.append(a.info.name);
8896                }
8897            }
8898            if (r != null) {
8899                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8900            }
8901
8902            N = pkg.activities.size();
8903            r = null;
8904            for (i=0; i<N; i++) {
8905                PackageParser.Activity a = pkg.activities.get(i);
8906                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8907                        a.info.processName);
8908                mActivities.addActivity(a, "activity");
8909                if (chatty) {
8910                    if (r == null) {
8911                        r = new StringBuilder(256);
8912                    } else {
8913                        r.append(' ');
8914                    }
8915                    r.append(a.info.name);
8916                }
8917            }
8918            if (r != null) {
8919                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8920            }
8921
8922            N = pkg.permissionGroups.size();
8923            r = null;
8924            for (i=0; i<N; i++) {
8925                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8926                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8927                final String curPackageName = cur == null ? null : cur.info.packageName;
8928                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8929                if (cur == null || isPackageUpdate) {
8930                    mPermissionGroups.put(pg.info.name, pg);
8931                    if (chatty) {
8932                        if (r == null) {
8933                            r = new StringBuilder(256);
8934                        } else {
8935                            r.append(' ');
8936                        }
8937                        if (isPackageUpdate) {
8938                            r.append("UPD:");
8939                        }
8940                        r.append(pg.info.name);
8941                    }
8942                } else {
8943                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8944                            + pg.info.packageName + " ignored: original from "
8945                            + cur.info.packageName);
8946                    if (chatty) {
8947                        if (r == null) {
8948                            r = new StringBuilder(256);
8949                        } else {
8950                            r.append(' ');
8951                        }
8952                        r.append("DUP:");
8953                        r.append(pg.info.name);
8954                    }
8955                }
8956            }
8957            if (r != null) {
8958                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8959            }
8960
8961            N = pkg.permissions.size();
8962            r = null;
8963            for (i=0; i<N; i++) {
8964                PackageParser.Permission p = pkg.permissions.get(i);
8965
8966                // Assume by default that we did not install this permission into the system.
8967                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8968
8969                // Now that permission groups have a special meaning, we ignore permission
8970                // groups for legacy apps to prevent unexpected behavior. In particular,
8971                // permissions for one app being granted to someone just becase they happen
8972                // to be in a group defined by another app (before this had no implications).
8973                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8974                    p.group = mPermissionGroups.get(p.info.group);
8975                    // Warn for a permission in an unknown group.
8976                    if (p.info.group != null && p.group == null) {
8977                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8978                                + p.info.packageName + " in an unknown group " + p.info.group);
8979                    }
8980                }
8981
8982                ArrayMap<String, BasePermission> permissionMap =
8983                        p.tree ? mSettings.mPermissionTrees
8984                                : mSettings.mPermissions;
8985                BasePermission bp = permissionMap.get(p.info.name);
8986
8987                // Allow system apps to redefine non-system permissions
8988                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8989                    final boolean currentOwnerIsSystem = (bp.perm != null
8990                            && isSystemApp(bp.perm.owner));
8991                    if (isSystemApp(p.owner)) {
8992                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8993                            // It's a built-in permission and no owner, take ownership now
8994                            bp.packageSetting = pkgSetting;
8995                            bp.perm = p;
8996                            bp.uid = pkg.applicationInfo.uid;
8997                            bp.sourcePackage = p.info.packageName;
8998                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8999                        } else if (!currentOwnerIsSystem) {
9000                            String msg = "New decl " + p.owner + " of permission  "
9001                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
9002                            reportSettingsProblem(Log.WARN, msg);
9003                            bp = null;
9004                        }
9005                    }
9006                }
9007
9008                if (bp == null) {
9009                    bp = new BasePermission(p.info.name, p.info.packageName,
9010                            BasePermission.TYPE_NORMAL);
9011                    permissionMap.put(p.info.name, bp);
9012                }
9013
9014                if (bp.perm == null) {
9015                    if (bp.sourcePackage == null
9016                            || bp.sourcePackage.equals(p.info.packageName)) {
9017                        BasePermission tree = findPermissionTreeLP(p.info.name);
9018                        if (tree == null
9019                                || tree.sourcePackage.equals(p.info.packageName)) {
9020                            bp.packageSetting = pkgSetting;
9021                            bp.perm = p;
9022                            bp.uid = pkg.applicationInfo.uid;
9023                            bp.sourcePackage = p.info.packageName;
9024                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
9025                            if (chatty) {
9026                                if (r == null) {
9027                                    r = new StringBuilder(256);
9028                                } else {
9029                                    r.append(' ');
9030                                }
9031                                r.append(p.info.name);
9032                            }
9033                        } else {
9034                            Slog.w(TAG, "Permission " + p.info.name + " from package "
9035                                    + p.info.packageName + " ignored: base tree "
9036                                    + tree.name + " is from package "
9037                                    + tree.sourcePackage);
9038                        }
9039                    } else {
9040                        Slog.w(TAG, "Permission " + p.info.name + " from package "
9041                                + p.info.packageName + " ignored: original from "
9042                                + bp.sourcePackage);
9043                    }
9044                } else if (chatty) {
9045                    if (r == null) {
9046                        r = new StringBuilder(256);
9047                    } else {
9048                        r.append(' ');
9049                    }
9050                    r.append("DUP:");
9051                    r.append(p.info.name);
9052                }
9053                if (bp.perm == p) {
9054                    bp.protectionLevel = p.info.protectionLevel;
9055                }
9056            }
9057
9058            if (r != null) {
9059                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
9060            }
9061
9062            N = pkg.instrumentation.size();
9063            r = null;
9064            for (i=0; i<N; i++) {
9065                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9066                a.info.packageName = pkg.applicationInfo.packageName;
9067                a.info.sourceDir = pkg.applicationInfo.sourceDir;
9068                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
9069                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
9070                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
9071                a.info.dataDir = pkg.applicationInfo.dataDir;
9072                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
9073                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
9074                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
9075                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
9076                mInstrumentation.put(a.getComponentName(), a);
9077                if (chatty) {
9078                    if (r == null) {
9079                        r = new StringBuilder(256);
9080                    } else {
9081                        r.append(' ');
9082                    }
9083                    r.append(a.info.name);
9084                }
9085            }
9086            if (r != null) {
9087                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
9088            }
9089
9090            if (pkg.protectedBroadcasts != null) {
9091                N = pkg.protectedBroadcasts.size();
9092                for (i=0; i<N; i++) {
9093                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
9094                }
9095            }
9096
9097            // Create idmap files for pairs of (packages, overlay packages).
9098            // Note: "android", ie framework-res.apk, is handled by native layers.
9099            if (pkg.mOverlayTarget != null) {
9100                // This is an overlay package.
9101                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9102                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9103                        mOverlays.put(pkg.mOverlayTarget,
9104                                new ArrayMap<String, PackageParser.Package>());
9105                    }
9106                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9107                    map.put(pkg.packageName, pkg);
9108                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9109                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9110                        createIdmapFailed = true;
9111                    }
9112                }
9113            } else if (mOverlays.containsKey(pkg.packageName) &&
9114                    !pkg.packageName.equals("android")) {
9115                // This is a regular package, with one or more known overlay packages.
9116                createIdmapsForPackageLI(pkg);
9117            }
9118        }
9119
9120        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9121
9122        if (createIdmapFailed) {
9123            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9124                    "scanPackageLI failed to createIdmap");
9125        }
9126    }
9127
9128    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9129            PackageParser.Package update, int[] userIds) {
9130        if (existing.applicationInfo == null || update.applicationInfo == null) {
9131            // This isn't due to an app installation.
9132            return;
9133        }
9134
9135        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9136        final File newCodePath = new File(update.applicationInfo.getCodePath());
9137
9138        // The codePath hasn't changed, so there's nothing for us to do.
9139        if (Objects.equals(oldCodePath, newCodePath)) {
9140            return;
9141        }
9142
9143        File canonicalNewCodePath;
9144        try {
9145            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9146        } catch (IOException e) {
9147            Slog.w(TAG, "Failed to get canonical path.", e);
9148            return;
9149        }
9150
9151        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9152        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9153        // that the last component of the path (i.e, the name) doesn't need canonicalization
9154        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9155        // but may change in the future. Hopefully this function won't exist at that point.
9156        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9157                oldCodePath.getName());
9158
9159        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9160        // with "@".
9161        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9162        if (!oldMarkerPrefix.endsWith("@")) {
9163            oldMarkerPrefix += "@";
9164        }
9165        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9166        if (!newMarkerPrefix.endsWith("@")) {
9167            newMarkerPrefix += "@";
9168        }
9169
9170        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9171        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9172        for (String updatedPath : updatedPaths) {
9173            String updatedPathName = new File(updatedPath).getName();
9174            markerSuffixes.add(updatedPathName.replace('/', '@'));
9175        }
9176
9177        for (int userId : userIds) {
9178            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9179
9180            for (String markerSuffix : markerSuffixes) {
9181                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9182                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9183                if (oldForeignUseMark.exists()) {
9184                    try {
9185                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9186                                newForeignUseMark.getAbsolutePath());
9187                    } catch (ErrnoException e) {
9188                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9189                        oldForeignUseMark.delete();
9190                    }
9191                }
9192            }
9193        }
9194    }
9195
9196    /**
9197     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9198     * is derived purely on the basis of the contents of {@code scanFile} and
9199     * {@code cpuAbiOverride}.
9200     *
9201     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9202     */
9203    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9204                                 String cpuAbiOverride, boolean extractLibs,
9205                                 File appLib32InstallDir)
9206            throws PackageManagerException {
9207        // TODO: We can probably be smarter about this stuff. For installed apps,
9208        // we can calculate this information at install time once and for all. For
9209        // system apps, we can probably assume that this information doesn't change
9210        // after the first boot scan. As things stand, we do lots of unnecessary work.
9211
9212        // Give ourselves some initial paths; we'll come back for another
9213        // pass once we've determined ABI below.
9214        setNativeLibraryPaths(pkg, appLib32InstallDir);
9215
9216        // We would never need to extract libs for forward-locked and external packages,
9217        // since the container service will do it for us. We shouldn't attempt to
9218        // extract libs from system app when it was not updated.
9219        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9220                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9221            extractLibs = false;
9222        }
9223
9224        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9225        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9226
9227        NativeLibraryHelper.Handle handle = null;
9228        try {
9229            handle = NativeLibraryHelper.Handle.create(pkg);
9230            // TODO(multiArch): This can be null for apps that didn't go through the
9231            // usual installation process. We can calculate it again, like we
9232            // do during install time.
9233            //
9234            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9235            // unnecessary.
9236            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9237
9238            // Null out the abis so that they can be recalculated.
9239            pkg.applicationInfo.primaryCpuAbi = null;
9240            pkg.applicationInfo.secondaryCpuAbi = null;
9241            if (isMultiArch(pkg.applicationInfo)) {
9242                // Warn if we've set an abiOverride for multi-lib packages..
9243                // By definition, we need to copy both 32 and 64 bit libraries for
9244                // such packages.
9245                if (pkg.cpuAbiOverride != null
9246                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9247                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9248                }
9249
9250                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9251                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9252                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9253                    if (extractLibs) {
9254                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9255                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9256                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9257                                useIsaSpecificSubdirs);
9258                    } else {
9259                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9260                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9261                    }
9262                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9263                }
9264
9265                maybeThrowExceptionForMultiArchCopy(
9266                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9267
9268                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9269                    if (extractLibs) {
9270                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9271                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9272                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9273                                useIsaSpecificSubdirs);
9274                    } else {
9275                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9276                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9277                    }
9278                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9279                }
9280
9281                maybeThrowExceptionForMultiArchCopy(
9282                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9283
9284                if (abi64 >= 0) {
9285                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9286                }
9287
9288                if (abi32 >= 0) {
9289                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9290                    if (abi64 >= 0) {
9291                        if (pkg.use32bitAbi) {
9292                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9293                            pkg.applicationInfo.primaryCpuAbi = abi;
9294                        } else {
9295                            pkg.applicationInfo.secondaryCpuAbi = abi;
9296                        }
9297                    } else {
9298                        pkg.applicationInfo.primaryCpuAbi = abi;
9299                    }
9300                }
9301
9302            } else {
9303                String[] abiList = (cpuAbiOverride != null) ?
9304                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9305
9306                // Enable gross and lame hacks for apps that are built with old
9307                // SDK tools. We must scan their APKs for renderscript bitcode and
9308                // not launch them if it's present. Don't bother checking on devices
9309                // that don't have 64 bit support.
9310                boolean needsRenderScriptOverride = false;
9311                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9312                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9313                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9314                    needsRenderScriptOverride = true;
9315                }
9316
9317                final int copyRet;
9318                if (extractLibs) {
9319                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9320                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9321                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9322                } else {
9323                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9324                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9325                }
9326                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9327
9328                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9329                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9330                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9331                }
9332
9333                if (copyRet >= 0) {
9334                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9335                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9336                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9337                } else if (needsRenderScriptOverride) {
9338                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9339                }
9340            }
9341        } catch (IOException ioe) {
9342            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9343        } finally {
9344            IoUtils.closeQuietly(handle);
9345        }
9346
9347        // Now that we've calculated the ABIs and determined if it's an internal app,
9348        // we will go ahead and populate the nativeLibraryPath.
9349        setNativeLibraryPaths(pkg, appLib32InstallDir);
9350    }
9351
9352    /**
9353     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9354     * i.e, so that all packages can be run inside a single process if required.
9355     *
9356     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9357     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9358     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9359     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9360     * updating a package that belongs to a shared user.
9361     *
9362     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9363     * adds unnecessary complexity.
9364     */
9365    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9366            PackageParser.Package scannedPackage) {
9367        String requiredInstructionSet = null;
9368        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9369            requiredInstructionSet = VMRuntime.getInstructionSet(
9370                     scannedPackage.applicationInfo.primaryCpuAbi);
9371        }
9372
9373        PackageSetting requirer = null;
9374        for (PackageSetting ps : packagesForUser) {
9375            // If packagesForUser contains scannedPackage, we skip it. This will happen
9376            // when scannedPackage is an update of an existing package. Without this check,
9377            // we will never be able to change the ABI of any package belonging to a shared
9378            // user, even if it's compatible with other packages.
9379            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9380                if (ps.primaryCpuAbiString == null) {
9381                    continue;
9382                }
9383
9384                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9385                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9386                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9387                    // this but there's not much we can do.
9388                    String errorMessage = "Instruction set mismatch, "
9389                            + ((requirer == null) ? "[caller]" : requirer)
9390                            + " requires " + requiredInstructionSet + " whereas " + ps
9391                            + " requires " + instructionSet;
9392                    Slog.w(TAG, errorMessage);
9393                }
9394
9395                if (requiredInstructionSet == null) {
9396                    requiredInstructionSet = instructionSet;
9397                    requirer = ps;
9398                }
9399            }
9400        }
9401
9402        if (requiredInstructionSet != null) {
9403            String adjustedAbi;
9404            if (requirer != null) {
9405                // requirer != null implies that either scannedPackage was null or that scannedPackage
9406                // did not require an ABI, in which case we have to adjust scannedPackage to match
9407                // the ABI of the set (which is the same as requirer's ABI)
9408                adjustedAbi = requirer.primaryCpuAbiString;
9409                if (scannedPackage != null) {
9410                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9411                }
9412            } else {
9413                // requirer == null implies that we're updating all ABIs in the set to
9414                // match scannedPackage.
9415                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9416            }
9417
9418            for (PackageSetting ps : packagesForUser) {
9419                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9420                    if (ps.primaryCpuAbiString != null) {
9421                        continue;
9422                    }
9423
9424                    ps.primaryCpuAbiString = adjustedAbi;
9425                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9426                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9427                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9428                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9429                                + " (requirer="
9430                                + (requirer == null ? "null" : requirer.pkg.packageName)
9431                                + ", scannedPackage="
9432                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9433                                + ")");
9434                        try {
9435                            mInstaller.rmdex(ps.codePathString,
9436                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9437                        } catch (InstallerException ignored) {
9438                        }
9439                    }
9440                }
9441            }
9442        }
9443    }
9444
9445    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9446        synchronized (mPackages) {
9447            mResolverReplaced = true;
9448            // Set up information for custom user intent resolution activity.
9449            mResolveActivity.applicationInfo = pkg.applicationInfo;
9450            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9451            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9452            mResolveActivity.processName = pkg.applicationInfo.packageName;
9453            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9454            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9455                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9456            mResolveActivity.theme = 0;
9457            mResolveActivity.exported = true;
9458            mResolveActivity.enabled = true;
9459            mResolveInfo.activityInfo = mResolveActivity;
9460            mResolveInfo.priority = 0;
9461            mResolveInfo.preferredOrder = 0;
9462            mResolveInfo.match = 0;
9463            mResolveComponentName = mCustomResolverComponentName;
9464            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9465                    mResolveComponentName);
9466        }
9467    }
9468
9469    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9470        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9471
9472        // Set up information for ephemeral installer activity
9473        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9474        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9475        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9476        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9477        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9478        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9479                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9480        mEphemeralInstallerActivity.theme = 0;
9481        mEphemeralInstallerActivity.exported = true;
9482        mEphemeralInstallerActivity.enabled = true;
9483        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9484        mEphemeralInstallerInfo.priority = 0;
9485        mEphemeralInstallerInfo.preferredOrder = 1;
9486        mEphemeralInstallerInfo.isDefault = true;
9487        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9488                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9489
9490        if (DEBUG_EPHEMERAL) {
9491            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9492        }
9493    }
9494
9495    private static String calculateBundledApkRoot(final String codePathString) {
9496        final File codePath = new File(codePathString);
9497        final File codeRoot;
9498        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9499            codeRoot = Environment.getRootDirectory();
9500        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9501            codeRoot = Environment.getOemDirectory();
9502        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9503            codeRoot = Environment.getVendorDirectory();
9504        } else {
9505            // Unrecognized code path; take its top real segment as the apk root:
9506            // e.g. /something/app/blah.apk => /something
9507            try {
9508                File f = codePath.getCanonicalFile();
9509                File parent = f.getParentFile();    // non-null because codePath is a file
9510                File tmp;
9511                while ((tmp = parent.getParentFile()) != null) {
9512                    f = parent;
9513                    parent = tmp;
9514                }
9515                codeRoot = f;
9516                Slog.w(TAG, "Unrecognized code path "
9517                        + codePath + " - using " + codeRoot);
9518            } catch (IOException e) {
9519                // Can't canonicalize the code path -- shenanigans?
9520                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9521                return Environment.getRootDirectory().getPath();
9522            }
9523        }
9524        return codeRoot.getPath();
9525    }
9526
9527    /**
9528     * Derive and set the location of native libraries for the given package,
9529     * which varies depending on where and how the package was installed.
9530     */
9531    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
9532        final ApplicationInfo info = pkg.applicationInfo;
9533        final String codePath = pkg.codePath;
9534        final File codeFile = new File(codePath);
9535        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9536        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9537
9538        info.nativeLibraryRootDir = null;
9539        info.nativeLibraryRootRequiresIsa = false;
9540        info.nativeLibraryDir = null;
9541        info.secondaryNativeLibraryDir = null;
9542
9543        if (isApkFile(codeFile)) {
9544            // Monolithic install
9545            if (bundledApp) {
9546                // If "/system/lib64/apkname" exists, assume that is the per-package
9547                // native library directory to use; otherwise use "/system/lib/apkname".
9548                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9549                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9550                        getPrimaryInstructionSet(info));
9551
9552                // This is a bundled system app so choose the path based on the ABI.
9553                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9554                // is just the default path.
9555                final String apkName = deriveCodePathName(codePath);
9556                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9557                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9558                        apkName).getAbsolutePath();
9559
9560                if (info.secondaryCpuAbi != null) {
9561                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9562                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9563                            secondaryLibDir, apkName).getAbsolutePath();
9564                }
9565            } else if (asecApp) {
9566                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9567                        .getAbsolutePath();
9568            } else {
9569                final String apkName = deriveCodePathName(codePath);
9570                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
9571                        .getAbsolutePath();
9572            }
9573
9574            info.nativeLibraryRootRequiresIsa = false;
9575            info.nativeLibraryDir = info.nativeLibraryRootDir;
9576        } else {
9577            // Cluster install
9578            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9579            info.nativeLibraryRootRequiresIsa = true;
9580
9581            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9582                    getPrimaryInstructionSet(info)).getAbsolutePath();
9583
9584            if (info.secondaryCpuAbi != null) {
9585                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9586                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9587            }
9588        }
9589    }
9590
9591    /**
9592     * Calculate the abis and roots for a bundled app. These can uniquely
9593     * be determined from the contents of the system partition, i.e whether
9594     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9595     * of this information, and instead assume that the system was built
9596     * sensibly.
9597     */
9598    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9599                                           PackageSetting pkgSetting) {
9600        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9601
9602        // If "/system/lib64/apkname" exists, assume that is the per-package
9603        // native library directory to use; otherwise use "/system/lib/apkname".
9604        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9605        setBundledAppAbi(pkg, apkRoot, apkName);
9606        // pkgSetting might be null during rescan following uninstall of updates
9607        // to a bundled app, so accommodate that possibility.  The settings in
9608        // that case will be established later from the parsed package.
9609        //
9610        // If the settings aren't null, sync them up with what we've just derived.
9611        // note that apkRoot isn't stored in the package settings.
9612        if (pkgSetting != null) {
9613            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9614            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9615        }
9616    }
9617
9618    /**
9619     * Deduces the ABI of a bundled app and sets the relevant fields on the
9620     * parsed pkg object.
9621     *
9622     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9623     *        under which system libraries are installed.
9624     * @param apkName the name of the installed package.
9625     */
9626    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9627        final File codeFile = new File(pkg.codePath);
9628
9629        final boolean has64BitLibs;
9630        final boolean has32BitLibs;
9631        if (isApkFile(codeFile)) {
9632            // Monolithic install
9633            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9634            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9635        } else {
9636            // Cluster install
9637            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9638            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9639                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9640                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9641                has64BitLibs = (new File(rootDir, isa)).exists();
9642            } else {
9643                has64BitLibs = false;
9644            }
9645            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9646                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9647                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9648                has32BitLibs = (new File(rootDir, isa)).exists();
9649            } else {
9650                has32BitLibs = false;
9651            }
9652        }
9653
9654        if (has64BitLibs && !has32BitLibs) {
9655            // The package has 64 bit libs, but not 32 bit libs. Its primary
9656            // ABI should be 64 bit. We can safely assume here that the bundled
9657            // native libraries correspond to the most preferred ABI in the list.
9658
9659            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9660            pkg.applicationInfo.secondaryCpuAbi = null;
9661        } else if (has32BitLibs && !has64BitLibs) {
9662            // The package has 32 bit libs but not 64 bit libs. Its primary
9663            // ABI should be 32 bit.
9664
9665            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9666            pkg.applicationInfo.secondaryCpuAbi = null;
9667        } else if (has32BitLibs && has64BitLibs) {
9668            // The application has both 64 and 32 bit bundled libraries. We check
9669            // here that the app declares multiArch support, and warn if it doesn't.
9670            //
9671            // We will be lenient here and record both ABIs. The primary will be the
9672            // ABI that's higher on the list, i.e, a device that's configured to prefer
9673            // 64 bit apps will see a 64 bit primary ABI,
9674
9675            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9676                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9677            }
9678
9679            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9680                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9681                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9682            } else {
9683                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9684                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9685            }
9686        } else {
9687            pkg.applicationInfo.primaryCpuAbi = null;
9688            pkg.applicationInfo.secondaryCpuAbi = null;
9689        }
9690    }
9691
9692    private void killApplication(String pkgName, int appId, String reason) {
9693        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9694    }
9695
9696    private void killApplication(String pkgName, int appId, int userId, String reason) {
9697        // Request the ActivityManager to kill the process(only for existing packages)
9698        // so that we do not end up in a confused state while the user is still using the older
9699        // version of the application while the new one gets installed.
9700        final long token = Binder.clearCallingIdentity();
9701        try {
9702            IActivityManager am = ActivityManager.getService();
9703            if (am != null) {
9704                try {
9705                    am.killApplication(pkgName, appId, userId, reason);
9706                } catch (RemoteException e) {
9707                }
9708            }
9709        } finally {
9710            Binder.restoreCallingIdentity(token);
9711        }
9712    }
9713
9714    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9715        // Remove the parent package setting
9716        PackageSetting ps = (PackageSetting) pkg.mExtras;
9717        if (ps != null) {
9718            removePackageLI(ps, chatty);
9719        }
9720        // Remove the child package setting
9721        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9722        for (int i = 0; i < childCount; i++) {
9723            PackageParser.Package childPkg = pkg.childPackages.get(i);
9724            ps = (PackageSetting) childPkg.mExtras;
9725            if (ps != null) {
9726                removePackageLI(ps, chatty);
9727            }
9728        }
9729    }
9730
9731    void removePackageLI(PackageSetting ps, boolean chatty) {
9732        if (DEBUG_INSTALL) {
9733            if (chatty)
9734                Log.d(TAG, "Removing package " + ps.name);
9735        }
9736
9737        // writer
9738        synchronized (mPackages) {
9739            mPackages.remove(ps.name);
9740            final PackageParser.Package pkg = ps.pkg;
9741            if (pkg != null) {
9742                cleanPackageDataStructuresLILPw(pkg, chatty);
9743            }
9744        }
9745    }
9746
9747    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9748        if (DEBUG_INSTALL) {
9749            if (chatty)
9750                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9751        }
9752
9753        // writer
9754        synchronized (mPackages) {
9755            // Remove the parent package
9756            mPackages.remove(pkg.applicationInfo.packageName);
9757            cleanPackageDataStructuresLILPw(pkg, chatty);
9758
9759            // Remove the child packages
9760            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9761            for (int i = 0; i < childCount; i++) {
9762                PackageParser.Package childPkg = pkg.childPackages.get(i);
9763                mPackages.remove(childPkg.applicationInfo.packageName);
9764                cleanPackageDataStructuresLILPw(childPkg, chatty);
9765            }
9766        }
9767    }
9768
9769    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9770        int N = pkg.providers.size();
9771        StringBuilder r = null;
9772        int i;
9773        for (i=0; i<N; i++) {
9774            PackageParser.Provider p = pkg.providers.get(i);
9775            mProviders.removeProvider(p);
9776            if (p.info.authority == null) {
9777
9778                /* There was another ContentProvider with this authority when
9779                 * this app was installed so this authority is null,
9780                 * Ignore it as we don't have to unregister the provider.
9781                 */
9782                continue;
9783            }
9784            String names[] = p.info.authority.split(";");
9785            for (int j = 0; j < names.length; j++) {
9786                if (mProvidersByAuthority.get(names[j]) == p) {
9787                    mProvidersByAuthority.remove(names[j]);
9788                    if (DEBUG_REMOVE) {
9789                        if (chatty)
9790                            Log.d(TAG, "Unregistered content provider: " + names[j]
9791                                    + ", className = " + p.info.name + ", isSyncable = "
9792                                    + p.info.isSyncable);
9793                    }
9794                }
9795            }
9796            if (DEBUG_REMOVE && chatty) {
9797                if (r == null) {
9798                    r = new StringBuilder(256);
9799                } else {
9800                    r.append(' ');
9801                }
9802                r.append(p.info.name);
9803            }
9804        }
9805        if (r != null) {
9806            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9807        }
9808
9809        N = pkg.services.size();
9810        r = null;
9811        for (i=0; i<N; i++) {
9812            PackageParser.Service s = pkg.services.get(i);
9813            mServices.removeService(s);
9814            if (chatty) {
9815                if (r == null) {
9816                    r = new StringBuilder(256);
9817                } else {
9818                    r.append(' ');
9819                }
9820                r.append(s.info.name);
9821            }
9822        }
9823        if (r != null) {
9824            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9825        }
9826
9827        N = pkg.receivers.size();
9828        r = null;
9829        for (i=0; i<N; i++) {
9830            PackageParser.Activity a = pkg.receivers.get(i);
9831            mReceivers.removeActivity(a, "receiver");
9832            if (DEBUG_REMOVE && chatty) {
9833                if (r == null) {
9834                    r = new StringBuilder(256);
9835                } else {
9836                    r.append(' ');
9837                }
9838                r.append(a.info.name);
9839            }
9840        }
9841        if (r != null) {
9842            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9843        }
9844
9845        N = pkg.activities.size();
9846        r = null;
9847        for (i=0; i<N; i++) {
9848            PackageParser.Activity a = pkg.activities.get(i);
9849            mActivities.removeActivity(a, "activity");
9850            if (DEBUG_REMOVE && chatty) {
9851                if (r == null) {
9852                    r = new StringBuilder(256);
9853                } else {
9854                    r.append(' ');
9855                }
9856                r.append(a.info.name);
9857            }
9858        }
9859        if (r != null) {
9860            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9861        }
9862
9863        N = pkg.permissions.size();
9864        r = null;
9865        for (i=0; i<N; i++) {
9866            PackageParser.Permission p = pkg.permissions.get(i);
9867            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9868            if (bp == null) {
9869                bp = mSettings.mPermissionTrees.get(p.info.name);
9870            }
9871            if (bp != null && bp.perm == p) {
9872                bp.perm = null;
9873                if (DEBUG_REMOVE && chatty) {
9874                    if (r == null) {
9875                        r = new StringBuilder(256);
9876                    } else {
9877                        r.append(' ');
9878                    }
9879                    r.append(p.info.name);
9880                }
9881            }
9882            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9883                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9884                if (appOpPkgs != null) {
9885                    appOpPkgs.remove(pkg.packageName);
9886                }
9887            }
9888        }
9889        if (r != null) {
9890            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9891        }
9892
9893        N = pkg.requestedPermissions.size();
9894        r = null;
9895        for (i=0; i<N; i++) {
9896            String perm = pkg.requestedPermissions.get(i);
9897            BasePermission bp = mSettings.mPermissions.get(perm);
9898            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9899                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9900                if (appOpPkgs != null) {
9901                    appOpPkgs.remove(pkg.packageName);
9902                    if (appOpPkgs.isEmpty()) {
9903                        mAppOpPermissionPackages.remove(perm);
9904                    }
9905                }
9906            }
9907        }
9908        if (r != null) {
9909            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9910        }
9911
9912        N = pkg.instrumentation.size();
9913        r = null;
9914        for (i=0; i<N; i++) {
9915            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9916            mInstrumentation.remove(a.getComponentName());
9917            if (DEBUG_REMOVE && chatty) {
9918                if (r == null) {
9919                    r = new StringBuilder(256);
9920                } else {
9921                    r.append(' ');
9922                }
9923                r.append(a.info.name);
9924            }
9925        }
9926        if (r != null) {
9927            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9928        }
9929
9930        r = null;
9931        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9932            // Only system apps can hold shared libraries.
9933            if (pkg.libraryNames != null) {
9934                for (i=0; i<pkg.libraryNames.size(); i++) {
9935                    String name = pkg.libraryNames.get(i);
9936                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9937                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9938                        mSharedLibraries.remove(name);
9939                        if (DEBUG_REMOVE && chatty) {
9940                            if (r == null) {
9941                                r = new StringBuilder(256);
9942                            } else {
9943                                r.append(' ');
9944                            }
9945                            r.append(name);
9946                        }
9947                    }
9948                }
9949            }
9950        }
9951        if (r != null) {
9952            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9953        }
9954    }
9955
9956    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9957        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9958            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9959                return true;
9960            }
9961        }
9962        return false;
9963    }
9964
9965    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9966    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9967    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9968
9969    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9970        // Update the parent permissions
9971        updatePermissionsLPw(pkg.packageName, pkg, flags);
9972        // Update the child permissions
9973        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9974        for (int i = 0; i < childCount; i++) {
9975            PackageParser.Package childPkg = pkg.childPackages.get(i);
9976            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9977        }
9978    }
9979
9980    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9981            int flags) {
9982        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9983        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9984    }
9985
9986    private void updatePermissionsLPw(String changingPkg,
9987            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9988        // Make sure there are no dangling permission trees.
9989        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9990        while (it.hasNext()) {
9991            final BasePermission bp = it.next();
9992            if (bp.packageSetting == null) {
9993                // We may not yet have parsed the package, so just see if
9994                // we still know about its settings.
9995                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9996            }
9997            if (bp.packageSetting == null) {
9998                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9999                        + " from package " + bp.sourcePackage);
10000                it.remove();
10001            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10002                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10003                    Slog.i(TAG, "Removing old permission tree: " + bp.name
10004                            + " from package " + bp.sourcePackage);
10005                    flags |= UPDATE_PERMISSIONS_ALL;
10006                    it.remove();
10007                }
10008            }
10009        }
10010
10011        // Make sure all dynamic permissions have been assigned to a package,
10012        // and make sure there are no dangling permissions.
10013        it = mSettings.mPermissions.values().iterator();
10014        while (it.hasNext()) {
10015            final BasePermission bp = it.next();
10016            if (bp.type == BasePermission.TYPE_DYNAMIC) {
10017                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
10018                        + bp.name + " pkg=" + bp.sourcePackage
10019                        + " info=" + bp.pendingInfo);
10020                if (bp.packageSetting == null && bp.pendingInfo != null) {
10021                    final BasePermission tree = findPermissionTreeLP(bp.name);
10022                    if (tree != null && tree.perm != null) {
10023                        bp.packageSetting = tree.packageSetting;
10024                        bp.perm = new PackageParser.Permission(tree.perm.owner,
10025                                new PermissionInfo(bp.pendingInfo));
10026                        bp.perm.info.packageName = tree.perm.info.packageName;
10027                        bp.perm.info.name = bp.name;
10028                        bp.uid = tree.uid;
10029                    }
10030                }
10031            }
10032            if (bp.packageSetting == null) {
10033                // We may not yet have parsed the package, so just see if
10034                // we still know about its settings.
10035                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10036            }
10037            if (bp.packageSetting == null) {
10038                Slog.w(TAG, "Removing dangling permission: " + bp.name
10039                        + " from package " + bp.sourcePackage);
10040                it.remove();
10041            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10042                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10043                    Slog.i(TAG, "Removing old permission: " + bp.name
10044                            + " from package " + bp.sourcePackage);
10045                    flags |= UPDATE_PERMISSIONS_ALL;
10046                    it.remove();
10047                }
10048            }
10049        }
10050
10051        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
10052        // Now update the permissions for all packages, in particular
10053        // replace the granted permissions of the system packages.
10054        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
10055            for (PackageParser.Package pkg : mPackages.values()) {
10056                if (pkg != pkgInfo) {
10057                    // Only replace for packages on requested volume
10058                    final String volumeUuid = getVolumeUuidForPackage(pkg);
10059                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
10060                            && Objects.equals(replaceVolumeUuid, volumeUuid);
10061                    grantPermissionsLPw(pkg, replace, changingPkg);
10062                }
10063            }
10064        }
10065
10066        if (pkgInfo != null) {
10067            // Only replace for packages on requested volume
10068            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
10069            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
10070                    && Objects.equals(replaceVolumeUuid, volumeUuid);
10071            grantPermissionsLPw(pkgInfo, replace, changingPkg);
10072        }
10073        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10074    }
10075
10076    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
10077            String packageOfInterest) {
10078        // IMPORTANT: There are two types of permissions: install and runtime.
10079        // Install time permissions are granted when the app is installed to
10080        // all device users and users added in the future. Runtime permissions
10081        // are granted at runtime explicitly to specific users. Normal and signature
10082        // protected permissions are install time permissions. Dangerous permissions
10083        // are install permissions if the app's target SDK is Lollipop MR1 or older,
10084        // otherwise they are runtime permissions. This function does not manage
10085        // runtime permissions except for the case an app targeting Lollipop MR1
10086        // being upgraded to target a newer SDK, in which case dangerous permissions
10087        // are transformed from install time to runtime ones.
10088
10089        final PackageSetting ps = (PackageSetting) pkg.mExtras;
10090        if (ps == null) {
10091            return;
10092        }
10093
10094        PermissionsState permissionsState = ps.getPermissionsState();
10095        PermissionsState origPermissions = permissionsState;
10096
10097        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
10098
10099        boolean runtimePermissionsRevoked = false;
10100        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
10101
10102        boolean changedInstallPermission = false;
10103
10104        if (replace) {
10105            ps.installPermissionsFixed = false;
10106            if (!ps.isSharedUser()) {
10107                origPermissions = new PermissionsState(permissionsState);
10108                permissionsState.reset();
10109            } else {
10110                // We need to know only about runtime permission changes since the
10111                // calling code always writes the install permissions state but
10112                // the runtime ones are written only if changed. The only cases of
10113                // changed runtime permissions here are promotion of an install to
10114                // runtime and revocation of a runtime from a shared user.
10115                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
10116                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
10117                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10118                    runtimePermissionsRevoked = true;
10119                }
10120            }
10121        }
10122
10123        permissionsState.setGlobalGids(mGlobalGids);
10124
10125        final int N = pkg.requestedPermissions.size();
10126        for (int i=0; i<N; i++) {
10127            final String name = pkg.requestedPermissions.get(i);
10128            final BasePermission bp = mSettings.mPermissions.get(name);
10129
10130            if (DEBUG_INSTALL) {
10131                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10132            }
10133
10134            if (bp == null || bp.packageSetting == null) {
10135                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10136                    Slog.w(TAG, "Unknown permission " + name
10137                            + " in package " + pkg.packageName);
10138                }
10139                continue;
10140            }
10141
10142
10143            // Limit ephemeral apps to ephemeral allowed permissions.
10144            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
10145                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
10146                        + pkg.packageName);
10147                continue;
10148            }
10149
10150            final String perm = bp.name;
10151            boolean allowedSig = false;
10152            int grant = GRANT_DENIED;
10153
10154            // Keep track of app op permissions.
10155            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10156                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10157                if (pkgs == null) {
10158                    pkgs = new ArraySet<>();
10159                    mAppOpPermissionPackages.put(bp.name, pkgs);
10160                }
10161                pkgs.add(pkg.packageName);
10162            }
10163
10164            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10165            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10166                    >= Build.VERSION_CODES.M;
10167            switch (level) {
10168                case PermissionInfo.PROTECTION_NORMAL: {
10169                    // For all apps normal permissions are install time ones.
10170                    grant = GRANT_INSTALL;
10171                } break;
10172
10173                case PermissionInfo.PROTECTION_DANGEROUS: {
10174                    // If a permission review is required for legacy apps we represent
10175                    // their permissions as always granted runtime ones since we need
10176                    // to keep the review required permission flag per user while an
10177                    // install permission's state is shared across all users.
10178                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
10179                        // For legacy apps dangerous permissions are install time ones.
10180                        grant = GRANT_INSTALL;
10181                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10182                        // For legacy apps that became modern, install becomes runtime.
10183                        grant = GRANT_UPGRADE;
10184                    } else if (mPromoteSystemApps
10185                            && isSystemApp(ps)
10186                            && mExistingSystemPackages.contains(ps.name)) {
10187                        // For legacy system apps, install becomes runtime.
10188                        // We cannot check hasInstallPermission() for system apps since those
10189                        // permissions were granted implicitly and not persisted pre-M.
10190                        grant = GRANT_UPGRADE;
10191                    } else {
10192                        // For modern apps keep runtime permissions unchanged.
10193                        grant = GRANT_RUNTIME;
10194                    }
10195                } break;
10196
10197                case PermissionInfo.PROTECTION_SIGNATURE: {
10198                    // For all apps signature permissions are install time ones.
10199                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10200                    if (allowedSig) {
10201                        grant = GRANT_INSTALL;
10202                    }
10203                } break;
10204            }
10205
10206            if (DEBUG_INSTALL) {
10207                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10208            }
10209
10210            if (grant != GRANT_DENIED) {
10211                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10212                    // If this is an existing, non-system package, then
10213                    // we can't add any new permissions to it.
10214                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10215                        // Except...  if this is a permission that was added
10216                        // to the platform (note: need to only do this when
10217                        // updating the platform).
10218                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10219                            grant = GRANT_DENIED;
10220                        }
10221                    }
10222                }
10223
10224                switch (grant) {
10225                    case GRANT_INSTALL: {
10226                        // Revoke this as runtime permission to handle the case of
10227                        // a runtime permission being downgraded to an install one.
10228                        // Also in permission review mode we keep dangerous permissions
10229                        // for legacy apps
10230                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10231                            if (origPermissions.getRuntimePermissionState(
10232                                    bp.name, userId) != null) {
10233                                // Revoke the runtime permission and clear the flags.
10234                                origPermissions.revokeRuntimePermission(bp, userId);
10235                                origPermissions.updatePermissionFlags(bp, userId,
10236                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10237                                // If we revoked a permission permission, we have to write.
10238                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10239                                        changedRuntimePermissionUserIds, userId);
10240                            }
10241                        }
10242                        // Grant an install permission.
10243                        if (permissionsState.grantInstallPermission(bp) !=
10244                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10245                            changedInstallPermission = true;
10246                        }
10247                    } break;
10248
10249                    case GRANT_RUNTIME: {
10250                        // Grant previously granted runtime permissions.
10251                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10252                            PermissionState permissionState = origPermissions
10253                                    .getRuntimePermissionState(bp.name, userId);
10254                            int flags = permissionState != null
10255                                    ? permissionState.getFlags() : 0;
10256                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10257                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10258                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10259                                    // If we cannot put the permission as it was, we have to write.
10260                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10261                                            changedRuntimePermissionUserIds, userId);
10262                                }
10263                                // If the app supports runtime permissions no need for a review.
10264                                if (mPermissionReviewRequired
10265                                        && appSupportsRuntimePermissions
10266                                        && (flags & PackageManager
10267                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10268                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10269                                    // Since we changed the flags, we have to write.
10270                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10271                                            changedRuntimePermissionUserIds, userId);
10272                                }
10273                            } else if (mPermissionReviewRequired
10274                                    && !appSupportsRuntimePermissions) {
10275                                // For legacy apps that need a permission review, every new
10276                                // runtime permission is granted but it is pending a review.
10277                                // We also need to review only platform defined runtime
10278                                // permissions as these are the only ones the platform knows
10279                                // how to disable the API to simulate revocation as legacy
10280                                // apps don't expect to run with revoked permissions.
10281                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10282                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10283                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10284                                        // We changed the flags, hence have to write.
10285                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10286                                                changedRuntimePermissionUserIds, userId);
10287                                    }
10288                                }
10289                                if (permissionsState.grantRuntimePermission(bp, userId)
10290                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10291                                    // We changed the permission, hence have to write.
10292                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10293                                            changedRuntimePermissionUserIds, userId);
10294                                }
10295                            }
10296                            // Propagate the permission flags.
10297                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10298                        }
10299                    } break;
10300
10301                    case GRANT_UPGRADE: {
10302                        // Grant runtime permissions for a previously held install permission.
10303                        PermissionState permissionState = origPermissions
10304                                .getInstallPermissionState(bp.name);
10305                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10306
10307                        if (origPermissions.revokeInstallPermission(bp)
10308                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10309                            // We will be transferring the permission flags, so clear them.
10310                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10311                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10312                            changedInstallPermission = true;
10313                        }
10314
10315                        // If the permission is not to be promoted to runtime we ignore it and
10316                        // also its other flags as they are not applicable to install permissions.
10317                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10318                            for (int userId : currentUserIds) {
10319                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10320                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10321                                    // Transfer the permission flags.
10322                                    permissionsState.updatePermissionFlags(bp, userId,
10323                                            flags, flags);
10324                                    // If we granted the permission, we have to write.
10325                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10326                                            changedRuntimePermissionUserIds, userId);
10327                                }
10328                            }
10329                        }
10330                    } break;
10331
10332                    default: {
10333                        if (packageOfInterest == null
10334                                || packageOfInterest.equals(pkg.packageName)) {
10335                            Slog.w(TAG, "Not granting permission " + perm
10336                                    + " to package " + pkg.packageName
10337                                    + " because it was previously installed without");
10338                        }
10339                    } break;
10340                }
10341            } else {
10342                if (permissionsState.revokeInstallPermission(bp) !=
10343                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10344                    // Also drop the permission flags.
10345                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10346                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10347                    changedInstallPermission = true;
10348                    Slog.i(TAG, "Un-granting permission " + perm
10349                            + " from package " + pkg.packageName
10350                            + " (protectionLevel=" + bp.protectionLevel
10351                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10352                            + ")");
10353                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10354                    // Don't print warning for app op permissions, since it is fine for them
10355                    // not to be granted, there is a UI for the user to decide.
10356                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10357                        Slog.w(TAG, "Not granting permission " + perm
10358                                + " to package " + pkg.packageName
10359                                + " (protectionLevel=" + bp.protectionLevel
10360                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10361                                + ")");
10362                    }
10363                }
10364            }
10365        }
10366
10367        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10368                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10369            // This is the first that we have heard about this package, so the
10370            // permissions we have now selected are fixed until explicitly
10371            // changed.
10372            ps.installPermissionsFixed = true;
10373        }
10374
10375        // Persist the runtime permissions state for users with changes. If permissions
10376        // were revoked because no app in the shared user declares them we have to
10377        // write synchronously to avoid losing runtime permissions state.
10378        for (int userId : changedRuntimePermissionUserIds) {
10379            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10380        }
10381    }
10382
10383    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10384        boolean allowed = false;
10385        final int NP = PackageParser.NEW_PERMISSIONS.length;
10386        for (int ip=0; ip<NP; ip++) {
10387            final PackageParser.NewPermissionInfo npi
10388                    = PackageParser.NEW_PERMISSIONS[ip];
10389            if (npi.name.equals(perm)
10390                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10391                allowed = true;
10392                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10393                        + pkg.packageName);
10394                break;
10395            }
10396        }
10397        return allowed;
10398    }
10399
10400    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10401            BasePermission bp, PermissionsState origPermissions) {
10402        boolean allowed;
10403        allowed = (compareSignatures(
10404                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10405                        == PackageManager.SIGNATURE_MATCH)
10406                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10407                        == PackageManager.SIGNATURE_MATCH);
10408        if (!allowed && (bp.protectionLevel
10409                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10410            if (isSystemApp(pkg)) {
10411                // For updated system applications, a system permission
10412                // is granted only if it had been defined by the original application.
10413                if (pkg.isUpdatedSystemApp()) {
10414                    final PackageSetting sysPs = mSettings
10415                            .getDisabledSystemPkgLPr(pkg.packageName);
10416                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10417                        // If the original was granted this permission, we take
10418                        // that grant decision as read and propagate it to the
10419                        // update.
10420                        if (sysPs.isPrivileged()) {
10421                            allowed = true;
10422                        }
10423                    } else {
10424                        // The system apk may have been updated with an older
10425                        // version of the one on the data partition, but which
10426                        // granted a new system permission that it didn't have
10427                        // before.  In this case we do want to allow the app to
10428                        // now get the new permission if the ancestral apk is
10429                        // privileged to get it.
10430                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10431                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10432                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10433                                    allowed = true;
10434                                    break;
10435                                }
10436                            }
10437                        }
10438                        // Also if a privileged parent package on the system image or any of
10439                        // its children requested a privileged permission, the updated child
10440                        // packages can also get the permission.
10441                        if (pkg.parentPackage != null) {
10442                            final PackageSetting disabledSysParentPs = mSettings
10443                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10444                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10445                                    && disabledSysParentPs.isPrivileged()) {
10446                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10447                                    allowed = true;
10448                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10449                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10450                                    for (int i = 0; i < count; i++) {
10451                                        PackageParser.Package disabledSysChildPkg =
10452                                                disabledSysParentPs.pkg.childPackages.get(i);
10453                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10454                                                perm)) {
10455                                            allowed = true;
10456                                            break;
10457                                        }
10458                                    }
10459                                }
10460                            }
10461                        }
10462                    }
10463                } else {
10464                    allowed = isPrivilegedApp(pkg);
10465                }
10466            }
10467        }
10468        if (!allowed) {
10469            if (!allowed && (bp.protectionLevel
10470                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10471                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10472                // If this was a previously normal/dangerous permission that got moved
10473                // to a system permission as part of the runtime permission redesign, then
10474                // we still want to blindly grant it to old apps.
10475                allowed = true;
10476            }
10477            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10478                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10479                // If this permission is to be granted to the system installer and
10480                // this app is an installer, then it gets the permission.
10481                allowed = true;
10482            }
10483            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10484                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10485                // If this permission is to be granted to the system verifier and
10486                // this app is a verifier, then it gets the permission.
10487                allowed = true;
10488            }
10489            if (!allowed && (bp.protectionLevel
10490                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10491                    && isSystemApp(pkg)) {
10492                // Any pre-installed system app is allowed to get this permission.
10493                allowed = true;
10494            }
10495            if (!allowed && (bp.protectionLevel
10496                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10497                // For development permissions, a development permission
10498                // is granted only if it was already granted.
10499                allowed = origPermissions.hasInstallPermission(perm);
10500            }
10501            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10502                    && pkg.packageName.equals(mSetupWizardPackage)) {
10503                // If this permission is to be granted to the system setup wizard and
10504                // this app is a setup wizard, then it gets the permission.
10505                allowed = true;
10506            }
10507        }
10508        return allowed;
10509    }
10510
10511    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10512        final int permCount = pkg.requestedPermissions.size();
10513        for (int j = 0; j < permCount; j++) {
10514            String requestedPermission = pkg.requestedPermissions.get(j);
10515            if (permission.equals(requestedPermission)) {
10516                return true;
10517            }
10518        }
10519        return false;
10520    }
10521
10522    final class ActivityIntentResolver
10523            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10524        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10525                boolean defaultOnly, int userId) {
10526            if (!sUserManager.exists(userId)) return null;
10527            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10528            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10529        }
10530
10531        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10532                int userId) {
10533            if (!sUserManager.exists(userId)) return null;
10534            mFlags = flags;
10535            return super.queryIntent(intent, resolvedType,
10536                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10537        }
10538
10539        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10540                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10541            if (!sUserManager.exists(userId)) return null;
10542            if (packageActivities == null) {
10543                return null;
10544            }
10545            mFlags = flags;
10546            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10547            final int N = packageActivities.size();
10548            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10549                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10550
10551            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10552            for (int i = 0; i < N; ++i) {
10553                intentFilters = packageActivities.get(i).intents;
10554                if (intentFilters != null && intentFilters.size() > 0) {
10555                    PackageParser.ActivityIntentInfo[] array =
10556                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10557                    intentFilters.toArray(array);
10558                    listCut.add(array);
10559                }
10560            }
10561            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10562        }
10563
10564        /**
10565         * Finds a privileged activity that matches the specified activity names.
10566         */
10567        private PackageParser.Activity findMatchingActivity(
10568                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10569            for (PackageParser.Activity sysActivity : activityList) {
10570                if (sysActivity.info.name.equals(activityInfo.name)) {
10571                    return sysActivity;
10572                }
10573                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10574                    return sysActivity;
10575                }
10576                if (sysActivity.info.targetActivity != null) {
10577                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10578                        return sysActivity;
10579                    }
10580                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10581                        return sysActivity;
10582                    }
10583                }
10584            }
10585            return null;
10586        }
10587
10588        public class IterGenerator<E> {
10589            public Iterator<E> generate(ActivityIntentInfo info) {
10590                return null;
10591            }
10592        }
10593
10594        public class ActionIterGenerator extends IterGenerator<String> {
10595            @Override
10596            public Iterator<String> generate(ActivityIntentInfo info) {
10597                return info.actionsIterator();
10598            }
10599        }
10600
10601        public class CategoriesIterGenerator extends IterGenerator<String> {
10602            @Override
10603            public Iterator<String> generate(ActivityIntentInfo info) {
10604                return info.categoriesIterator();
10605            }
10606        }
10607
10608        public class SchemesIterGenerator extends IterGenerator<String> {
10609            @Override
10610            public Iterator<String> generate(ActivityIntentInfo info) {
10611                return info.schemesIterator();
10612            }
10613        }
10614
10615        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10616            @Override
10617            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10618                return info.authoritiesIterator();
10619            }
10620        }
10621
10622        /**
10623         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10624         * MODIFIED. Do not pass in a list that should not be changed.
10625         */
10626        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10627                IterGenerator<T> generator, Iterator<T> searchIterator) {
10628            // loop through the set of actions; every one must be found in the intent filter
10629            while (searchIterator.hasNext()) {
10630                // we must have at least one filter in the list to consider a match
10631                if (intentList.size() == 0) {
10632                    break;
10633                }
10634
10635                final T searchAction = searchIterator.next();
10636
10637                // loop through the set of intent filters
10638                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10639                while (intentIter.hasNext()) {
10640                    final ActivityIntentInfo intentInfo = intentIter.next();
10641                    boolean selectionFound = false;
10642
10643                    // loop through the intent filter's selection criteria; at least one
10644                    // of them must match the searched criteria
10645                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10646                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10647                        final T intentSelection = intentSelectionIter.next();
10648                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10649                            selectionFound = true;
10650                            break;
10651                        }
10652                    }
10653
10654                    // the selection criteria wasn't found in this filter's set; this filter
10655                    // is not a potential match
10656                    if (!selectionFound) {
10657                        intentIter.remove();
10658                    }
10659                }
10660            }
10661        }
10662
10663        private boolean isProtectedAction(ActivityIntentInfo filter) {
10664            final Iterator<String> actionsIter = filter.actionsIterator();
10665            while (actionsIter != null && actionsIter.hasNext()) {
10666                final String filterAction = actionsIter.next();
10667                if (PROTECTED_ACTIONS.contains(filterAction)) {
10668                    return true;
10669                }
10670            }
10671            return false;
10672        }
10673
10674        /**
10675         * Adjusts the priority of the given intent filter according to policy.
10676         * <p>
10677         * <ul>
10678         * <li>The priority for non privileged applications is capped to '0'</li>
10679         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10680         * <li>The priority for unbundled updates to privileged applications is capped to the
10681         *      priority defined on the system partition</li>
10682         * </ul>
10683         * <p>
10684         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10685         * allowed to obtain any priority on any action.
10686         */
10687        private void adjustPriority(
10688                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10689            // nothing to do; priority is fine as-is
10690            if (intent.getPriority() <= 0) {
10691                return;
10692            }
10693
10694            final ActivityInfo activityInfo = intent.activity.info;
10695            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10696
10697            final boolean privilegedApp =
10698                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10699            if (!privilegedApp) {
10700                // non-privileged applications can never define a priority >0
10701                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10702                        + " package: " + applicationInfo.packageName
10703                        + " activity: " + intent.activity.className
10704                        + " origPrio: " + intent.getPriority());
10705                intent.setPriority(0);
10706                return;
10707            }
10708
10709            if (systemActivities == null) {
10710                // the system package is not disabled; we're parsing the system partition
10711                if (isProtectedAction(intent)) {
10712                    if (mDeferProtectedFilters) {
10713                        // We can't deal with these just yet. No component should ever obtain a
10714                        // >0 priority for a protected actions, with ONE exception -- the setup
10715                        // wizard. The setup wizard, however, cannot be known until we're able to
10716                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10717                        // until all intent filters have been processed. Chicken, meet egg.
10718                        // Let the filter temporarily have a high priority and rectify the
10719                        // priorities after all system packages have been scanned.
10720                        mProtectedFilters.add(intent);
10721                        if (DEBUG_FILTERS) {
10722                            Slog.i(TAG, "Protected action; save for later;"
10723                                    + " package: " + applicationInfo.packageName
10724                                    + " activity: " + intent.activity.className
10725                                    + " origPrio: " + intent.getPriority());
10726                        }
10727                        return;
10728                    } else {
10729                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10730                            Slog.i(TAG, "No setup wizard;"
10731                                + " All protected intents capped to priority 0");
10732                        }
10733                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10734                            if (DEBUG_FILTERS) {
10735                                Slog.i(TAG, "Found setup wizard;"
10736                                    + " allow priority " + intent.getPriority() + ";"
10737                                    + " package: " + intent.activity.info.packageName
10738                                    + " activity: " + intent.activity.className
10739                                    + " priority: " + intent.getPriority());
10740                            }
10741                            // setup wizard gets whatever it wants
10742                            return;
10743                        }
10744                        Slog.w(TAG, "Protected action; cap priority to 0;"
10745                                + " package: " + intent.activity.info.packageName
10746                                + " activity: " + intent.activity.className
10747                                + " origPrio: " + intent.getPriority());
10748                        intent.setPriority(0);
10749                        return;
10750                    }
10751                }
10752                // privileged apps on the system image get whatever priority they request
10753                return;
10754            }
10755
10756            // privileged app unbundled update ... try to find the same activity
10757            final PackageParser.Activity foundActivity =
10758                    findMatchingActivity(systemActivities, activityInfo);
10759            if (foundActivity == null) {
10760                // this is a new activity; it cannot obtain >0 priority
10761                if (DEBUG_FILTERS) {
10762                    Slog.i(TAG, "New activity; cap priority to 0;"
10763                            + " package: " + applicationInfo.packageName
10764                            + " activity: " + intent.activity.className
10765                            + " origPrio: " + intent.getPriority());
10766                }
10767                intent.setPriority(0);
10768                return;
10769            }
10770
10771            // found activity, now check for filter equivalence
10772
10773            // a shallow copy is enough; we modify the list, not its contents
10774            final List<ActivityIntentInfo> intentListCopy =
10775                    new ArrayList<>(foundActivity.intents);
10776            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10777
10778            // find matching action subsets
10779            final Iterator<String> actionsIterator = intent.actionsIterator();
10780            if (actionsIterator != null) {
10781                getIntentListSubset(
10782                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10783                if (intentListCopy.size() == 0) {
10784                    // no more intents to match; we're not equivalent
10785                    if (DEBUG_FILTERS) {
10786                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10787                                + " package: " + applicationInfo.packageName
10788                                + " activity: " + intent.activity.className
10789                                + " origPrio: " + intent.getPriority());
10790                    }
10791                    intent.setPriority(0);
10792                    return;
10793                }
10794            }
10795
10796            // find matching category subsets
10797            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10798            if (categoriesIterator != null) {
10799                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10800                        categoriesIterator);
10801                if (intentListCopy.size() == 0) {
10802                    // no more intents to match; we're not equivalent
10803                    if (DEBUG_FILTERS) {
10804                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10805                                + " package: " + applicationInfo.packageName
10806                                + " activity: " + intent.activity.className
10807                                + " origPrio: " + intent.getPriority());
10808                    }
10809                    intent.setPriority(0);
10810                    return;
10811                }
10812            }
10813
10814            // find matching schemes subsets
10815            final Iterator<String> schemesIterator = intent.schemesIterator();
10816            if (schemesIterator != null) {
10817                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10818                        schemesIterator);
10819                if (intentListCopy.size() == 0) {
10820                    // no more intents to match; we're not equivalent
10821                    if (DEBUG_FILTERS) {
10822                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10823                                + " package: " + applicationInfo.packageName
10824                                + " activity: " + intent.activity.className
10825                                + " origPrio: " + intent.getPriority());
10826                    }
10827                    intent.setPriority(0);
10828                    return;
10829                }
10830            }
10831
10832            // find matching authorities subsets
10833            final Iterator<IntentFilter.AuthorityEntry>
10834                    authoritiesIterator = intent.authoritiesIterator();
10835            if (authoritiesIterator != null) {
10836                getIntentListSubset(intentListCopy,
10837                        new AuthoritiesIterGenerator(),
10838                        authoritiesIterator);
10839                if (intentListCopy.size() == 0) {
10840                    // no more intents to match; we're not equivalent
10841                    if (DEBUG_FILTERS) {
10842                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10843                                + " package: " + applicationInfo.packageName
10844                                + " activity: " + intent.activity.className
10845                                + " origPrio: " + intent.getPriority());
10846                    }
10847                    intent.setPriority(0);
10848                    return;
10849                }
10850            }
10851
10852            // we found matching filter(s); app gets the max priority of all intents
10853            int cappedPriority = 0;
10854            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10855                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10856            }
10857            if (intent.getPriority() > cappedPriority) {
10858                if (DEBUG_FILTERS) {
10859                    Slog.i(TAG, "Found matching filter(s);"
10860                            + " cap priority to " + cappedPriority + ";"
10861                            + " package: " + applicationInfo.packageName
10862                            + " activity: " + intent.activity.className
10863                            + " origPrio: " + intent.getPriority());
10864                }
10865                intent.setPriority(cappedPriority);
10866                return;
10867            }
10868            // all this for nothing; the requested priority was <= what was on the system
10869        }
10870
10871        public final void addActivity(PackageParser.Activity a, String type) {
10872            mActivities.put(a.getComponentName(), a);
10873            if (DEBUG_SHOW_INFO)
10874                Log.v(
10875                TAG, "  " + type + " " +
10876                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10877            if (DEBUG_SHOW_INFO)
10878                Log.v(TAG, "    Class=" + a.info.name);
10879            final int NI = a.intents.size();
10880            for (int j=0; j<NI; j++) {
10881                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10882                if ("activity".equals(type)) {
10883                    final PackageSetting ps =
10884                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10885                    final List<PackageParser.Activity> systemActivities =
10886                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10887                    adjustPriority(systemActivities, intent);
10888                }
10889                if (DEBUG_SHOW_INFO) {
10890                    Log.v(TAG, "    IntentFilter:");
10891                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10892                }
10893                if (!intent.debugCheck()) {
10894                    Log.w(TAG, "==> For Activity " + a.info.name);
10895                }
10896                addFilter(intent);
10897            }
10898        }
10899
10900        public final void removeActivity(PackageParser.Activity a, String type) {
10901            mActivities.remove(a.getComponentName());
10902            if (DEBUG_SHOW_INFO) {
10903                Log.v(TAG, "  " + type + " "
10904                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10905                                : a.info.name) + ":");
10906                Log.v(TAG, "    Class=" + a.info.name);
10907            }
10908            final int NI = a.intents.size();
10909            for (int j=0; j<NI; j++) {
10910                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10911                if (DEBUG_SHOW_INFO) {
10912                    Log.v(TAG, "    IntentFilter:");
10913                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10914                }
10915                removeFilter(intent);
10916            }
10917        }
10918
10919        @Override
10920        protected boolean allowFilterResult(
10921                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10922            ActivityInfo filterAi = filter.activity.info;
10923            for (int i=dest.size()-1; i>=0; i--) {
10924                ActivityInfo destAi = dest.get(i).activityInfo;
10925                if (destAi.name == filterAi.name
10926                        && destAi.packageName == filterAi.packageName) {
10927                    return false;
10928                }
10929            }
10930            return true;
10931        }
10932
10933        @Override
10934        protected ActivityIntentInfo[] newArray(int size) {
10935            return new ActivityIntentInfo[size];
10936        }
10937
10938        @Override
10939        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10940            if (!sUserManager.exists(userId)) return true;
10941            PackageParser.Package p = filter.activity.owner;
10942            if (p != null) {
10943                PackageSetting ps = (PackageSetting)p.mExtras;
10944                if (ps != null) {
10945                    // System apps are never considered stopped for purposes of
10946                    // filtering, because there may be no way for the user to
10947                    // actually re-launch them.
10948                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10949                            && ps.getStopped(userId);
10950                }
10951            }
10952            return false;
10953        }
10954
10955        @Override
10956        protected boolean isPackageForFilter(String packageName,
10957                PackageParser.ActivityIntentInfo info) {
10958            return packageName.equals(info.activity.owner.packageName);
10959        }
10960
10961        @Override
10962        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10963                int match, int userId) {
10964            if (!sUserManager.exists(userId)) return null;
10965            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10966                return null;
10967            }
10968            final PackageParser.Activity activity = info.activity;
10969            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10970            if (ps == null) {
10971                return null;
10972            }
10973            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10974                    ps.readUserState(userId), userId);
10975            if (ai == null) {
10976                return null;
10977            }
10978            final ResolveInfo res = new ResolveInfo();
10979            res.activityInfo = ai;
10980            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10981                res.filter = info;
10982            }
10983            if (info != null) {
10984                res.handleAllWebDataURI = info.handleAllWebDataURI();
10985            }
10986            res.priority = info.getPriority();
10987            res.preferredOrder = activity.owner.mPreferredOrder;
10988            //System.out.println("Result: " + res.activityInfo.className +
10989            //                   " = " + res.priority);
10990            res.match = match;
10991            res.isDefault = info.hasDefault;
10992            res.labelRes = info.labelRes;
10993            res.nonLocalizedLabel = info.nonLocalizedLabel;
10994            if (userNeedsBadging(userId)) {
10995                res.noResourceId = true;
10996            } else {
10997                res.icon = info.icon;
10998            }
10999            res.iconResourceId = info.icon;
11000            res.system = res.activityInfo.applicationInfo.isSystemApp();
11001            return res;
11002        }
11003
11004        @Override
11005        protected void sortResults(List<ResolveInfo> results) {
11006            Collections.sort(results, mResolvePrioritySorter);
11007        }
11008
11009        @Override
11010        protected void dumpFilter(PrintWriter out, String prefix,
11011                PackageParser.ActivityIntentInfo filter) {
11012            out.print(prefix); out.print(
11013                    Integer.toHexString(System.identityHashCode(filter.activity)));
11014                    out.print(' ');
11015                    filter.activity.printComponentShortName(out);
11016                    out.print(" filter ");
11017                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11018        }
11019
11020        @Override
11021        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
11022            return filter.activity;
11023        }
11024
11025        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11026            PackageParser.Activity activity = (PackageParser.Activity)label;
11027            out.print(prefix); out.print(
11028                    Integer.toHexString(System.identityHashCode(activity)));
11029                    out.print(' ');
11030                    activity.printComponentShortName(out);
11031            if (count > 1) {
11032                out.print(" ("); out.print(count); out.print(" filters)");
11033            }
11034            out.println();
11035        }
11036
11037        // Keys are String (activity class name), values are Activity.
11038        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
11039                = new ArrayMap<ComponentName, PackageParser.Activity>();
11040        private int mFlags;
11041    }
11042
11043    private final class ServiceIntentResolver
11044            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
11045        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11046                boolean defaultOnly, int userId) {
11047            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11048            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11049        }
11050
11051        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11052                int userId) {
11053            if (!sUserManager.exists(userId)) return null;
11054            mFlags = flags;
11055            return super.queryIntent(intent, resolvedType,
11056                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11057        }
11058
11059        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11060                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
11061            if (!sUserManager.exists(userId)) return null;
11062            if (packageServices == null) {
11063                return null;
11064            }
11065            mFlags = flags;
11066            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
11067            final int N = packageServices.size();
11068            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
11069                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
11070
11071            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
11072            for (int i = 0; i < N; ++i) {
11073                intentFilters = packageServices.get(i).intents;
11074                if (intentFilters != null && intentFilters.size() > 0) {
11075                    PackageParser.ServiceIntentInfo[] array =
11076                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
11077                    intentFilters.toArray(array);
11078                    listCut.add(array);
11079                }
11080            }
11081            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11082        }
11083
11084        public final void addService(PackageParser.Service s) {
11085            mServices.put(s.getComponentName(), s);
11086            if (DEBUG_SHOW_INFO) {
11087                Log.v(TAG, "  "
11088                        + (s.info.nonLocalizedLabel != null
11089                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11090                Log.v(TAG, "    Class=" + s.info.name);
11091            }
11092            final int NI = s.intents.size();
11093            int j;
11094            for (j=0; j<NI; j++) {
11095                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11096                if (DEBUG_SHOW_INFO) {
11097                    Log.v(TAG, "    IntentFilter:");
11098                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11099                }
11100                if (!intent.debugCheck()) {
11101                    Log.w(TAG, "==> For Service " + s.info.name);
11102                }
11103                addFilter(intent);
11104            }
11105        }
11106
11107        public final void removeService(PackageParser.Service s) {
11108            mServices.remove(s.getComponentName());
11109            if (DEBUG_SHOW_INFO) {
11110                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
11111                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11112                Log.v(TAG, "    Class=" + s.info.name);
11113            }
11114            final int NI = s.intents.size();
11115            int j;
11116            for (j=0; j<NI; j++) {
11117                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11118                if (DEBUG_SHOW_INFO) {
11119                    Log.v(TAG, "    IntentFilter:");
11120                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11121                }
11122                removeFilter(intent);
11123            }
11124        }
11125
11126        @Override
11127        protected boolean allowFilterResult(
11128                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11129            ServiceInfo filterSi = filter.service.info;
11130            for (int i=dest.size()-1; i>=0; i--) {
11131                ServiceInfo destAi = dest.get(i).serviceInfo;
11132                if (destAi.name == filterSi.name
11133                        && destAi.packageName == filterSi.packageName) {
11134                    return false;
11135                }
11136            }
11137            return true;
11138        }
11139
11140        @Override
11141        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11142            return new PackageParser.ServiceIntentInfo[size];
11143        }
11144
11145        @Override
11146        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11147            if (!sUserManager.exists(userId)) return true;
11148            PackageParser.Package p = filter.service.owner;
11149            if (p != null) {
11150                PackageSetting ps = (PackageSetting)p.mExtras;
11151                if (ps != null) {
11152                    // System apps are never considered stopped for purposes of
11153                    // filtering, because there may be no way for the user to
11154                    // actually re-launch them.
11155                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11156                            && ps.getStopped(userId);
11157                }
11158            }
11159            return false;
11160        }
11161
11162        @Override
11163        protected boolean isPackageForFilter(String packageName,
11164                PackageParser.ServiceIntentInfo info) {
11165            return packageName.equals(info.service.owner.packageName);
11166        }
11167
11168        @Override
11169        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11170                int match, int userId) {
11171            if (!sUserManager.exists(userId)) return null;
11172            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11173            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11174                return null;
11175            }
11176            final PackageParser.Service service = info.service;
11177            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11178            if (ps == null) {
11179                return null;
11180            }
11181            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11182                    ps.readUserState(userId), userId);
11183            if (si == null) {
11184                return null;
11185            }
11186            final ResolveInfo res = new ResolveInfo();
11187            res.serviceInfo = si;
11188            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11189                res.filter = filter;
11190            }
11191            res.priority = info.getPriority();
11192            res.preferredOrder = service.owner.mPreferredOrder;
11193            res.match = match;
11194            res.isDefault = info.hasDefault;
11195            res.labelRes = info.labelRes;
11196            res.nonLocalizedLabel = info.nonLocalizedLabel;
11197            res.icon = info.icon;
11198            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11199            return res;
11200        }
11201
11202        @Override
11203        protected void sortResults(List<ResolveInfo> results) {
11204            Collections.sort(results, mResolvePrioritySorter);
11205        }
11206
11207        @Override
11208        protected void dumpFilter(PrintWriter out, String prefix,
11209                PackageParser.ServiceIntentInfo filter) {
11210            out.print(prefix); out.print(
11211                    Integer.toHexString(System.identityHashCode(filter.service)));
11212                    out.print(' ');
11213                    filter.service.printComponentShortName(out);
11214                    out.print(" filter ");
11215                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11216        }
11217
11218        @Override
11219        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11220            return filter.service;
11221        }
11222
11223        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11224            PackageParser.Service service = (PackageParser.Service)label;
11225            out.print(prefix); out.print(
11226                    Integer.toHexString(System.identityHashCode(service)));
11227                    out.print(' ');
11228                    service.printComponentShortName(out);
11229            if (count > 1) {
11230                out.print(" ("); out.print(count); out.print(" filters)");
11231            }
11232            out.println();
11233        }
11234
11235//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11236//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11237//            final List<ResolveInfo> retList = Lists.newArrayList();
11238//            while (i.hasNext()) {
11239//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11240//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11241//                    retList.add(resolveInfo);
11242//                }
11243//            }
11244//            return retList;
11245//        }
11246
11247        // Keys are String (activity class name), values are Activity.
11248        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11249                = new ArrayMap<ComponentName, PackageParser.Service>();
11250        private int mFlags;
11251    };
11252
11253    private final class ProviderIntentResolver
11254            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11255        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11256                boolean defaultOnly, int userId) {
11257            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11258            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11259        }
11260
11261        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11262                int userId) {
11263            if (!sUserManager.exists(userId))
11264                return null;
11265            mFlags = flags;
11266            return super.queryIntent(intent, resolvedType,
11267                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11268        }
11269
11270        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11271                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11272            if (!sUserManager.exists(userId))
11273                return null;
11274            if (packageProviders == null) {
11275                return null;
11276            }
11277            mFlags = flags;
11278            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11279            final int N = packageProviders.size();
11280            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11281                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11282
11283            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11284            for (int i = 0; i < N; ++i) {
11285                intentFilters = packageProviders.get(i).intents;
11286                if (intentFilters != null && intentFilters.size() > 0) {
11287                    PackageParser.ProviderIntentInfo[] array =
11288                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11289                    intentFilters.toArray(array);
11290                    listCut.add(array);
11291                }
11292            }
11293            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11294        }
11295
11296        public final void addProvider(PackageParser.Provider p) {
11297            if (mProviders.containsKey(p.getComponentName())) {
11298                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11299                return;
11300            }
11301
11302            mProviders.put(p.getComponentName(), p);
11303            if (DEBUG_SHOW_INFO) {
11304                Log.v(TAG, "  "
11305                        + (p.info.nonLocalizedLabel != null
11306                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11307                Log.v(TAG, "    Class=" + p.info.name);
11308            }
11309            final int NI = p.intents.size();
11310            int j;
11311            for (j = 0; j < NI; j++) {
11312                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11313                if (DEBUG_SHOW_INFO) {
11314                    Log.v(TAG, "    IntentFilter:");
11315                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11316                }
11317                if (!intent.debugCheck()) {
11318                    Log.w(TAG, "==> For Provider " + p.info.name);
11319                }
11320                addFilter(intent);
11321            }
11322        }
11323
11324        public final void removeProvider(PackageParser.Provider p) {
11325            mProviders.remove(p.getComponentName());
11326            if (DEBUG_SHOW_INFO) {
11327                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11328                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11329                Log.v(TAG, "    Class=" + p.info.name);
11330            }
11331            final int NI = p.intents.size();
11332            int j;
11333            for (j = 0; j < NI; j++) {
11334                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11335                if (DEBUG_SHOW_INFO) {
11336                    Log.v(TAG, "    IntentFilter:");
11337                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11338                }
11339                removeFilter(intent);
11340            }
11341        }
11342
11343        @Override
11344        protected boolean allowFilterResult(
11345                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11346            ProviderInfo filterPi = filter.provider.info;
11347            for (int i = dest.size() - 1; i >= 0; i--) {
11348                ProviderInfo destPi = dest.get(i).providerInfo;
11349                if (destPi.name == filterPi.name
11350                        && destPi.packageName == filterPi.packageName) {
11351                    return false;
11352                }
11353            }
11354            return true;
11355        }
11356
11357        @Override
11358        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11359            return new PackageParser.ProviderIntentInfo[size];
11360        }
11361
11362        @Override
11363        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11364            if (!sUserManager.exists(userId))
11365                return true;
11366            PackageParser.Package p = filter.provider.owner;
11367            if (p != null) {
11368                PackageSetting ps = (PackageSetting) p.mExtras;
11369                if (ps != null) {
11370                    // System apps are never considered stopped for purposes of
11371                    // filtering, because there may be no way for the user to
11372                    // actually re-launch them.
11373                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11374                            && ps.getStopped(userId);
11375                }
11376            }
11377            return false;
11378        }
11379
11380        @Override
11381        protected boolean isPackageForFilter(String packageName,
11382                PackageParser.ProviderIntentInfo info) {
11383            return packageName.equals(info.provider.owner.packageName);
11384        }
11385
11386        @Override
11387        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11388                int match, int userId) {
11389            if (!sUserManager.exists(userId))
11390                return null;
11391            final PackageParser.ProviderIntentInfo info = filter;
11392            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11393                return null;
11394            }
11395            final PackageParser.Provider provider = info.provider;
11396            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11397            if (ps == null) {
11398                return null;
11399            }
11400            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11401                    ps.readUserState(userId), userId);
11402            if (pi == null) {
11403                return null;
11404            }
11405            final ResolveInfo res = new ResolveInfo();
11406            res.providerInfo = pi;
11407            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11408                res.filter = filter;
11409            }
11410            res.priority = info.getPriority();
11411            res.preferredOrder = provider.owner.mPreferredOrder;
11412            res.match = match;
11413            res.isDefault = info.hasDefault;
11414            res.labelRes = info.labelRes;
11415            res.nonLocalizedLabel = info.nonLocalizedLabel;
11416            res.icon = info.icon;
11417            res.system = res.providerInfo.applicationInfo.isSystemApp();
11418            return res;
11419        }
11420
11421        @Override
11422        protected void sortResults(List<ResolveInfo> results) {
11423            Collections.sort(results, mResolvePrioritySorter);
11424        }
11425
11426        @Override
11427        protected void dumpFilter(PrintWriter out, String prefix,
11428                PackageParser.ProviderIntentInfo filter) {
11429            out.print(prefix);
11430            out.print(
11431                    Integer.toHexString(System.identityHashCode(filter.provider)));
11432            out.print(' ');
11433            filter.provider.printComponentShortName(out);
11434            out.print(" filter ");
11435            out.println(Integer.toHexString(System.identityHashCode(filter)));
11436        }
11437
11438        @Override
11439        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11440            return filter.provider;
11441        }
11442
11443        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11444            PackageParser.Provider provider = (PackageParser.Provider)label;
11445            out.print(prefix); out.print(
11446                    Integer.toHexString(System.identityHashCode(provider)));
11447                    out.print(' ');
11448                    provider.printComponentShortName(out);
11449            if (count > 1) {
11450                out.print(" ("); out.print(count); out.print(" filters)");
11451            }
11452            out.println();
11453        }
11454
11455        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11456                = new ArrayMap<ComponentName, PackageParser.Provider>();
11457        private int mFlags;
11458    }
11459
11460    private static final class EphemeralIntentResolver
11461            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveIntentInfo> {
11462        /**
11463         * The result that has the highest defined order. Ordering applies on a
11464         * per-package basis. Mapping is from package name to Pair of order and
11465         * EphemeralResolveInfo.
11466         * <p>
11467         * NOTE: This is implemented as a field variable for convenience and efficiency.
11468         * By having a field variable, we're able to track filter ordering as soon as
11469         * a non-zero order is defined. Otherwise, multiple loops across the result set
11470         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11471         * this needs to be contained entirely within {@link #filterResults()}.
11472         */
11473        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11474
11475        @Override
11476        protected EphemeralResolveIntentInfo[] newArray(int size) {
11477            return new EphemeralResolveIntentInfo[size];
11478        }
11479
11480        @Override
11481        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11482            return true;
11483        }
11484
11485        @Override
11486        protected EphemeralResolveIntentInfo newResult(EphemeralResolveIntentInfo info, int match,
11487                int userId) {
11488            if (!sUserManager.exists(userId)) {
11489                return null;
11490            }
11491            final String packageName = info.getEphemeralResolveInfo().getPackageName();
11492            final Integer order = info.getOrder();
11493            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11494                    mOrderResult.get(packageName);
11495            // ordering is enabled and this item's order isn't high enough
11496            if (lastOrderResult != null && lastOrderResult.first >= order) {
11497                return null;
11498            }
11499            final EphemeralResolveInfo res = info.getEphemeralResolveInfo();
11500            if (order > 0) {
11501                // non-zero order, enable ordering
11502                mOrderResult.put(packageName, new Pair<>(order, res));
11503            }
11504            return info;
11505        }
11506
11507        @Override
11508        protected void filterResults(List<EphemeralResolveIntentInfo> results) {
11509            // only do work if ordering is enabled [most of the time it won't be]
11510            if (mOrderResult.size() == 0) {
11511                return;
11512            }
11513            int resultSize = results.size();
11514            for (int i = 0; i < resultSize; i++) {
11515                final EphemeralResolveInfo info = results.get(i).getEphemeralResolveInfo();
11516                final String packageName = info.getPackageName();
11517                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11518                if (savedInfo == null) {
11519                    // package doesn't having ordering
11520                    continue;
11521                }
11522                if (savedInfo.second == info) {
11523                    // circled back to the highest ordered item; remove from order list
11524                    mOrderResult.remove(savedInfo);
11525                    if (mOrderResult.size() == 0) {
11526                        // no more ordered items
11527                        break;
11528                    }
11529                    continue;
11530                }
11531                // item has a worse order, remove it from the result list
11532                results.remove(i);
11533                resultSize--;
11534                i--;
11535            }
11536        }
11537    }
11538
11539    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11540            new Comparator<ResolveInfo>() {
11541        public int compare(ResolveInfo r1, ResolveInfo r2) {
11542            int v1 = r1.priority;
11543            int v2 = r2.priority;
11544            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11545            if (v1 != v2) {
11546                return (v1 > v2) ? -1 : 1;
11547            }
11548            v1 = r1.preferredOrder;
11549            v2 = r2.preferredOrder;
11550            if (v1 != v2) {
11551                return (v1 > v2) ? -1 : 1;
11552            }
11553            if (r1.isDefault != r2.isDefault) {
11554                return r1.isDefault ? -1 : 1;
11555            }
11556            v1 = r1.match;
11557            v2 = r2.match;
11558            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11559            if (v1 != v2) {
11560                return (v1 > v2) ? -1 : 1;
11561            }
11562            if (r1.system != r2.system) {
11563                return r1.system ? -1 : 1;
11564            }
11565            if (r1.activityInfo != null) {
11566                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11567            }
11568            if (r1.serviceInfo != null) {
11569                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11570            }
11571            if (r1.providerInfo != null) {
11572                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11573            }
11574            return 0;
11575        }
11576    };
11577
11578    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11579            new Comparator<ProviderInfo>() {
11580        public int compare(ProviderInfo p1, ProviderInfo p2) {
11581            final int v1 = p1.initOrder;
11582            final int v2 = p2.initOrder;
11583            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11584        }
11585    };
11586
11587    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11588            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11589            final int[] userIds) {
11590        mHandler.post(new Runnable() {
11591            @Override
11592            public void run() {
11593                try {
11594                    final IActivityManager am = ActivityManager.getService();
11595                    if (am == null) return;
11596                    final int[] resolvedUserIds;
11597                    if (userIds == null) {
11598                        resolvedUserIds = am.getRunningUserIds();
11599                    } else {
11600                        resolvedUserIds = userIds;
11601                    }
11602                    for (int id : resolvedUserIds) {
11603                        final Intent intent = new Intent(action,
11604                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11605                        if (extras != null) {
11606                            intent.putExtras(extras);
11607                        }
11608                        if (targetPkg != null) {
11609                            intent.setPackage(targetPkg);
11610                        }
11611                        // Modify the UID when posting to other users
11612                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11613                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11614                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11615                            intent.putExtra(Intent.EXTRA_UID, uid);
11616                        }
11617                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11618                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11619                        if (DEBUG_BROADCASTS) {
11620                            RuntimeException here = new RuntimeException("here");
11621                            here.fillInStackTrace();
11622                            Slog.d(TAG, "Sending to user " + id + ": "
11623                                    + intent.toShortString(false, true, false, false)
11624                                    + " " + intent.getExtras(), here);
11625                        }
11626                        am.broadcastIntent(null, intent, null, finishedReceiver,
11627                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11628                                null, finishedReceiver != null, false, id);
11629                    }
11630                } catch (RemoteException ex) {
11631                }
11632            }
11633        });
11634    }
11635
11636    /**
11637     * Check if the external storage media is available. This is true if there
11638     * is a mounted external storage medium or if the external storage is
11639     * emulated.
11640     */
11641    private boolean isExternalMediaAvailable() {
11642        return mMediaMounted || Environment.isExternalStorageEmulated();
11643    }
11644
11645    @Override
11646    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11647        // writer
11648        synchronized (mPackages) {
11649            if (!isExternalMediaAvailable()) {
11650                // If the external storage is no longer mounted at this point,
11651                // the caller may not have been able to delete all of this
11652                // packages files and can not delete any more.  Bail.
11653                return null;
11654            }
11655            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11656            if (lastPackage != null) {
11657                pkgs.remove(lastPackage);
11658            }
11659            if (pkgs.size() > 0) {
11660                return pkgs.get(0);
11661            }
11662        }
11663        return null;
11664    }
11665
11666    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11667        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11668                userId, andCode ? 1 : 0, packageName);
11669        if (mSystemReady) {
11670            msg.sendToTarget();
11671        } else {
11672            if (mPostSystemReadyMessages == null) {
11673                mPostSystemReadyMessages = new ArrayList<>();
11674            }
11675            mPostSystemReadyMessages.add(msg);
11676        }
11677    }
11678
11679    void startCleaningPackages() {
11680        // reader
11681        if (!isExternalMediaAvailable()) {
11682            return;
11683        }
11684        synchronized (mPackages) {
11685            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11686                return;
11687            }
11688        }
11689        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11690        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11691        IActivityManager am = ActivityManager.getService();
11692        if (am != null) {
11693            try {
11694                am.startService(null, intent, null, mContext.getOpPackageName(),
11695                        UserHandle.USER_SYSTEM);
11696            } catch (RemoteException e) {
11697            }
11698        }
11699    }
11700
11701    @Override
11702    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11703            int installFlags, String installerPackageName, int userId) {
11704        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11705
11706        final int callingUid = Binder.getCallingUid();
11707        enforceCrossUserPermission(callingUid, userId,
11708                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11709
11710        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11711            try {
11712                if (observer != null) {
11713                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11714                }
11715            } catch (RemoteException re) {
11716            }
11717            return;
11718        }
11719
11720        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11721            installFlags |= PackageManager.INSTALL_FROM_ADB;
11722
11723        } else {
11724            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11725            // about installerPackageName.
11726
11727            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11728            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11729        }
11730
11731        UserHandle user;
11732        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11733            user = UserHandle.ALL;
11734        } else {
11735            user = new UserHandle(userId);
11736        }
11737
11738        // Only system components can circumvent runtime permissions when installing.
11739        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11740                && mContext.checkCallingOrSelfPermission(Manifest.permission
11741                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11742            throw new SecurityException("You need the "
11743                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11744                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11745        }
11746
11747        final File originFile = new File(originPath);
11748        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11749
11750        final Message msg = mHandler.obtainMessage(INIT_COPY);
11751        final VerificationInfo verificationInfo = new VerificationInfo(
11752                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11753        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11754                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11755                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11756                null /*certificates*/);
11757        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11758        msg.obj = params;
11759
11760        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11761                System.identityHashCode(msg.obj));
11762        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11763                System.identityHashCode(msg.obj));
11764
11765        mHandler.sendMessage(msg);
11766    }
11767
11768    void installStage(String packageName, File stagedDir, String stagedCid,
11769            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11770            String installerPackageName, int installerUid, UserHandle user,
11771            Certificate[][] certificates) {
11772        if (DEBUG_EPHEMERAL) {
11773            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11774                Slog.d(TAG, "Ephemeral install of " + packageName);
11775            }
11776        }
11777        final VerificationInfo verificationInfo = new VerificationInfo(
11778                sessionParams.originatingUri, sessionParams.referrerUri,
11779                sessionParams.originatingUid, installerUid);
11780
11781        final OriginInfo origin;
11782        if (stagedDir != null) {
11783            origin = OriginInfo.fromStagedFile(stagedDir);
11784        } else {
11785            origin = OriginInfo.fromStagedContainer(stagedCid);
11786        }
11787
11788        final Message msg = mHandler.obtainMessage(INIT_COPY);
11789        final InstallParams params = new InstallParams(origin, null, observer,
11790                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11791                verificationInfo, user, sessionParams.abiOverride,
11792                sessionParams.grantedRuntimePermissions, certificates);
11793        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11794        msg.obj = params;
11795
11796        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11797                System.identityHashCode(msg.obj));
11798        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11799                System.identityHashCode(msg.obj));
11800
11801        mHandler.sendMessage(msg);
11802    }
11803
11804    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11805            int userId) {
11806        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11807        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
11808    }
11809
11810    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
11811            int appId, int... userIds) {
11812        if (ArrayUtils.isEmpty(userIds)) {
11813            return;
11814        }
11815        Bundle extras = new Bundle(1);
11816        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
11817        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
11818
11819        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11820                packageName, extras, 0, null, null, userIds);
11821        if (isSystem) {
11822            mHandler.post(() -> {
11823                        for (int userId : userIds) {
11824                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
11825                        }
11826                    }
11827            );
11828        }
11829    }
11830
11831    /**
11832     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
11833     * automatically without needing an explicit launch.
11834     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
11835     */
11836    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
11837        // If user is not running, the app didn't miss any broadcast
11838        if (!mUserManagerInternal.isUserRunning(userId)) {
11839            return;
11840        }
11841        final IActivityManager am = ActivityManager.getService();
11842        try {
11843            // Deliver LOCKED_BOOT_COMPLETED first
11844            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
11845                    .setPackage(packageName);
11846            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
11847            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
11848                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11849
11850            // Deliver BOOT_COMPLETED only if user is unlocked
11851            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
11852                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
11853                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
11854                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11855            }
11856        } catch (RemoteException e) {
11857            throw e.rethrowFromSystemServer();
11858        }
11859    }
11860
11861    @Override
11862    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11863            int userId) {
11864        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11865        PackageSetting pkgSetting;
11866        final int uid = Binder.getCallingUid();
11867        enforceCrossUserPermission(uid, userId,
11868                true /* requireFullPermission */, true /* checkShell */,
11869                "setApplicationHiddenSetting for user " + userId);
11870
11871        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11872            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11873            return false;
11874        }
11875
11876        long callingId = Binder.clearCallingIdentity();
11877        try {
11878            boolean sendAdded = false;
11879            boolean sendRemoved = false;
11880            // writer
11881            synchronized (mPackages) {
11882                pkgSetting = mSettings.mPackages.get(packageName);
11883                if (pkgSetting == null) {
11884                    return false;
11885                }
11886                // Do not allow "android" is being disabled
11887                if ("android".equals(packageName)) {
11888                    Slog.w(TAG, "Cannot hide package: android");
11889                    return false;
11890                }
11891                // Only allow protected packages to hide themselves.
11892                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11893                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11894                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11895                    return false;
11896                }
11897
11898                if (pkgSetting.getHidden(userId) != hidden) {
11899                    pkgSetting.setHidden(hidden, userId);
11900                    mSettings.writePackageRestrictionsLPr(userId);
11901                    if (hidden) {
11902                        sendRemoved = true;
11903                    } else {
11904                        sendAdded = true;
11905                    }
11906                }
11907            }
11908            if (sendAdded) {
11909                sendPackageAddedForUser(packageName, pkgSetting, userId);
11910                return true;
11911            }
11912            if (sendRemoved) {
11913                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11914                        "hiding pkg");
11915                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11916                return true;
11917            }
11918        } finally {
11919            Binder.restoreCallingIdentity(callingId);
11920        }
11921        return false;
11922    }
11923
11924    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11925            int userId) {
11926        final PackageRemovedInfo info = new PackageRemovedInfo();
11927        info.removedPackage = packageName;
11928        info.removedUsers = new int[] {userId};
11929        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11930        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11931    }
11932
11933    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11934        if (pkgList.length > 0) {
11935            Bundle extras = new Bundle(1);
11936            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11937
11938            sendPackageBroadcast(
11939                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11940                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11941                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11942                    new int[] {userId});
11943        }
11944    }
11945
11946    /**
11947     * Returns true if application is not found or there was an error. Otherwise it returns
11948     * the hidden state of the package for the given user.
11949     */
11950    @Override
11951    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11952        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11953        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11954                true /* requireFullPermission */, false /* checkShell */,
11955                "getApplicationHidden for user " + userId);
11956        PackageSetting pkgSetting;
11957        long callingId = Binder.clearCallingIdentity();
11958        try {
11959            // writer
11960            synchronized (mPackages) {
11961                pkgSetting = mSettings.mPackages.get(packageName);
11962                if (pkgSetting == null) {
11963                    return true;
11964                }
11965                return pkgSetting.getHidden(userId);
11966            }
11967        } finally {
11968            Binder.restoreCallingIdentity(callingId);
11969        }
11970    }
11971
11972    /**
11973     * @hide
11974     */
11975    @Override
11976    public int installExistingPackageAsUser(String packageName, int userId) {
11977        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11978                null);
11979        PackageSetting pkgSetting;
11980        final int uid = Binder.getCallingUid();
11981        enforceCrossUserPermission(uid, userId,
11982                true /* requireFullPermission */, true /* checkShell */,
11983                "installExistingPackage for user " + userId);
11984        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11985            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11986        }
11987
11988        long callingId = Binder.clearCallingIdentity();
11989        try {
11990            boolean installed = false;
11991
11992            // writer
11993            synchronized (mPackages) {
11994                pkgSetting = mSettings.mPackages.get(packageName);
11995                if (pkgSetting == null) {
11996                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11997                }
11998                if (!pkgSetting.getInstalled(userId)) {
11999                    pkgSetting.setInstalled(true, userId);
12000                    pkgSetting.setHidden(false, userId);
12001                    mSettings.writePackageRestrictionsLPr(userId);
12002                    installed = true;
12003                }
12004            }
12005
12006            if (installed) {
12007                if (pkgSetting.pkg != null) {
12008                    synchronized (mInstallLock) {
12009                        // We don't need to freeze for a brand new install
12010                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
12011                    }
12012                }
12013                sendPackageAddedForUser(packageName, pkgSetting, userId);
12014            }
12015        } finally {
12016            Binder.restoreCallingIdentity(callingId);
12017        }
12018
12019        return PackageManager.INSTALL_SUCCEEDED;
12020    }
12021
12022    boolean isUserRestricted(int userId, String restrictionKey) {
12023        Bundle restrictions = sUserManager.getUserRestrictions(userId);
12024        if (restrictions.getBoolean(restrictionKey, false)) {
12025            Log.w(TAG, "User is restricted: " + restrictionKey);
12026            return true;
12027        }
12028        return false;
12029    }
12030
12031    @Override
12032    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
12033            int userId) {
12034        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12035        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12036                true /* requireFullPermission */, true /* checkShell */,
12037                "setPackagesSuspended for user " + userId);
12038
12039        if (ArrayUtils.isEmpty(packageNames)) {
12040            return packageNames;
12041        }
12042
12043        // List of package names for whom the suspended state has changed.
12044        List<String> changedPackages = new ArrayList<>(packageNames.length);
12045        // List of package names for whom the suspended state is not set as requested in this
12046        // method.
12047        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
12048        long callingId = Binder.clearCallingIdentity();
12049        try {
12050            for (int i = 0; i < packageNames.length; i++) {
12051                String packageName = packageNames[i];
12052                boolean changed = false;
12053                final int appId;
12054                synchronized (mPackages) {
12055                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12056                    if (pkgSetting == null) {
12057                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
12058                                + "\". Skipping suspending/un-suspending.");
12059                        unactionedPackages.add(packageName);
12060                        continue;
12061                    }
12062                    appId = pkgSetting.appId;
12063                    if (pkgSetting.getSuspended(userId) != suspended) {
12064                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
12065                            unactionedPackages.add(packageName);
12066                            continue;
12067                        }
12068                        pkgSetting.setSuspended(suspended, userId);
12069                        mSettings.writePackageRestrictionsLPr(userId);
12070                        changed = true;
12071                        changedPackages.add(packageName);
12072                    }
12073                }
12074
12075                if (changed && suspended) {
12076                    killApplication(packageName, UserHandle.getUid(userId, appId),
12077                            "suspending package");
12078                }
12079            }
12080        } finally {
12081            Binder.restoreCallingIdentity(callingId);
12082        }
12083
12084        if (!changedPackages.isEmpty()) {
12085            sendPackagesSuspendedForUser(changedPackages.toArray(
12086                    new String[changedPackages.size()]), userId, suspended);
12087        }
12088
12089        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
12090    }
12091
12092    @Override
12093    public boolean isPackageSuspendedForUser(String packageName, int userId) {
12094        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12095                true /* requireFullPermission */, false /* checkShell */,
12096                "isPackageSuspendedForUser for user " + userId);
12097        synchronized (mPackages) {
12098            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12099            if (pkgSetting == null) {
12100                throw new IllegalArgumentException("Unknown target package: " + packageName);
12101            }
12102            return pkgSetting.getSuspended(userId);
12103        }
12104    }
12105
12106    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
12107        if (isPackageDeviceAdmin(packageName, userId)) {
12108            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12109                    + "\": has an active device admin");
12110            return false;
12111        }
12112
12113        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
12114        if (packageName.equals(activeLauncherPackageName)) {
12115            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12116                    + "\": contains the active launcher");
12117            return false;
12118        }
12119
12120        if (packageName.equals(mRequiredInstallerPackage)) {
12121            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12122                    + "\": required for package installation");
12123            return false;
12124        }
12125
12126        if (packageName.equals(mRequiredUninstallerPackage)) {
12127            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12128                    + "\": required for package uninstallation");
12129            return false;
12130        }
12131
12132        if (packageName.equals(mRequiredVerifierPackage)) {
12133            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12134                    + "\": required for package verification");
12135            return false;
12136        }
12137
12138        if (packageName.equals(getDefaultDialerPackageName(userId))) {
12139            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12140                    + "\": is the default dialer");
12141            return false;
12142        }
12143
12144        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12145            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12146                    + "\": protected package");
12147            return false;
12148        }
12149
12150        return true;
12151    }
12152
12153    private String getActiveLauncherPackageName(int userId) {
12154        Intent intent = new Intent(Intent.ACTION_MAIN);
12155        intent.addCategory(Intent.CATEGORY_HOME);
12156        ResolveInfo resolveInfo = resolveIntent(
12157                intent,
12158                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12159                PackageManager.MATCH_DEFAULT_ONLY,
12160                userId);
12161
12162        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12163    }
12164
12165    private String getDefaultDialerPackageName(int userId) {
12166        synchronized (mPackages) {
12167            return mSettings.getDefaultDialerPackageNameLPw(userId);
12168        }
12169    }
12170
12171    @Override
12172    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12173        mContext.enforceCallingOrSelfPermission(
12174                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12175                "Only package verification agents can verify applications");
12176
12177        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12178        final PackageVerificationResponse response = new PackageVerificationResponse(
12179                verificationCode, Binder.getCallingUid());
12180        msg.arg1 = id;
12181        msg.obj = response;
12182        mHandler.sendMessage(msg);
12183    }
12184
12185    @Override
12186    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12187            long millisecondsToDelay) {
12188        mContext.enforceCallingOrSelfPermission(
12189                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12190                "Only package verification agents can extend verification timeouts");
12191
12192        final PackageVerificationState state = mPendingVerification.get(id);
12193        final PackageVerificationResponse response = new PackageVerificationResponse(
12194                verificationCodeAtTimeout, Binder.getCallingUid());
12195
12196        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12197            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12198        }
12199        if (millisecondsToDelay < 0) {
12200            millisecondsToDelay = 0;
12201        }
12202        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12203                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12204            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12205        }
12206
12207        if ((state != null) && !state.timeoutExtended()) {
12208            state.extendTimeout();
12209
12210            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12211            msg.arg1 = id;
12212            msg.obj = response;
12213            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12214        }
12215    }
12216
12217    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12218            int verificationCode, UserHandle user) {
12219        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12220        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12221        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12222        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12223        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12224
12225        mContext.sendBroadcastAsUser(intent, user,
12226                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12227    }
12228
12229    private ComponentName matchComponentForVerifier(String packageName,
12230            List<ResolveInfo> receivers) {
12231        ActivityInfo targetReceiver = null;
12232
12233        final int NR = receivers.size();
12234        for (int i = 0; i < NR; i++) {
12235            final ResolveInfo info = receivers.get(i);
12236            if (info.activityInfo == null) {
12237                continue;
12238            }
12239
12240            if (packageName.equals(info.activityInfo.packageName)) {
12241                targetReceiver = info.activityInfo;
12242                break;
12243            }
12244        }
12245
12246        if (targetReceiver == null) {
12247            return null;
12248        }
12249
12250        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12251    }
12252
12253    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12254            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12255        if (pkgInfo.verifiers.length == 0) {
12256            return null;
12257        }
12258
12259        final int N = pkgInfo.verifiers.length;
12260        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12261        for (int i = 0; i < N; i++) {
12262            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12263
12264            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12265                    receivers);
12266            if (comp == null) {
12267                continue;
12268            }
12269
12270            final int verifierUid = getUidForVerifier(verifierInfo);
12271            if (verifierUid == -1) {
12272                continue;
12273            }
12274
12275            if (DEBUG_VERIFY) {
12276                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12277                        + " with the correct signature");
12278            }
12279            sufficientVerifiers.add(comp);
12280            verificationState.addSufficientVerifier(verifierUid);
12281        }
12282
12283        return sufficientVerifiers;
12284    }
12285
12286    private int getUidForVerifier(VerifierInfo verifierInfo) {
12287        synchronized (mPackages) {
12288            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12289            if (pkg == null) {
12290                return -1;
12291            } else if (pkg.mSignatures.length != 1) {
12292                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12293                        + " has more than one signature; ignoring");
12294                return -1;
12295            }
12296
12297            /*
12298             * If the public key of the package's signature does not match
12299             * our expected public key, then this is a different package and
12300             * we should skip.
12301             */
12302
12303            final byte[] expectedPublicKey;
12304            try {
12305                final Signature verifierSig = pkg.mSignatures[0];
12306                final PublicKey publicKey = verifierSig.getPublicKey();
12307                expectedPublicKey = publicKey.getEncoded();
12308            } catch (CertificateException e) {
12309                return -1;
12310            }
12311
12312            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12313
12314            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12315                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12316                        + " does not have the expected public key; ignoring");
12317                return -1;
12318            }
12319
12320            return pkg.applicationInfo.uid;
12321        }
12322    }
12323
12324    @Override
12325    public void finishPackageInstall(int token, boolean didLaunch) {
12326        enforceSystemOrRoot("Only the system is allowed to finish installs");
12327
12328        if (DEBUG_INSTALL) {
12329            Slog.v(TAG, "BM finishing package install for " + token);
12330        }
12331        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12332
12333        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12334        mHandler.sendMessage(msg);
12335    }
12336
12337    /**
12338     * Get the verification agent timeout.
12339     *
12340     * @return verification timeout in milliseconds
12341     */
12342    private long getVerificationTimeout() {
12343        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12344                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12345                DEFAULT_VERIFICATION_TIMEOUT);
12346    }
12347
12348    /**
12349     * Get the default verification agent response code.
12350     *
12351     * @return default verification response code
12352     */
12353    private int getDefaultVerificationResponse() {
12354        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12355                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12356                DEFAULT_VERIFICATION_RESPONSE);
12357    }
12358
12359    /**
12360     * Check whether or not package verification has been enabled.
12361     *
12362     * @return true if verification should be performed
12363     */
12364    private boolean isVerificationEnabled(int userId, int installFlags) {
12365        if (!DEFAULT_VERIFY_ENABLE) {
12366            return false;
12367        }
12368        // Ephemeral apps don't get the full verification treatment
12369        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12370            if (DEBUG_EPHEMERAL) {
12371                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12372            }
12373            return false;
12374        }
12375
12376        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12377
12378        // Check if installing from ADB
12379        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12380            // Do not run verification in a test harness environment
12381            if (ActivityManager.isRunningInTestHarness()) {
12382                return false;
12383            }
12384            if (ensureVerifyAppsEnabled) {
12385                return true;
12386            }
12387            // Check if the developer does not want package verification for ADB installs
12388            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12389                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12390                return false;
12391            }
12392        }
12393
12394        if (ensureVerifyAppsEnabled) {
12395            return true;
12396        }
12397
12398        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12399                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12400    }
12401
12402    @Override
12403    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12404            throws RemoteException {
12405        mContext.enforceCallingOrSelfPermission(
12406                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12407                "Only intentfilter verification agents can verify applications");
12408
12409        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12410        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12411                Binder.getCallingUid(), verificationCode, failedDomains);
12412        msg.arg1 = id;
12413        msg.obj = response;
12414        mHandler.sendMessage(msg);
12415    }
12416
12417    @Override
12418    public int getIntentVerificationStatus(String packageName, int userId) {
12419        synchronized (mPackages) {
12420            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12421        }
12422    }
12423
12424    @Override
12425    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12426        mContext.enforceCallingOrSelfPermission(
12427                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12428
12429        boolean result = false;
12430        synchronized (mPackages) {
12431            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12432        }
12433        if (result) {
12434            scheduleWritePackageRestrictionsLocked(userId);
12435        }
12436        return result;
12437    }
12438
12439    @Override
12440    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12441            String packageName) {
12442        synchronized (mPackages) {
12443            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12444        }
12445    }
12446
12447    @Override
12448    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12449        if (TextUtils.isEmpty(packageName)) {
12450            return ParceledListSlice.emptyList();
12451        }
12452        synchronized (mPackages) {
12453            PackageParser.Package pkg = mPackages.get(packageName);
12454            if (pkg == null || pkg.activities == null) {
12455                return ParceledListSlice.emptyList();
12456            }
12457            final int count = pkg.activities.size();
12458            ArrayList<IntentFilter> result = new ArrayList<>();
12459            for (int n=0; n<count; n++) {
12460                PackageParser.Activity activity = pkg.activities.get(n);
12461                if (activity.intents != null && activity.intents.size() > 0) {
12462                    result.addAll(activity.intents);
12463                }
12464            }
12465            return new ParceledListSlice<>(result);
12466        }
12467    }
12468
12469    @Override
12470    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12471        mContext.enforceCallingOrSelfPermission(
12472                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12473
12474        synchronized (mPackages) {
12475            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12476            if (packageName != null) {
12477                result |= updateIntentVerificationStatus(packageName,
12478                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12479                        userId);
12480                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12481                        packageName, userId);
12482            }
12483            return result;
12484        }
12485    }
12486
12487    @Override
12488    public String getDefaultBrowserPackageName(int userId) {
12489        synchronized (mPackages) {
12490            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12491        }
12492    }
12493
12494    /**
12495     * Get the "allow unknown sources" setting.
12496     *
12497     * @return the current "allow unknown sources" setting
12498     */
12499    private int getUnknownSourcesSettings() {
12500        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12501                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12502                -1);
12503    }
12504
12505    @Override
12506    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12507        final int uid = Binder.getCallingUid();
12508        // writer
12509        synchronized (mPackages) {
12510            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12511            if (targetPackageSetting == null) {
12512                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12513            }
12514
12515            PackageSetting installerPackageSetting;
12516            if (installerPackageName != null) {
12517                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12518                if (installerPackageSetting == null) {
12519                    throw new IllegalArgumentException("Unknown installer package: "
12520                            + installerPackageName);
12521                }
12522            } else {
12523                installerPackageSetting = null;
12524            }
12525
12526            Signature[] callerSignature;
12527            Object obj = mSettings.getUserIdLPr(uid);
12528            if (obj != null) {
12529                if (obj instanceof SharedUserSetting) {
12530                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12531                } else if (obj instanceof PackageSetting) {
12532                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12533                } else {
12534                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12535                }
12536            } else {
12537                throw new SecurityException("Unknown calling UID: " + uid);
12538            }
12539
12540            // Verify: can't set installerPackageName to a package that is
12541            // not signed with the same cert as the caller.
12542            if (installerPackageSetting != null) {
12543                if (compareSignatures(callerSignature,
12544                        installerPackageSetting.signatures.mSignatures)
12545                        != PackageManager.SIGNATURE_MATCH) {
12546                    throw new SecurityException(
12547                            "Caller does not have same cert as new installer package "
12548                            + installerPackageName);
12549                }
12550            }
12551
12552            // Verify: if target already has an installer package, it must
12553            // be signed with the same cert as the caller.
12554            if (targetPackageSetting.installerPackageName != null) {
12555                PackageSetting setting = mSettings.mPackages.get(
12556                        targetPackageSetting.installerPackageName);
12557                // If the currently set package isn't valid, then it's always
12558                // okay to change it.
12559                if (setting != null) {
12560                    if (compareSignatures(callerSignature,
12561                            setting.signatures.mSignatures)
12562                            != PackageManager.SIGNATURE_MATCH) {
12563                        throw new SecurityException(
12564                                "Caller does not have same cert as old installer package "
12565                                + targetPackageSetting.installerPackageName);
12566                    }
12567                }
12568            }
12569
12570            // Okay!
12571            targetPackageSetting.installerPackageName = installerPackageName;
12572            if (installerPackageName != null) {
12573                mSettings.mInstallerPackages.add(installerPackageName);
12574            }
12575            scheduleWriteSettingsLocked();
12576        }
12577    }
12578
12579    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12580        // Queue up an async operation since the package installation may take a little while.
12581        mHandler.post(new Runnable() {
12582            public void run() {
12583                mHandler.removeCallbacks(this);
12584                 // Result object to be returned
12585                PackageInstalledInfo res = new PackageInstalledInfo();
12586                res.setReturnCode(currentStatus);
12587                res.uid = -1;
12588                res.pkg = null;
12589                res.removedInfo = null;
12590                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12591                    args.doPreInstall(res.returnCode);
12592                    synchronized (mInstallLock) {
12593                        installPackageTracedLI(args, res);
12594                    }
12595                    args.doPostInstall(res.returnCode, res.uid);
12596                }
12597
12598                // A restore should be performed at this point if (a) the install
12599                // succeeded, (b) the operation is not an update, and (c) the new
12600                // package has not opted out of backup participation.
12601                final boolean update = res.removedInfo != null
12602                        && res.removedInfo.removedPackage != null;
12603                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12604                boolean doRestore = !update
12605                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12606
12607                // Set up the post-install work request bookkeeping.  This will be used
12608                // and cleaned up by the post-install event handling regardless of whether
12609                // there's a restore pass performed.  Token values are >= 1.
12610                int token;
12611                if (mNextInstallToken < 0) mNextInstallToken = 1;
12612                token = mNextInstallToken++;
12613
12614                PostInstallData data = new PostInstallData(args, res);
12615                mRunningInstalls.put(token, data);
12616                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12617
12618                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12619                    // Pass responsibility to the Backup Manager.  It will perform a
12620                    // restore if appropriate, then pass responsibility back to the
12621                    // Package Manager to run the post-install observer callbacks
12622                    // and broadcasts.
12623                    IBackupManager bm = IBackupManager.Stub.asInterface(
12624                            ServiceManager.getService(Context.BACKUP_SERVICE));
12625                    if (bm != null) {
12626                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12627                                + " to BM for possible restore");
12628                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12629                        try {
12630                            // TODO: http://b/22388012
12631                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12632                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12633                            } else {
12634                                doRestore = false;
12635                            }
12636                        } catch (RemoteException e) {
12637                            // can't happen; the backup manager is local
12638                        } catch (Exception e) {
12639                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12640                            doRestore = false;
12641                        }
12642                    } else {
12643                        Slog.e(TAG, "Backup Manager not found!");
12644                        doRestore = false;
12645                    }
12646                }
12647
12648                if (!doRestore) {
12649                    // No restore possible, or the Backup Manager was mysteriously not
12650                    // available -- just fire the post-install work request directly.
12651                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12652
12653                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12654
12655                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12656                    mHandler.sendMessage(msg);
12657                }
12658            }
12659        });
12660    }
12661
12662    /**
12663     * Callback from PackageSettings whenever an app is first transitioned out of the
12664     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12665     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12666     * here whether the app is the target of an ongoing install, and only send the
12667     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12668     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12669     * handling.
12670     */
12671    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12672        // Serialize this with the rest of the install-process message chain.  In the
12673        // restore-at-install case, this Runnable will necessarily run before the
12674        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12675        // are coherent.  In the non-restore case, the app has already completed install
12676        // and been launched through some other means, so it is not in a problematic
12677        // state for observers to see the FIRST_LAUNCH signal.
12678        mHandler.post(new Runnable() {
12679            @Override
12680            public void run() {
12681                for (int i = 0; i < mRunningInstalls.size(); i++) {
12682                    final PostInstallData data = mRunningInstalls.valueAt(i);
12683                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12684                        continue;
12685                    }
12686                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12687                        // right package; but is it for the right user?
12688                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12689                            if (userId == data.res.newUsers[uIndex]) {
12690                                if (DEBUG_BACKUP) {
12691                                    Slog.i(TAG, "Package " + pkgName
12692                                            + " being restored so deferring FIRST_LAUNCH");
12693                                }
12694                                return;
12695                            }
12696                        }
12697                    }
12698                }
12699                // didn't find it, so not being restored
12700                if (DEBUG_BACKUP) {
12701                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12702                }
12703                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12704            }
12705        });
12706    }
12707
12708    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12709        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12710                installerPkg, null, userIds);
12711    }
12712
12713    private abstract class HandlerParams {
12714        private static final int MAX_RETRIES = 4;
12715
12716        /**
12717         * Number of times startCopy() has been attempted and had a non-fatal
12718         * error.
12719         */
12720        private int mRetries = 0;
12721
12722        /** User handle for the user requesting the information or installation. */
12723        private final UserHandle mUser;
12724        String traceMethod;
12725        int traceCookie;
12726
12727        HandlerParams(UserHandle user) {
12728            mUser = user;
12729        }
12730
12731        UserHandle getUser() {
12732            return mUser;
12733        }
12734
12735        HandlerParams setTraceMethod(String traceMethod) {
12736            this.traceMethod = traceMethod;
12737            return this;
12738        }
12739
12740        HandlerParams setTraceCookie(int traceCookie) {
12741            this.traceCookie = traceCookie;
12742            return this;
12743        }
12744
12745        final boolean startCopy() {
12746            boolean res;
12747            try {
12748                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12749
12750                if (++mRetries > MAX_RETRIES) {
12751                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12752                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12753                    handleServiceError();
12754                    return false;
12755                } else {
12756                    handleStartCopy();
12757                    res = true;
12758                }
12759            } catch (RemoteException e) {
12760                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12761                mHandler.sendEmptyMessage(MCS_RECONNECT);
12762                res = false;
12763            }
12764            handleReturnCode();
12765            return res;
12766        }
12767
12768        final void serviceError() {
12769            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12770            handleServiceError();
12771            handleReturnCode();
12772        }
12773
12774        abstract void handleStartCopy() throws RemoteException;
12775        abstract void handleServiceError();
12776        abstract void handleReturnCode();
12777    }
12778
12779    class MeasureParams extends HandlerParams {
12780        private final PackageStats mStats;
12781        private boolean mSuccess;
12782
12783        private final IPackageStatsObserver mObserver;
12784
12785        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12786            super(new UserHandle(stats.userHandle));
12787            mObserver = observer;
12788            mStats = stats;
12789        }
12790
12791        @Override
12792        public String toString() {
12793            return "MeasureParams{"
12794                + Integer.toHexString(System.identityHashCode(this))
12795                + " " + mStats.packageName + "}";
12796        }
12797
12798        @Override
12799        void handleStartCopy() throws RemoteException {
12800            synchronized (mInstallLock) {
12801                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12802            }
12803
12804            if (mSuccess) {
12805                boolean mounted = false;
12806                try {
12807                    final String status = Environment.getExternalStorageState();
12808                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12809                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12810                } catch (Exception e) {
12811                }
12812
12813                if (mounted) {
12814                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12815
12816                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12817                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12818
12819                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12820                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12821
12822                    // Always subtract cache size, since it's a subdirectory
12823                    mStats.externalDataSize -= mStats.externalCacheSize;
12824
12825                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12826                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12827
12828                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12829                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12830                }
12831            }
12832        }
12833
12834        @Override
12835        void handleReturnCode() {
12836            if (mObserver != null) {
12837                try {
12838                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12839                } catch (RemoteException e) {
12840                    Slog.i(TAG, "Observer no longer exists.");
12841                }
12842            }
12843        }
12844
12845        @Override
12846        void handleServiceError() {
12847            Slog.e(TAG, "Could not measure application " + mStats.packageName
12848                            + " external storage");
12849        }
12850    }
12851
12852    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12853            throws RemoteException {
12854        long result = 0;
12855        for (File path : paths) {
12856            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12857        }
12858        return result;
12859    }
12860
12861    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12862        for (File path : paths) {
12863            try {
12864                mcs.clearDirectory(path.getAbsolutePath());
12865            } catch (RemoteException e) {
12866            }
12867        }
12868    }
12869
12870    static class OriginInfo {
12871        /**
12872         * Location where install is coming from, before it has been
12873         * copied/renamed into place. This could be a single monolithic APK
12874         * file, or a cluster directory. This location may be untrusted.
12875         */
12876        final File file;
12877        final String cid;
12878
12879        /**
12880         * Flag indicating that {@link #file} or {@link #cid} has already been
12881         * staged, meaning downstream users don't need to defensively copy the
12882         * contents.
12883         */
12884        final boolean staged;
12885
12886        /**
12887         * Flag indicating that {@link #file} or {@link #cid} is an already
12888         * installed app that is being moved.
12889         */
12890        final boolean existing;
12891
12892        final String resolvedPath;
12893        final File resolvedFile;
12894
12895        static OriginInfo fromNothing() {
12896            return new OriginInfo(null, null, false, false);
12897        }
12898
12899        static OriginInfo fromUntrustedFile(File file) {
12900            return new OriginInfo(file, null, false, false);
12901        }
12902
12903        static OriginInfo fromExistingFile(File file) {
12904            return new OriginInfo(file, null, false, true);
12905        }
12906
12907        static OriginInfo fromStagedFile(File file) {
12908            return new OriginInfo(file, null, true, false);
12909        }
12910
12911        static OriginInfo fromStagedContainer(String cid) {
12912            return new OriginInfo(null, cid, true, false);
12913        }
12914
12915        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12916            this.file = file;
12917            this.cid = cid;
12918            this.staged = staged;
12919            this.existing = existing;
12920
12921            if (cid != null) {
12922                resolvedPath = PackageHelper.getSdDir(cid);
12923                resolvedFile = new File(resolvedPath);
12924            } else if (file != null) {
12925                resolvedPath = file.getAbsolutePath();
12926                resolvedFile = file;
12927            } else {
12928                resolvedPath = null;
12929                resolvedFile = null;
12930            }
12931        }
12932    }
12933
12934    static class MoveInfo {
12935        final int moveId;
12936        final String fromUuid;
12937        final String toUuid;
12938        final String packageName;
12939        final String dataAppName;
12940        final int appId;
12941        final String seinfo;
12942        final int targetSdkVersion;
12943
12944        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12945                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12946            this.moveId = moveId;
12947            this.fromUuid = fromUuid;
12948            this.toUuid = toUuid;
12949            this.packageName = packageName;
12950            this.dataAppName = dataAppName;
12951            this.appId = appId;
12952            this.seinfo = seinfo;
12953            this.targetSdkVersion = targetSdkVersion;
12954        }
12955    }
12956
12957    static class VerificationInfo {
12958        /** A constant used to indicate that a uid value is not present. */
12959        public static final int NO_UID = -1;
12960
12961        /** URI referencing where the package was downloaded from. */
12962        final Uri originatingUri;
12963
12964        /** HTTP referrer URI associated with the originatingURI. */
12965        final Uri referrer;
12966
12967        /** UID of the application that the install request originated from. */
12968        final int originatingUid;
12969
12970        /** UID of application requesting the install */
12971        final int installerUid;
12972
12973        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12974            this.originatingUri = originatingUri;
12975            this.referrer = referrer;
12976            this.originatingUid = originatingUid;
12977            this.installerUid = installerUid;
12978        }
12979    }
12980
12981    class InstallParams extends HandlerParams {
12982        final OriginInfo origin;
12983        final MoveInfo move;
12984        final IPackageInstallObserver2 observer;
12985        int installFlags;
12986        final String installerPackageName;
12987        final String volumeUuid;
12988        private InstallArgs mArgs;
12989        private int mRet;
12990        final String packageAbiOverride;
12991        final String[] grantedRuntimePermissions;
12992        final VerificationInfo verificationInfo;
12993        final Certificate[][] certificates;
12994
12995        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12996                int installFlags, String installerPackageName, String volumeUuid,
12997                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12998                String[] grantedPermissions, Certificate[][] certificates) {
12999            super(user);
13000            this.origin = origin;
13001            this.move = move;
13002            this.observer = observer;
13003            this.installFlags = installFlags;
13004            this.installerPackageName = installerPackageName;
13005            this.volumeUuid = volumeUuid;
13006            this.verificationInfo = verificationInfo;
13007            this.packageAbiOverride = packageAbiOverride;
13008            this.grantedRuntimePermissions = grantedPermissions;
13009            this.certificates = certificates;
13010        }
13011
13012        @Override
13013        public String toString() {
13014            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
13015                    + " file=" + origin.file + " cid=" + origin.cid + "}";
13016        }
13017
13018        private int installLocationPolicy(PackageInfoLite pkgLite) {
13019            String packageName = pkgLite.packageName;
13020            int installLocation = pkgLite.installLocation;
13021            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13022            // reader
13023            synchronized (mPackages) {
13024                // Currently installed package which the new package is attempting to replace or
13025                // null if no such package is installed.
13026                PackageParser.Package installedPkg = mPackages.get(packageName);
13027                // Package which currently owns the data which the new package will own if installed.
13028                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
13029                // will be null whereas dataOwnerPkg will contain information about the package
13030                // which was uninstalled while keeping its data.
13031                PackageParser.Package dataOwnerPkg = installedPkg;
13032                if (dataOwnerPkg  == null) {
13033                    PackageSetting ps = mSettings.mPackages.get(packageName);
13034                    if (ps != null) {
13035                        dataOwnerPkg = ps.pkg;
13036                    }
13037                }
13038
13039                if (dataOwnerPkg != null) {
13040                    // If installed, the package will get access to data left on the device by its
13041                    // predecessor. As a security measure, this is permited only if this is not a
13042                    // version downgrade or if the predecessor package is marked as debuggable and
13043                    // a downgrade is explicitly requested.
13044                    //
13045                    // On debuggable platform builds, downgrades are permitted even for
13046                    // non-debuggable packages to make testing easier. Debuggable platform builds do
13047                    // not offer security guarantees and thus it's OK to disable some security
13048                    // mechanisms to make debugging/testing easier on those builds. However, even on
13049                    // debuggable builds downgrades of packages are permitted only if requested via
13050                    // installFlags. This is because we aim to keep the behavior of debuggable
13051                    // platform builds as close as possible to the behavior of non-debuggable
13052                    // platform builds.
13053                    final boolean downgradeRequested =
13054                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
13055                    final boolean packageDebuggable =
13056                                (dataOwnerPkg.applicationInfo.flags
13057                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
13058                    final boolean downgradePermitted =
13059                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
13060                    if (!downgradePermitted) {
13061                        try {
13062                            checkDowngrade(dataOwnerPkg, pkgLite);
13063                        } catch (PackageManagerException e) {
13064                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
13065                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
13066                        }
13067                    }
13068                }
13069
13070                if (installedPkg != null) {
13071                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13072                        // Check for updated system application.
13073                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13074                            if (onSd) {
13075                                Slog.w(TAG, "Cannot install update to system app on sdcard");
13076                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
13077                            }
13078                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13079                        } else {
13080                            if (onSd) {
13081                                // Install flag overrides everything.
13082                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13083                            }
13084                            // If current upgrade specifies particular preference
13085                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
13086                                // Application explicitly specified internal.
13087                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13088                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
13089                                // App explictly prefers external. Let policy decide
13090                            } else {
13091                                // Prefer previous location
13092                                if (isExternal(installedPkg)) {
13093                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13094                                }
13095                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13096                            }
13097                        }
13098                    } else {
13099                        // Invalid install. Return error code
13100                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
13101                    }
13102                }
13103            }
13104            // All the special cases have been taken care of.
13105            // Return result based on recommended install location.
13106            if (onSd) {
13107                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13108            }
13109            return pkgLite.recommendedInstallLocation;
13110        }
13111
13112        /*
13113         * Invoke remote method to get package information and install
13114         * location values. Override install location based on default
13115         * policy if needed and then create install arguments based
13116         * on the install location.
13117         */
13118        public void handleStartCopy() throws RemoteException {
13119            int ret = PackageManager.INSTALL_SUCCEEDED;
13120
13121            // If we're already staged, we've firmly committed to an install location
13122            if (origin.staged) {
13123                if (origin.file != null) {
13124                    installFlags |= PackageManager.INSTALL_INTERNAL;
13125                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13126                } else if (origin.cid != null) {
13127                    installFlags |= PackageManager.INSTALL_EXTERNAL;
13128                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
13129                } else {
13130                    throw new IllegalStateException("Invalid stage location");
13131                }
13132            }
13133
13134            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13135            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
13136            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13137            PackageInfoLite pkgLite = null;
13138
13139            if (onInt && onSd) {
13140                // Check if both bits are set.
13141                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
13142                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13143            } else if (onSd && ephemeral) {
13144                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
13145                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13146            } else {
13147                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13148                        packageAbiOverride);
13149
13150                if (DEBUG_EPHEMERAL && ephemeral) {
13151                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
13152                }
13153
13154                /*
13155                 * If we have too little free space, try to free cache
13156                 * before giving up.
13157                 */
13158                if (!origin.staged && pkgLite.recommendedInstallLocation
13159                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13160                    // TODO: focus freeing disk space on the target device
13161                    final StorageManager storage = StorageManager.from(mContext);
13162                    final long lowThreshold = storage.getStorageLowBytes(
13163                            Environment.getDataDirectory());
13164
13165                    final long sizeBytes = mContainerService.calculateInstalledSize(
13166                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13167
13168                    try {
13169                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
13170                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13171                                installFlags, packageAbiOverride);
13172                    } catch (InstallerException e) {
13173                        Slog.w(TAG, "Failed to free cache", e);
13174                    }
13175
13176                    /*
13177                     * The cache free must have deleted the file we
13178                     * downloaded to install.
13179                     *
13180                     * TODO: fix the "freeCache" call to not delete
13181                     *       the file we care about.
13182                     */
13183                    if (pkgLite.recommendedInstallLocation
13184                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13185                        pkgLite.recommendedInstallLocation
13186                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13187                    }
13188                }
13189            }
13190
13191            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13192                int loc = pkgLite.recommendedInstallLocation;
13193                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13194                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13195                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13196                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13197                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13198                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13199                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13200                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13201                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13202                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13203                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13204                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13205                } else {
13206                    // Override with defaults if needed.
13207                    loc = installLocationPolicy(pkgLite);
13208                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13209                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13210                    } else if (!onSd && !onInt) {
13211                        // Override install location with flags
13212                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13213                            // Set the flag to install on external media.
13214                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13215                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13216                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13217                            if (DEBUG_EPHEMERAL) {
13218                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13219                            }
13220                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13221                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13222                                    |PackageManager.INSTALL_INTERNAL);
13223                        } else {
13224                            // Make sure the flag for installing on external
13225                            // media is unset
13226                            installFlags |= PackageManager.INSTALL_INTERNAL;
13227                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13228                        }
13229                    }
13230                }
13231            }
13232
13233            final InstallArgs args = createInstallArgs(this);
13234            mArgs = args;
13235
13236            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13237                // TODO: http://b/22976637
13238                // Apps installed for "all" users use the device owner to verify the app
13239                UserHandle verifierUser = getUser();
13240                if (verifierUser == UserHandle.ALL) {
13241                    verifierUser = UserHandle.SYSTEM;
13242                }
13243
13244                /*
13245                 * Determine if we have any installed package verifiers. If we
13246                 * do, then we'll defer to them to verify the packages.
13247                 */
13248                final int requiredUid = mRequiredVerifierPackage == null ? -1
13249                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13250                                verifierUser.getIdentifier());
13251                if (!origin.existing && requiredUid != -1
13252                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13253                    final Intent verification = new Intent(
13254                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13255                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13256                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13257                            PACKAGE_MIME_TYPE);
13258                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13259
13260                    // Query all live verifiers based on current user state
13261                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13262                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13263
13264                    if (DEBUG_VERIFY) {
13265                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13266                                + verification.toString() + " with " + pkgLite.verifiers.length
13267                                + " optional verifiers");
13268                    }
13269
13270                    final int verificationId = mPendingVerificationToken++;
13271
13272                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13273
13274                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13275                            installerPackageName);
13276
13277                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13278                            installFlags);
13279
13280                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13281                            pkgLite.packageName);
13282
13283                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13284                            pkgLite.versionCode);
13285
13286                    if (verificationInfo != null) {
13287                        if (verificationInfo.originatingUri != null) {
13288                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13289                                    verificationInfo.originatingUri);
13290                        }
13291                        if (verificationInfo.referrer != null) {
13292                            verification.putExtra(Intent.EXTRA_REFERRER,
13293                                    verificationInfo.referrer);
13294                        }
13295                        if (verificationInfo.originatingUid >= 0) {
13296                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13297                                    verificationInfo.originatingUid);
13298                        }
13299                        if (verificationInfo.installerUid >= 0) {
13300                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13301                                    verificationInfo.installerUid);
13302                        }
13303                    }
13304
13305                    final PackageVerificationState verificationState = new PackageVerificationState(
13306                            requiredUid, args);
13307
13308                    mPendingVerification.append(verificationId, verificationState);
13309
13310                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13311                            receivers, verificationState);
13312
13313                    /*
13314                     * If any sufficient verifiers were listed in the package
13315                     * manifest, attempt to ask them.
13316                     */
13317                    if (sufficientVerifiers != null) {
13318                        final int N = sufficientVerifiers.size();
13319                        if (N == 0) {
13320                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13321                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13322                        } else {
13323                            for (int i = 0; i < N; i++) {
13324                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13325
13326                                final Intent sufficientIntent = new Intent(verification);
13327                                sufficientIntent.setComponent(verifierComponent);
13328                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13329                            }
13330                        }
13331                    }
13332
13333                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13334                            mRequiredVerifierPackage, receivers);
13335                    if (ret == PackageManager.INSTALL_SUCCEEDED
13336                            && mRequiredVerifierPackage != null) {
13337                        Trace.asyncTraceBegin(
13338                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13339                        /*
13340                         * Send the intent to the required verification agent,
13341                         * but only start the verification timeout after the
13342                         * target BroadcastReceivers have run.
13343                         */
13344                        verification.setComponent(requiredVerifierComponent);
13345                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13346                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13347                                new BroadcastReceiver() {
13348                                    @Override
13349                                    public void onReceive(Context context, Intent intent) {
13350                                        final Message msg = mHandler
13351                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13352                                        msg.arg1 = verificationId;
13353                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13354                                    }
13355                                }, null, 0, null, null);
13356
13357                        /*
13358                         * We don't want the copy to proceed until verification
13359                         * succeeds, so null out this field.
13360                         */
13361                        mArgs = null;
13362                    }
13363                } else {
13364                    /*
13365                     * No package verification is enabled, so immediately start
13366                     * the remote call to initiate copy using temporary file.
13367                     */
13368                    ret = args.copyApk(mContainerService, true);
13369                }
13370            }
13371
13372            mRet = ret;
13373        }
13374
13375        @Override
13376        void handleReturnCode() {
13377            // If mArgs is null, then MCS couldn't be reached. When it
13378            // reconnects, it will try again to install. At that point, this
13379            // will succeed.
13380            if (mArgs != null) {
13381                processPendingInstall(mArgs, mRet);
13382            }
13383        }
13384
13385        @Override
13386        void handleServiceError() {
13387            mArgs = createInstallArgs(this);
13388            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13389        }
13390
13391        public boolean isForwardLocked() {
13392            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13393        }
13394    }
13395
13396    /**
13397     * Used during creation of InstallArgs
13398     *
13399     * @param installFlags package installation flags
13400     * @return true if should be installed on external storage
13401     */
13402    private static boolean installOnExternalAsec(int installFlags) {
13403        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13404            return false;
13405        }
13406        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13407            return true;
13408        }
13409        return false;
13410    }
13411
13412    /**
13413     * Used during creation of InstallArgs
13414     *
13415     * @param installFlags package installation flags
13416     * @return true if should be installed as forward locked
13417     */
13418    private static boolean installForwardLocked(int installFlags) {
13419        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13420    }
13421
13422    private InstallArgs createInstallArgs(InstallParams params) {
13423        if (params.move != null) {
13424            return new MoveInstallArgs(params);
13425        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13426            return new AsecInstallArgs(params);
13427        } else {
13428            return new FileInstallArgs(params);
13429        }
13430    }
13431
13432    /**
13433     * Create args that describe an existing installed package. Typically used
13434     * when cleaning up old installs, or used as a move source.
13435     */
13436    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13437            String resourcePath, String[] instructionSets) {
13438        final boolean isInAsec;
13439        if (installOnExternalAsec(installFlags)) {
13440            /* Apps on SD card are always in ASEC containers. */
13441            isInAsec = true;
13442        } else if (installForwardLocked(installFlags)
13443                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13444            /*
13445             * Forward-locked apps are only in ASEC containers if they're the
13446             * new style
13447             */
13448            isInAsec = true;
13449        } else {
13450            isInAsec = false;
13451        }
13452
13453        if (isInAsec) {
13454            return new AsecInstallArgs(codePath, instructionSets,
13455                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13456        } else {
13457            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13458        }
13459    }
13460
13461    static abstract class InstallArgs {
13462        /** @see InstallParams#origin */
13463        final OriginInfo origin;
13464        /** @see InstallParams#move */
13465        final MoveInfo move;
13466
13467        final IPackageInstallObserver2 observer;
13468        // Always refers to PackageManager flags only
13469        final int installFlags;
13470        final String installerPackageName;
13471        final String volumeUuid;
13472        final UserHandle user;
13473        final String abiOverride;
13474        final String[] installGrantPermissions;
13475        /** If non-null, drop an async trace when the install completes */
13476        final String traceMethod;
13477        final int traceCookie;
13478        final Certificate[][] certificates;
13479
13480        // The list of instruction sets supported by this app. This is currently
13481        // only used during the rmdex() phase to clean up resources. We can get rid of this
13482        // if we move dex files under the common app path.
13483        /* nullable */ String[] instructionSets;
13484
13485        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13486                int installFlags, String installerPackageName, String volumeUuid,
13487                UserHandle user, String[] instructionSets,
13488                String abiOverride, String[] installGrantPermissions,
13489                String traceMethod, int traceCookie, Certificate[][] certificates) {
13490            this.origin = origin;
13491            this.move = move;
13492            this.installFlags = installFlags;
13493            this.observer = observer;
13494            this.installerPackageName = installerPackageName;
13495            this.volumeUuid = volumeUuid;
13496            this.user = user;
13497            this.instructionSets = instructionSets;
13498            this.abiOverride = abiOverride;
13499            this.installGrantPermissions = installGrantPermissions;
13500            this.traceMethod = traceMethod;
13501            this.traceCookie = traceCookie;
13502            this.certificates = certificates;
13503        }
13504
13505        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13506        abstract int doPreInstall(int status);
13507
13508        /**
13509         * Rename package into final resting place. All paths on the given
13510         * scanned package should be updated to reflect the rename.
13511         */
13512        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13513        abstract int doPostInstall(int status, int uid);
13514
13515        /** @see PackageSettingBase#codePathString */
13516        abstract String getCodePath();
13517        /** @see PackageSettingBase#resourcePathString */
13518        abstract String getResourcePath();
13519
13520        // Need installer lock especially for dex file removal.
13521        abstract void cleanUpResourcesLI();
13522        abstract boolean doPostDeleteLI(boolean delete);
13523
13524        /**
13525         * Called before the source arguments are copied. This is used mostly
13526         * for MoveParams when it needs to read the source file to put it in the
13527         * destination.
13528         */
13529        int doPreCopy() {
13530            return PackageManager.INSTALL_SUCCEEDED;
13531        }
13532
13533        /**
13534         * Called after the source arguments are copied. This is used mostly for
13535         * MoveParams when it needs to read the source file to put it in the
13536         * destination.
13537         */
13538        int doPostCopy(int uid) {
13539            return PackageManager.INSTALL_SUCCEEDED;
13540        }
13541
13542        protected boolean isFwdLocked() {
13543            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13544        }
13545
13546        protected boolean isExternalAsec() {
13547            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13548        }
13549
13550        protected boolean isEphemeral() {
13551            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13552        }
13553
13554        UserHandle getUser() {
13555            return user;
13556        }
13557    }
13558
13559    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13560        if (!allCodePaths.isEmpty()) {
13561            if (instructionSets == null) {
13562                throw new IllegalStateException("instructionSet == null");
13563            }
13564            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13565            for (String codePath : allCodePaths) {
13566                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13567                    try {
13568                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13569                    } catch (InstallerException ignored) {
13570                    }
13571                }
13572            }
13573        }
13574    }
13575
13576    /**
13577     * Logic to handle installation of non-ASEC applications, including copying
13578     * and renaming logic.
13579     */
13580    class FileInstallArgs extends InstallArgs {
13581        private File codeFile;
13582        private File resourceFile;
13583
13584        // Example topology:
13585        // /data/app/com.example/base.apk
13586        // /data/app/com.example/split_foo.apk
13587        // /data/app/com.example/lib/arm/libfoo.so
13588        // /data/app/com.example/lib/arm64/libfoo.so
13589        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13590
13591        /** New install */
13592        FileInstallArgs(InstallParams params) {
13593            super(params.origin, params.move, params.observer, params.installFlags,
13594                    params.installerPackageName, params.volumeUuid,
13595                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13596                    params.grantedRuntimePermissions,
13597                    params.traceMethod, params.traceCookie, params.certificates);
13598            if (isFwdLocked()) {
13599                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13600            }
13601        }
13602
13603        /** Existing install */
13604        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13605            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13606                    null, null, null, 0, null /*certificates*/);
13607            this.codeFile = (codePath != null) ? new File(codePath) : null;
13608            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13609        }
13610
13611        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13612            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13613            try {
13614                return doCopyApk(imcs, temp);
13615            } finally {
13616                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13617            }
13618        }
13619
13620        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13621            if (origin.staged) {
13622                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13623                codeFile = origin.file;
13624                resourceFile = origin.file;
13625                return PackageManager.INSTALL_SUCCEEDED;
13626            }
13627
13628            try {
13629                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13630                final File tempDir =
13631                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13632                codeFile = tempDir;
13633                resourceFile = tempDir;
13634            } catch (IOException e) {
13635                Slog.w(TAG, "Failed to create copy file: " + e);
13636                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13637            }
13638
13639            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13640                @Override
13641                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13642                    if (!FileUtils.isValidExtFilename(name)) {
13643                        throw new IllegalArgumentException("Invalid filename: " + name);
13644                    }
13645                    try {
13646                        final File file = new File(codeFile, name);
13647                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13648                                O_RDWR | O_CREAT, 0644);
13649                        Os.chmod(file.getAbsolutePath(), 0644);
13650                        return new ParcelFileDescriptor(fd);
13651                    } catch (ErrnoException e) {
13652                        throw new RemoteException("Failed to open: " + e.getMessage());
13653                    }
13654                }
13655            };
13656
13657            int ret = PackageManager.INSTALL_SUCCEEDED;
13658            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13659            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13660                Slog.e(TAG, "Failed to copy package");
13661                return ret;
13662            }
13663
13664            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13665            NativeLibraryHelper.Handle handle = null;
13666            try {
13667                handle = NativeLibraryHelper.Handle.create(codeFile);
13668                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13669                        abiOverride);
13670            } catch (IOException e) {
13671                Slog.e(TAG, "Copying native libraries failed", e);
13672                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13673            } finally {
13674                IoUtils.closeQuietly(handle);
13675            }
13676
13677            return ret;
13678        }
13679
13680        int doPreInstall(int status) {
13681            if (status != PackageManager.INSTALL_SUCCEEDED) {
13682                cleanUp();
13683            }
13684            return status;
13685        }
13686
13687        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13688            if (status != PackageManager.INSTALL_SUCCEEDED) {
13689                cleanUp();
13690                return false;
13691            }
13692
13693            final File targetDir = codeFile.getParentFile();
13694            final File beforeCodeFile = codeFile;
13695            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13696
13697            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13698            try {
13699                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13700            } catch (ErrnoException e) {
13701                Slog.w(TAG, "Failed to rename", e);
13702                return false;
13703            }
13704
13705            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13706                Slog.w(TAG, "Failed to restorecon");
13707                return false;
13708            }
13709
13710            // Reflect the rename internally
13711            codeFile = afterCodeFile;
13712            resourceFile = afterCodeFile;
13713
13714            // Reflect the rename in scanned details
13715            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13716            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13717                    afterCodeFile, pkg.baseCodePath));
13718            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13719                    afterCodeFile, pkg.splitCodePaths));
13720
13721            // Reflect the rename in app info
13722            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13723            pkg.setApplicationInfoCodePath(pkg.codePath);
13724            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13725            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13726            pkg.setApplicationInfoResourcePath(pkg.codePath);
13727            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13728            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13729
13730            return true;
13731        }
13732
13733        int doPostInstall(int status, int uid) {
13734            if (status != PackageManager.INSTALL_SUCCEEDED) {
13735                cleanUp();
13736            }
13737            return status;
13738        }
13739
13740        @Override
13741        String getCodePath() {
13742            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13743        }
13744
13745        @Override
13746        String getResourcePath() {
13747            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13748        }
13749
13750        private boolean cleanUp() {
13751            if (codeFile == null || !codeFile.exists()) {
13752                return false;
13753            }
13754
13755            removeCodePathLI(codeFile);
13756
13757            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13758                resourceFile.delete();
13759            }
13760
13761            return true;
13762        }
13763
13764        void cleanUpResourcesLI() {
13765            // Try enumerating all code paths before deleting
13766            List<String> allCodePaths = Collections.EMPTY_LIST;
13767            if (codeFile != null && codeFile.exists()) {
13768                try {
13769                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13770                    allCodePaths = pkg.getAllCodePaths();
13771                } catch (PackageParserException e) {
13772                    // Ignored; we tried our best
13773                }
13774            }
13775
13776            cleanUp();
13777            removeDexFiles(allCodePaths, instructionSets);
13778        }
13779
13780        boolean doPostDeleteLI(boolean delete) {
13781            // XXX err, shouldn't we respect the delete flag?
13782            cleanUpResourcesLI();
13783            return true;
13784        }
13785    }
13786
13787    private boolean isAsecExternal(String cid) {
13788        final String asecPath = PackageHelper.getSdFilesystem(cid);
13789        return !asecPath.startsWith(mAsecInternalPath);
13790    }
13791
13792    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13793            PackageManagerException {
13794        if (copyRet < 0) {
13795            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13796                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13797                throw new PackageManagerException(copyRet, message);
13798            }
13799        }
13800    }
13801
13802    /**
13803     * Extract the MountService "container ID" from the full code path of an
13804     * .apk.
13805     */
13806    static String cidFromCodePath(String fullCodePath) {
13807        int eidx = fullCodePath.lastIndexOf("/");
13808        String subStr1 = fullCodePath.substring(0, eidx);
13809        int sidx = subStr1.lastIndexOf("/");
13810        return subStr1.substring(sidx+1, eidx);
13811    }
13812
13813    /**
13814     * Logic to handle installation of ASEC applications, including copying and
13815     * renaming logic.
13816     */
13817    class AsecInstallArgs extends InstallArgs {
13818        static final String RES_FILE_NAME = "pkg.apk";
13819        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13820
13821        String cid;
13822        String packagePath;
13823        String resourcePath;
13824
13825        /** New install */
13826        AsecInstallArgs(InstallParams params) {
13827            super(params.origin, params.move, params.observer, params.installFlags,
13828                    params.installerPackageName, params.volumeUuid,
13829                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13830                    params.grantedRuntimePermissions,
13831                    params.traceMethod, params.traceCookie, params.certificates);
13832        }
13833
13834        /** Existing install */
13835        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13836                        boolean isExternal, boolean isForwardLocked) {
13837            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13838              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13839                    instructionSets, null, null, null, 0, null /*certificates*/);
13840            // Hackily pretend we're still looking at a full code path
13841            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13842                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13843            }
13844
13845            // Extract cid from fullCodePath
13846            int eidx = fullCodePath.lastIndexOf("/");
13847            String subStr1 = fullCodePath.substring(0, eidx);
13848            int sidx = subStr1.lastIndexOf("/");
13849            cid = subStr1.substring(sidx+1, eidx);
13850            setMountPath(subStr1);
13851        }
13852
13853        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13854            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13855              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13856                    instructionSets, null, null, null, 0, null /*certificates*/);
13857            this.cid = cid;
13858            setMountPath(PackageHelper.getSdDir(cid));
13859        }
13860
13861        void createCopyFile() {
13862            cid = mInstallerService.allocateExternalStageCidLegacy();
13863        }
13864
13865        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13866            if (origin.staged && origin.cid != null) {
13867                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13868                cid = origin.cid;
13869                setMountPath(PackageHelper.getSdDir(cid));
13870                return PackageManager.INSTALL_SUCCEEDED;
13871            }
13872
13873            if (temp) {
13874                createCopyFile();
13875            } else {
13876                /*
13877                 * Pre-emptively destroy the container since it's destroyed if
13878                 * copying fails due to it existing anyway.
13879                 */
13880                PackageHelper.destroySdDir(cid);
13881            }
13882
13883            final String newMountPath = imcs.copyPackageToContainer(
13884                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13885                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13886
13887            if (newMountPath != null) {
13888                setMountPath(newMountPath);
13889                return PackageManager.INSTALL_SUCCEEDED;
13890            } else {
13891                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13892            }
13893        }
13894
13895        @Override
13896        String getCodePath() {
13897            return packagePath;
13898        }
13899
13900        @Override
13901        String getResourcePath() {
13902            return resourcePath;
13903        }
13904
13905        int doPreInstall(int status) {
13906            if (status != PackageManager.INSTALL_SUCCEEDED) {
13907                // Destroy container
13908                PackageHelper.destroySdDir(cid);
13909            } else {
13910                boolean mounted = PackageHelper.isContainerMounted(cid);
13911                if (!mounted) {
13912                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13913                            Process.SYSTEM_UID);
13914                    if (newMountPath != null) {
13915                        setMountPath(newMountPath);
13916                    } else {
13917                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13918                    }
13919                }
13920            }
13921            return status;
13922        }
13923
13924        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13925            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13926            String newMountPath = null;
13927            if (PackageHelper.isContainerMounted(cid)) {
13928                // Unmount the container
13929                if (!PackageHelper.unMountSdDir(cid)) {
13930                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13931                    return false;
13932                }
13933            }
13934            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13935                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13936                        " which might be stale. Will try to clean up.");
13937                // Clean up the stale container and proceed to recreate.
13938                if (!PackageHelper.destroySdDir(newCacheId)) {
13939                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13940                    return false;
13941                }
13942                // Successfully cleaned up stale container. Try to rename again.
13943                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13944                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13945                            + " inspite of cleaning it up.");
13946                    return false;
13947                }
13948            }
13949            if (!PackageHelper.isContainerMounted(newCacheId)) {
13950                Slog.w(TAG, "Mounting container " + newCacheId);
13951                newMountPath = PackageHelper.mountSdDir(newCacheId,
13952                        getEncryptKey(), Process.SYSTEM_UID);
13953            } else {
13954                newMountPath = PackageHelper.getSdDir(newCacheId);
13955            }
13956            if (newMountPath == null) {
13957                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13958                return false;
13959            }
13960            Log.i(TAG, "Succesfully renamed " + cid +
13961                    " to " + newCacheId +
13962                    " at new path: " + newMountPath);
13963            cid = newCacheId;
13964
13965            final File beforeCodeFile = new File(packagePath);
13966            setMountPath(newMountPath);
13967            final File afterCodeFile = new File(packagePath);
13968
13969            // Reflect the rename in scanned details
13970            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13971            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13972                    afterCodeFile, pkg.baseCodePath));
13973            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13974                    afterCodeFile, pkg.splitCodePaths));
13975
13976            // Reflect the rename in app info
13977            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13978            pkg.setApplicationInfoCodePath(pkg.codePath);
13979            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13980            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13981            pkg.setApplicationInfoResourcePath(pkg.codePath);
13982            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13983            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13984
13985            return true;
13986        }
13987
13988        private void setMountPath(String mountPath) {
13989            final File mountFile = new File(mountPath);
13990
13991            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13992            if (monolithicFile.exists()) {
13993                packagePath = monolithicFile.getAbsolutePath();
13994                if (isFwdLocked()) {
13995                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13996                } else {
13997                    resourcePath = packagePath;
13998                }
13999            } else {
14000                packagePath = mountFile.getAbsolutePath();
14001                resourcePath = packagePath;
14002            }
14003        }
14004
14005        int doPostInstall(int status, int uid) {
14006            if (status != PackageManager.INSTALL_SUCCEEDED) {
14007                cleanUp();
14008            } else {
14009                final int groupOwner;
14010                final String protectedFile;
14011                if (isFwdLocked()) {
14012                    groupOwner = UserHandle.getSharedAppGid(uid);
14013                    protectedFile = RES_FILE_NAME;
14014                } else {
14015                    groupOwner = -1;
14016                    protectedFile = null;
14017                }
14018
14019                if (uid < Process.FIRST_APPLICATION_UID
14020                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
14021                    Slog.e(TAG, "Failed to finalize " + cid);
14022                    PackageHelper.destroySdDir(cid);
14023                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14024                }
14025
14026                boolean mounted = PackageHelper.isContainerMounted(cid);
14027                if (!mounted) {
14028                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
14029                }
14030            }
14031            return status;
14032        }
14033
14034        private void cleanUp() {
14035            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
14036
14037            // Destroy secure container
14038            PackageHelper.destroySdDir(cid);
14039        }
14040
14041        private List<String> getAllCodePaths() {
14042            final File codeFile = new File(getCodePath());
14043            if (codeFile != null && codeFile.exists()) {
14044                try {
14045                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14046                    return pkg.getAllCodePaths();
14047                } catch (PackageParserException e) {
14048                    // Ignored; we tried our best
14049                }
14050            }
14051            return Collections.EMPTY_LIST;
14052        }
14053
14054        void cleanUpResourcesLI() {
14055            // Enumerate all code paths before deleting
14056            cleanUpResourcesLI(getAllCodePaths());
14057        }
14058
14059        private void cleanUpResourcesLI(List<String> allCodePaths) {
14060            cleanUp();
14061            removeDexFiles(allCodePaths, instructionSets);
14062        }
14063
14064        String getPackageName() {
14065            return getAsecPackageName(cid);
14066        }
14067
14068        boolean doPostDeleteLI(boolean delete) {
14069            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
14070            final List<String> allCodePaths = getAllCodePaths();
14071            boolean mounted = PackageHelper.isContainerMounted(cid);
14072            if (mounted) {
14073                // Unmount first
14074                if (PackageHelper.unMountSdDir(cid)) {
14075                    mounted = false;
14076                }
14077            }
14078            if (!mounted && delete) {
14079                cleanUpResourcesLI(allCodePaths);
14080            }
14081            return !mounted;
14082        }
14083
14084        @Override
14085        int doPreCopy() {
14086            if (isFwdLocked()) {
14087                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
14088                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
14089                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14090                }
14091            }
14092
14093            return PackageManager.INSTALL_SUCCEEDED;
14094        }
14095
14096        @Override
14097        int doPostCopy(int uid) {
14098            if (isFwdLocked()) {
14099                if (uid < Process.FIRST_APPLICATION_UID
14100                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
14101                                RES_FILE_NAME)) {
14102                    Slog.e(TAG, "Failed to finalize " + cid);
14103                    PackageHelper.destroySdDir(cid);
14104                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14105                }
14106            }
14107
14108            return PackageManager.INSTALL_SUCCEEDED;
14109        }
14110    }
14111
14112    /**
14113     * Logic to handle movement of existing installed applications.
14114     */
14115    class MoveInstallArgs extends InstallArgs {
14116        private File codeFile;
14117        private File resourceFile;
14118
14119        /** New install */
14120        MoveInstallArgs(InstallParams params) {
14121            super(params.origin, params.move, params.observer, params.installFlags,
14122                    params.installerPackageName, params.volumeUuid,
14123                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14124                    params.grantedRuntimePermissions,
14125                    params.traceMethod, params.traceCookie, params.certificates);
14126        }
14127
14128        int copyApk(IMediaContainerService imcs, boolean temp) {
14129            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
14130                    + move.fromUuid + " to " + move.toUuid);
14131            synchronized (mInstaller) {
14132                try {
14133                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
14134                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
14135                } catch (InstallerException e) {
14136                    Slog.w(TAG, "Failed to move app", e);
14137                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14138                }
14139            }
14140
14141            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
14142            resourceFile = codeFile;
14143            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14144
14145            return PackageManager.INSTALL_SUCCEEDED;
14146        }
14147
14148        int doPreInstall(int status) {
14149            if (status != PackageManager.INSTALL_SUCCEEDED) {
14150                cleanUp(move.toUuid);
14151            }
14152            return status;
14153        }
14154
14155        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14156            if (status != PackageManager.INSTALL_SUCCEEDED) {
14157                cleanUp(move.toUuid);
14158                return false;
14159            }
14160
14161            // Reflect the move in app info
14162            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14163            pkg.setApplicationInfoCodePath(pkg.codePath);
14164            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14165            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14166            pkg.setApplicationInfoResourcePath(pkg.codePath);
14167            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14168            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14169
14170            return true;
14171        }
14172
14173        int doPostInstall(int status, int uid) {
14174            if (status == PackageManager.INSTALL_SUCCEEDED) {
14175                cleanUp(move.fromUuid);
14176            } else {
14177                cleanUp(move.toUuid);
14178            }
14179            return status;
14180        }
14181
14182        @Override
14183        String getCodePath() {
14184            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14185        }
14186
14187        @Override
14188        String getResourcePath() {
14189            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14190        }
14191
14192        private boolean cleanUp(String volumeUuid) {
14193            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14194                    move.dataAppName);
14195            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14196            final int[] userIds = sUserManager.getUserIds();
14197            synchronized (mInstallLock) {
14198                // Clean up both app data and code
14199                // All package moves are frozen until finished
14200                for (int userId : userIds) {
14201                    try {
14202                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14203                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14204                    } catch (InstallerException e) {
14205                        Slog.w(TAG, String.valueOf(e));
14206                    }
14207                }
14208                removeCodePathLI(codeFile);
14209            }
14210            return true;
14211        }
14212
14213        void cleanUpResourcesLI() {
14214            throw new UnsupportedOperationException();
14215        }
14216
14217        boolean doPostDeleteLI(boolean delete) {
14218            throw new UnsupportedOperationException();
14219        }
14220    }
14221
14222    static String getAsecPackageName(String packageCid) {
14223        int idx = packageCid.lastIndexOf("-");
14224        if (idx == -1) {
14225            return packageCid;
14226        }
14227        return packageCid.substring(0, idx);
14228    }
14229
14230    // Utility method used to create code paths based on package name and available index.
14231    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14232        String idxStr = "";
14233        int idx = 1;
14234        // Fall back to default value of idx=1 if prefix is not
14235        // part of oldCodePath
14236        if (oldCodePath != null) {
14237            String subStr = oldCodePath;
14238            // Drop the suffix right away
14239            if (suffix != null && subStr.endsWith(suffix)) {
14240                subStr = subStr.substring(0, subStr.length() - suffix.length());
14241            }
14242            // If oldCodePath already contains prefix find out the
14243            // ending index to either increment or decrement.
14244            int sidx = subStr.lastIndexOf(prefix);
14245            if (sidx != -1) {
14246                subStr = subStr.substring(sidx + prefix.length());
14247                if (subStr != null) {
14248                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14249                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14250                    }
14251                    try {
14252                        idx = Integer.parseInt(subStr);
14253                        if (idx <= 1) {
14254                            idx++;
14255                        } else {
14256                            idx--;
14257                        }
14258                    } catch(NumberFormatException e) {
14259                    }
14260                }
14261            }
14262        }
14263        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14264        return prefix + idxStr;
14265    }
14266
14267    private File getNextCodePath(File targetDir, String packageName) {
14268        int suffix = 1;
14269        File result;
14270        do {
14271            result = new File(targetDir, packageName + "-" + suffix);
14272            suffix++;
14273        } while (result.exists());
14274        return result;
14275    }
14276
14277    // Utility method that returns the relative package path with respect
14278    // to the installation directory. Like say for /data/data/com.test-1.apk
14279    // string com.test-1 is returned.
14280    static String deriveCodePathName(String codePath) {
14281        if (codePath == null) {
14282            return null;
14283        }
14284        final File codeFile = new File(codePath);
14285        final String name = codeFile.getName();
14286        if (codeFile.isDirectory()) {
14287            return name;
14288        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14289            final int lastDot = name.lastIndexOf('.');
14290            return name.substring(0, lastDot);
14291        } else {
14292            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14293            return null;
14294        }
14295    }
14296
14297    static class PackageInstalledInfo {
14298        String name;
14299        int uid;
14300        // The set of users that originally had this package installed.
14301        int[] origUsers;
14302        // The set of users that now have this package installed.
14303        int[] newUsers;
14304        PackageParser.Package pkg;
14305        int returnCode;
14306        String returnMsg;
14307        PackageRemovedInfo removedInfo;
14308        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14309
14310        public void setError(int code, String msg) {
14311            setReturnCode(code);
14312            setReturnMessage(msg);
14313            Slog.w(TAG, msg);
14314        }
14315
14316        public void setError(String msg, PackageParserException e) {
14317            setReturnCode(e.error);
14318            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14319            Slog.w(TAG, msg, e);
14320        }
14321
14322        public void setError(String msg, PackageManagerException e) {
14323            returnCode = e.error;
14324            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14325            Slog.w(TAG, msg, e);
14326        }
14327
14328        public void setReturnCode(int returnCode) {
14329            this.returnCode = returnCode;
14330            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14331            for (int i = 0; i < childCount; i++) {
14332                addedChildPackages.valueAt(i).returnCode = returnCode;
14333            }
14334        }
14335
14336        private void setReturnMessage(String returnMsg) {
14337            this.returnMsg = returnMsg;
14338            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14339            for (int i = 0; i < childCount; i++) {
14340                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14341            }
14342        }
14343
14344        // In some error cases we want to convey more info back to the observer
14345        String origPackage;
14346        String origPermission;
14347    }
14348
14349    /*
14350     * Install a non-existing package.
14351     */
14352    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14353            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14354            PackageInstalledInfo res) {
14355        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14356
14357        // Remember this for later, in case we need to rollback this install
14358        String pkgName = pkg.packageName;
14359
14360        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14361
14362        synchronized(mPackages) {
14363            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
14364            if (renamedPackage != null) {
14365                // A package with the same name is already installed, though
14366                // it has been renamed to an older name.  The package we
14367                // are trying to install should be installed as an update to
14368                // the existing one, but that has not been requested, so bail.
14369                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14370                        + " without first uninstalling package running as "
14371                        + renamedPackage);
14372                return;
14373            }
14374            if (mPackages.containsKey(pkgName)) {
14375                // Don't allow installation over an existing package with the same name.
14376                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14377                        + " without first uninstalling.");
14378                return;
14379            }
14380        }
14381
14382        try {
14383            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14384                    System.currentTimeMillis(), user);
14385
14386            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14387
14388            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14389                prepareAppDataAfterInstallLIF(newPackage);
14390
14391            } else {
14392                // Remove package from internal structures, but keep around any
14393                // data that might have already existed
14394                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14395                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14396            }
14397        } catch (PackageManagerException e) {
14398            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14399        }
14400
14401        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14402    }
14403
14404    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14405        // Can't rotate keys during boot or if sharedUser.
14406        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14407                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14408            return false;
14409        }
14410        // app is using upgradeKeySets; make sure all are valid
14411        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14412        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14413        for (int i = 0; i < upgradeKeySets.length; i++) {
14414            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14415                Slog.wtf(TAG, "Package "
14416                         + (oldPs.name != null ? oldPs.name : "<null>")
14417                         + " contains upgrade-key-set reference to unknown key-set: "
14418                         + upgradeKeySets[i]
14419                         + " reverting to signatures check.");
14420                return false;
14421            }
14422        }
14423        return true;
14424    }
14425
14426    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14427        // Upgrade keysets are being used.  Determine if new package has a superset of the
14428        // required keys.
14429        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14430        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14431        for (int i = 0; i < upgradeKeySets.length; i++) {
14432            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14433            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14434                return true;
14435            }
14436        }
14437        return false;
14438    }
14439
14440    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14441        try (DigestInputStream digestStream =
14442                new DigestInputStream(new FileInputStream(file), digest)) {
14443            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14444        }
14445    }
14446
14447    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14448            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14449        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14450
14451        final PackageParser.Package oldPackage;
14452        final String pkgName = pkg.packageName;
14453        final int[] allUsers;
14454        final int[] installedUsers;
14455
14456        synchronized(mPackages) {
14457            oldPackage = mPackages.get(pkgName);
14458            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14459
14460            // don't allow upgrade to target a release SDK from a pre-release SDK
14461            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14462                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14463            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14464                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14465            if (oldTargetsPreRelease
14466                    && !newTargetsPreRelease
14467                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14468                Slog.w(TAG, "Can't install package targeting released sdk");
14469                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14470                return;
14471            }
14472
14473            // don't allow an upgrade from full to ephemeral
14474            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14475            if (isEphemeral && !oldIsEphemeral) {
14476                // can't downgrade from full to ephemeral
14477                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14478                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14479                return;
14480            }
14481
14482            // verify signatures are valid
14483            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14484            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14485                if (!checkUpgradeKeySetLP(ps, pkg)) {
14486                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14487                            "New package not signed by keys specified by upgrade-keysets: "
14488                                    + pkgName);
14489                    return;
14490                }
14491            } else {
14492                // default to original signature matching
14493                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14494                        != PackageManager.SIGNATURE_MATCH) {
14495                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14496                            "New package has a different signature: " + pkgName);
14497                    return;
14498                }
14499            }
14500
14501            // don't allow a system upgrade unless the upgrade hash matches
14502            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14503                byte[] digestBytes = null;
14504                try {
14505                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14506                    updateDigest(digest, new File(pkg.baseCodePath));
14507                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14508                        for (String path : pkg.splitCodePaths) {
14509                            updateDigest(digest, new File(path));
14510                        }
14511                    }
14512                    digestBytes = digest.digest();
14513                } catch (NoSuchAlgorithmException | IOException e) {
14514                    res.setError(INSTALL_FAILED_INVALID_APK,
14515                            "Could not compute hash: " + pkgName);
14516                    return;
14517                }
14518                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14519                    res.setError(INSTALL_FAILED_INVALID_APK,
14520                            "New package fails restrict-update check: " + pkgName);
14521                    return;
14522                }
14523                // retain upgrade restriction
14524                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14525            }
14526
14527            // Check for shared user id changes
14528            String invalidPackageName =
14529                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14530            if (invalidPackageName != null) {
14531                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14532                        "Package " + invalidPackageName + " tried to change user "
14533                                + oldPackage.mSharedUserId);
14534                return;
14535            }
14536
14537            // In case of rollback, remember per-user/profile install state
14538            allUsers = sUserManager.getUserIds();
14539            installedUsers = ps.queryInstalledUsers(allUsers, true);
14540        }
14541
14542        // Update what is removed
14543        res.removedInfo = new PackageRemovedInfo();
14544        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14545        res.removedInfo.removedPackage = oldPackage.packageName;
14546        res.removedInfo.isUpdate = true;
14547        res.removedInfo.origUsers = installedUsers;
14548        final int childCount = (oldPackage.childPackages != null)
14549                ? oldPackage.childPackages.size() : 0;
14550        for (int i = 0; i < childCount; i++) {
14551            boolean childPackageUpdated = false;
14552            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14553            if (res.addedChildPackages != null) {
14554                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14555                if (childRes != null) {
14556                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14557                    childRes.removedInfo.removedPackage = childPkg.packageName;
14558                    childRes.removedInfo.isUpdate = true;
14559                    childPackageUpdated = true;
14560                }
14561            }
14562            if (!childPackageUpdated) {
14563                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14564                childRemovedRes.removedPackage = childPkg.packageName;
14565                childRemovedRes.isUpdate = false;
14566                childRemovedRes.dataRemoved = true;
14567                synchronized (mPackages) {
14568                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
14569                    if (childPs != null) {
14570                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14571                    }
14572                }
14573                if (res.removedInfo.removedChildPackages == null) {
14574                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14575                }
14576                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14577            }
14578        }
14579
14580        boolean sysPkg = (isSystemApp(oldPackage));
14581        if (sysPkg) {
14582            // Set the system/privileged flags as needed
14583            final boolean privileged =
14584                    (oldPackage.applicationInfo.privateFlags
14585                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14586            final int systemPolicyFlags = policyFlags
14587                    | PackageParser.PARSE_IS_SYSTEM
14588                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14589
14590            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14591                    user, allUsers, installerPackageName, res);
14592        } else {
14593            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14594                    user, allUsers, installerPackageName, res);
14595        }
14596    }
14597
14598    public List<String> getPreviousCodePaths(String packageName) {
14599        final PackageSetting ps = mSettings.mPackages.get(packageName);
14600        final List<String> result = new ArrayList<String>();
14601        if (ps != null && ps.oldCodePaths != null) {
14602            result.addAll(ps.oldCodePaths);
14603        }
14604        return result;
14605    }
14606
14607    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14608            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14609            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14610        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14611                + deletedPackage);
14612
14613        String pkgName = deletedPackage.packageName;
14614        boolean deletedPkg = true;
14615        boolean addedPkg = false;
14616        boolean updatedSettings = false;
14617        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14618        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14619                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14620
14621        final long origUpdateTime = (pkg.mExtras != null)
14622                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14623
14624        // First delete the existing package while retaining the data directory
14625        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14626                res.removedInfo, true, pkg)) {
14627            // If the existing package wasn't successfully deleted
14628            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14629            deletedPkg = false;
14630        } else {
14631            // Successfully deleted the old package; proceed with replace.
14632
14633            // If deleted package lived in a container, give users a chance to
14634            // relinquish resources before killing.
14635            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14636                if (DEBUG_INSTALL) {
14637                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14638                }
14639                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14640                final ArrayList<String> pkgList = new ArrayList<String>(1);
14641                pkgList.add(deletedPackage.applicationInfo.packageName);
14642                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14643            }
14644
14645            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14646                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14647            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14648
14649            try {
14650                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14651                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14652                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14653
14654                // Update the in-memory copy of the previous code paths.
14655                PackageSetting ps = mSettings.mPackages.get(pkgName);
14656                if (!killApp) {
14657                    if (ps.oldCodePaths == null) {
14658                        ps.oldCodePaths = new ArraySet<>();
14659                    }
14660                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14661                    if (deletedPackage.splitCodePaths != null) {
14662                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14663                    }
14664                } else {
14665                    ps.oldCodePaths = null;
14666                }
14667                if (ps.childPackageNames != null) {
14668                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14669                        final String childPkgName = ps.childPackageNames.get(i);
14670                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14671                        childPs.oldCodePaths = ps.oldCodePaths;
14672                    }
14673                }
14674                prepareAppDataAfterInstallLIF(newPackage);
14675                addedPkg = true;
14676            } catch (PackageManagerException e) {
14677                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14678            }
14679        }
14680
14681        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14682            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14683
14684            // Revert all internal state mutations and added folders for the failed install
14685            if (addedPkg) {
14686                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14687                        res.removedInfo, true, null);
14688            }
14689
14690            // Restore the old package
14691            if (deletedPkg) {
14692                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14693                File restoreFile = new File(deletedPackage.codePath);
14694                // Parse old package
14695                boolean oldExternal = isExternal(deletedPackage);
14696                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14697                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14698                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14699                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14700                try {
14701                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14702                            null);
14703                } catch (PackageManagerException e) {
14704                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14705                            + e.getMessage());
14706                    return;
14707                }
14708
14709                synchronized (mPackages) {
14710                    // Ensure the installer package name up to date
14711                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14712
14713                    // Update permissions for restored package
14714                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14715
14716                    mSettings.writeLPr();
14717                }
14718
14719                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14720            }
14721        } else {
14722            synchronized (mPackages) {
14723                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
14724                if (ps != null) {
14725                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14726                    if (res.removedInfo.removedChildPackages != null) {
14727                        final int childCount = res.removedInfo.removedChildPackages.size();
14728                        // Iterate in reverse as we may modify the collection
14729                        for (int i = childCount - 1; i >= 0; i--) {
14730                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14731                            if (res.addedChildPackages.containsKey(childPackageName)) {
14732                                res.removedInfo.removedChildPackages.removeAt(i);
14733                            } else {
14734                                PackageRemovedInfo childInfo = res.removedInfo
14735                                        .removedChildPackages.valueAt(i);
14736                                childInfo.removedForAllUsers = mPackages.get(
14737                                        childInfo.removedPackage) == null;
14738                            }
14739                        }
14740                    }
14741                }
14742            }
14743        }
14744    }
14745
14746    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14747            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14748            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14749        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14750                + ", old=" + deletedPackage);
14751
14752        final boolean disabledSystem;
14753
14754        // Remove existing system package
14755        removePackageLI(deletedPackage, true);
14756
14757        synchronized (mPackages) {
14758            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14759        }
14760        if (!disabledSystem) {
14761            // We didn't need to disable the .apk as a current system package,
14762            // which means we are replacing another update that is already
14763            // installed.  We need to make sure to delete the older one's .apk.
14764            res.removedInfo.args = createInstallArgsForExisting(0,
14765                    deletedPackage.applicationInfo.getCodePath(),
14766                    deletedPackage.applicationInfo.getResourcePath(),
14767                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14768        } else {
14769            res.removedInfo.args = null;
14770        }
14771
14772        // Successfully disabled the old package. Now proceed with re-installation
14773        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14774                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14775        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14776
14777        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14778        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14779                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14780
14781        PackageParser.Package newPackage = null;
14782        try {
14783            // Add the package to the internal data structures
14784            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14785
14786            // Set the update and install times
14787            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14788            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14789                    System.currentTimeMillis());
14790
14791            // Update the package dynamic state if succeeded
14792            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14793                // Now that the install succeeded make sure we remove data
14794                // directories for any child package the update removed.
14795                final int deletedChildCount = (deletedPackage.childPackages != null)
14796                        ? deletedPackage.childPackages.size() : 0;
14797                final int newChildCount = (newPackage.childPackages != null)
14798                        ? newPackage.childPackages.size() : 0;
14799                for (int i = 0; i < deletedChildCount; i++) {
14800                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14801                    boolean childPackageDeleted = true;
14802                    for (int j = 0; j < newChildCount; j++) {
14803                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14804                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14805                            childPackageDeleted = false;
14806                            break;
14807                        }
14808                    }
14809                    if (childPackageDeleted) {
14810                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14811                                deletedChildPkg.packageName);
14812                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14813                            PackageRemovedInfo removedChildRes = res.removedInfo
14814                                    .removedChildPackages.get(deletedChildPkg.packageName);
14815                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14816                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14817                        }
14818                    }
14819                }
14820
14821                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14822                prepareAppDataAfterInstallLIF(newPackage);
14823            }
14824        } catch (PackageManagerException e) {
14825            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14826            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14827        }
14828
14829        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14830            // Re installation failed. Restore old information
14831            // Remove new pkg information
14832            if (newPackage != null) {
14833                removeInstalledPackageLI(newPackage, true);
14834            }
14835            // Add back the old system package
14836            try {
14837                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14838            } catch (PackageManagerException e) {
14839                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14840            }
14841
14842            synchronized (mPackages) {
14843                if (disabledSystem) {
14844                    enableSystemPackageLPw(deletedPackage);
14845                }
14846
14847                // Ensure the installer package name up to date
14848                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14849
14850                // Update permissions for restored package
14851                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14852
14853                mSettings.writeLPr();
14854            }
14855
14856            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14857                    + " after failed upgrade");
14858        }
14859    }
14860
14861    /**
14862     * Checks whether the parent or any of the child packages have a change shared
14863     * user. For a package to be a valid update the shred users of the parent and
14864     * the children should match. We may later support changing child shared users.
14865     * @param oldPkg The updated package.
14866     * @param newPkg The update package.
14867     * @return The shared user that change between the versions.
14868     */
14869    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14870            PackageParser.Package newPkg) {
14871        // Check parent shared user
14872        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14873            return newPkg.packageName;
14874        }
14875        // Check child shared users
14876        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14877        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14878        for (int i = 0; i < newChildCount; i++) {
14879            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14880            // If this child was present, did it have the same shared user?
14881            for (int j = 0; j < oldChildCount; j++) {
14882                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14883                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14884                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14885                    return newChildPkg.packageName;
14886                }
14887            }
14888        }
14889        return null;
14890    }
14891
14892    private void removeNativeBinariesLI(PackageSetting ps) {
14893        // Remove the lib path for the parent package
14894        if (ps != null) {
14895            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14896            // Remove the lib path for the child packages
14897            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14898            for (int i = 0; i < childCount; i++) {
14899                PackageSetting childPs = null;
14900                synchronized (mPackages) {
14901                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
14902                }
14903                if (childPs != null) {
14904                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14905                            .legacyNativeLibraryPathString);
14906                }
14907            }
14908        }
14909    }
14910
14911    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14912        // Enable the parent package
14913        mSettings.enableSystemPackageLPw(pkg.packageName);
14914        // Enable the child packages
14915        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14916        for (int i = 0; i < childCount; i++) {
14917            PackageParser.Package childPkg = pkg.childPackages.get(i);
14918            mSettings.enableSystemPackageLPw(childPkg.packageName);
14919        }
14920    }
14921
14922    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14923            PackageParser.Package newPkg) {
14924        // Disable the parent package (parent always replaced)
14925        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14926        // Disable the child packages
14927        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14928        for (int i = 0; i < childCount; i++) {
14929            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14930            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14931            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14932        }
14933        return disabled;
14934    }
14935
14936    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14937            String installerPackageName) {
14938        // Enable the parent package
14939        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14940        // Enable the child packages
14941        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14942        for (int i = 0; i < childCount; i++) {
14943            PackageParser.Package childPkg = pkg.childPackages.get(i);
14944            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14945        }
14946    }
14947
14948    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14949        // Collect all used permissions in the UID
14950        ArraySet<String> usedPermissions = new ArraySet<>();
14951        final int packageCount = su.packages.size();
14952        for (int i = 0; i < packageCount; i++) {
14953            PackageSetting ps = su.packages.valueAt(i);
14954            if (ps.pkg == null) {
14955                continue;
14956            }
14957            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14958            for (int j = 0; j < requestedPermCount; j++) {
14959                String permission = ps.pkg.requestedPermissions.get(j);
14960                BasePermission bp = mSettings.mPermissions.get(permission);
14961                if (bp != null) {
14962                    usedPermissions.add(permission);
14963                }
14964            }
14965        }
14966
14967        PermissionsState permissionsState = su.getPermissionsState();
14968        // Prune install permissions
14969        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14970        final int installPermCount = installPermStates.size();
14971        for (int i = installPermCount - 1; i >= 0;  i--) {
14972            PermissionState permissionState = installPermStates.get(i);
14973            if (!usedPermissions.contains(permissionState.getName())) {
14974                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14975                if (bp != null) {
14976                    permissionsState.revokeInstallPermission(bp);
14977                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14978                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14979                }
14980            }
14981        }
14982
14983        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14984
14985        // Prune runtime permissions
14986        for (int userId : allUserIds) {
14987            List<PermissionState> runtimePermStates = permissionsState
14988                    .getRuntimePermissionStates(userId);
14989            final int runtimePermCount = runtimePermStates.size();
14990            for (int i = runtimePermCount - 1; i >= 0; i--) {
14991                PermissionState permissionState = runtimePermStates.get(i);
14992                if (!usedPermissions.contains(permissionState.getName())) {
14993                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14994                    if (bp != null) {
14995                        permissionsState.revokeRuntimePermission(bp, userId);
14996                        permissionsState.updatePermissionFlags(bp, userId,
14997                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14998                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14999                                runtimePermissionChangedUserIds, userId);
15000                    }
15001                }
15002            }
15003        }
15004
15005        return runtimePermissionChangedUserIds;
15006    }
15007
15008    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
15009            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
15010        // Update the parent package setting
15011        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
15012                res, user);
15013        // Update the child packages setting
15014        final int childCount = (newPackage.childPackages != null)
15015                ? newPackage.childPackages.size() : 0;
15016        for (int i = 0; i < childCount; i++) {
15017            PackageParser.Package childPackage = newPackage.childPackages.get(i);
15018            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
15019            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
15020                    childRes.origUsers, childRes, user);
15021        }
15022    }
15023
15024    private void updateSettingsInternalLI(PackageParser.Package newPackage,
15025            String installerPackageName, int[] allUsers, int[] installedForUsers,
15026            PackageInstalledInfo res, UserHandle user) {
15027        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
15028
15029        String pkgName = newPackage.packageName;
15030        synchronized (mPackages) {
15031            //write settings. the installStatus will be incomplete at this stage.
15032            //note that the new package setting would have already been
15033            //added to mPackages. It hasn't been persisted yet.
15034            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
15035            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15036            mSettings.writeLPr();
15037            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15038        }
15039
15040        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
15041        synchronized (mPackages) {
15042            updatePermissionsLPw(newPackage.packageName, newPackage,
15043                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
15044                            ? UPDATE_PERMISSIONS_ALL : 0));
15045            // For system-bundled packages, we assume that installing an upgraded version
15046            // of the package implies that the user actually wants to run that new code,
15047            // so we enable the package.
15048            PackageSetting ps = mSettings.mPackages.get(pkgName);
15049            final int userId = user.getIdentifier();
15050            if (ps != null) {
15051                if (isSystemApp(newPackage)) {
15052                    if (DEBUG_INSTALL) {
15053                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
15054                    }
15055                    // Enable system package for requested users
15056                    if (res.origUsers != null) {
15057                        for (int origUserId : res.origUsers) {
15058                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
15059                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
15060                                        origUserId, installerPackageName);
15061                            }
15062                        }
15063                    }
15064                    // Also convey the prior install/uninstall state
15065                    if (allUsers != null && installedForUsers != null) {
15066                        for (int currentUserId : allUsers) {
15067                            final boolean installed = ArrayUtils.contains(
15068                                    installedForUsers, currentUserId);
15069                            if (DEBUG_INSTALL) {
15070                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
15071                            }
15072                            ps.setInstalled(installed, currentUserId);
15073                        }
15074                        // these install state changes will be persisted in the
15075                        // upcoming call to mSettings.writeLPr().
15076                    }
15077                }
15078                // It's implied that when a user requests installation, they want the app to be
15079                // installed and enabled.
15080                if (userId != UserHandle.USER_ALL) {
15081                    ps.setInstalled(true, userId);
15082                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
15083                }
15084            }
15085            res.name = pkgName;
15086            res.uid = newPackage.applicationInfo.uid;
15087            res.pkg = newPackage;
15088            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
15089            mSettings.setInstallerPackageName(pkgName, installerPackageName);
15090            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15091            //to update install status
15092            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15093            mSettings.writeLPr();
15094            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15095        }
15096
15097        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15098    }
15099
15100    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
15101        try {
15102            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
15103            installPackageLI(args, res);
15104        } finally {
15105            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15106        }
15107    }
15108
15109    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
15110        final int installFlags = args.installFlags;
15111        final String installerPackageName = args.installerPackageName;
15112        final String volumeUuid = args.volumeUuid;
15113        final File tmpPackageFile = new File(args.getCodePath());
15114        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
15115        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
15116                || (args.volumeUuid != null));
15117        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
15118        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
15119        boolean replace = false;
15120        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
15121        if (args.move != null) {
15122            // moving a complete application; perform an initial scan on the new install location
15123            scanFlags |= SCAN_INITIAL;
15124        }
15125        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
15126            scanFlags |= SCAN_DONT_KILL_APP;
15127        }
15128
15129        // Result object to be returned
15130        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15131
15132        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
15133
15134        // Sanity check
15135        if (ephemeral && (forwardLocked || onExternal)) {
15136            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
15137                    + " external=" + onExternal);
15138            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15139            return;
15140        }
15141
15142        // Retrieve PackageSettings and parse package
15143        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15144                | PackageParser.PARSE_ENFORCE_CODE
15145                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15146                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15147                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15148                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15149        PackageParser pp = new PackageParser();
15150        pp.setSeparateProcesses(mSeparateProcesses);
15151        pp.setDisplayMetrics(mMetrics);
15152
15153        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15154        final PackageParser.Package pkg;
15155        try {
15156            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15157        } catch (PackageParserException e) {
15158            res.setError("Failed parse during installPackageLI", e);
15159            return;
15160        } finally {
15161            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15162        }
15163
15164        // If we are installing a clustered package add results for the children
15165        if (pkg.childPackages != null) {
15166            synchronized (mPackages) {
15167                final int childCount = pkg.childPackages.size();
15168                for (int i = 0; i < childCount; i++) {
15169                    PackageParser.Package childPkg = pkg.childPackages.get(i);
15170                    PackageInstalledInfo childRes = new PackageInstalledInfo();
15171                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15172                    childRes.pkg = childPkg;
15173                    childRes.name = childPkg.packageName;
15174                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15175                    if (childPs != null) {
15176                        childRes.origUsers = childPs.queryInstalledUsers(
15177                                sUserManager.getUserIds(), true);
15178                    }
15179                    if ((mPackages.containsKey(childPkg.packageName))) {
15180                        childRes.removedInfo = new PackageRemovedInfo();
15181                        childRes.removedInfo.removedPackage = childPkg.packageName;
15182                    }
15183                    if (res.addedChildPackages == null) {
15184                        res.addedChildPackages = new ArrayMap<>();
15185                    }
15186                    res.addedChildPackages.put(childPkg.packageName, childRes);
15187                }
15188            }
15189        }
15190
15191        // If package doesn't declare API override, mark that we have an install
15192        // time CPU ABI override.
15193        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15194            pkg.cpuAbiOverride = args.abiOverride;
15195        }
15196
15197        String pkgName = res.name = pkg.packageName;
15198        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15199            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15200                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15201                return;
15202            }
15203        }
15204
15205        try {
15206            // either use what we've been given or parse directly from the APK
15207            if (args.certificates != null) {
15208                try {
15209                    PackageParser.populateCertificates(pkg, args.certificates);
15210                } catch (PackageParserException e) {
15211                    // there was something wrong with the certificates we were given;
15212                    // try to pull them from the APK
15213                    PackageParser.collectCertificates(pkg, parseFlags);
15214                }
15215            } else {
15216                PackageParser.collectCertificates(pkg, parseFlags);
15217            }
15218        } catch (PackageParserException e) {
15219            res.setError("Failed collect during installPackageLI", e);
15220            return;
15221        }
15222
15223        // Get rid of all references to package scan path via parser.
15224        pp = null;
15225        String oldCodePath = null;
15226        boolean systemApp = false;
15227        synchronized (mPackages) {
15228            // Check if installing already existing package
15229            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15230                String oldName = mSettings.getRenamedPackageLPr(pkgName);
15231                if (pkg.mOriginalPackages != null
15232                        && pkg.mOriginalPackages.contains(oldName)
15233                        && mPackages.containsKey(oldName)) {
15234                    // This package is derived from an original package,
15235                    // and this device has been updating from that original
15236                    // name.  We must continue using the original name, so
15237                    // rename the new package here.
15238                    pkg.setPackageName(oldName);
15239                    pkgName = pkg.packageName;
15240                    replace = true;
15241                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15242                            + oldName + " pkgName=" + pkgName);
15243                } else if (mPackages.containsKey(pkgName)) {
15244                    // This package, under its official name, already exists
15245                    // on the device; we should replace it.
15246                    replace = true;
15247                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15248                }
15249
15250                // Child packages are installed through the parent package
15251                if (pkg.parentPackage != null) {
15252                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15253                            "Package " + pkg.packageName + " is child of package "
15254                                    + pkg.parentPackage.parentPackage + ". Child packages "
15255                                    + "can be updated only through the parent package.");
15256                    return;
15257                }
15258
15259                if (replace) {
15260                    // Prevent apps opting out from runtime permissions
15261                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15262                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15263                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15264                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15265                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15266                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15267                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15268                                        + " doesn't support runtime permissions but the old"
15269                                        + " target SDK " + oldTargetSdk + " does.");
15270                        return;
15271                    }
15272
15273                    // Prevent installing of child packages
15274                    if (oldPackage.parentPackage != null) {
15275                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15276                                "Package " + pkg.packageName + " is child of package "
15277                                        + oldPackage.parentPackage + ". Child packages "
15278                                        + "can be updated only through the parent package.");
15279                        return;
15280                    }
15281                }
15282            }
15283
15284            PackageSetting ps = mSettings.mPackages.get(pkgName);
15285            if (ps != null) {
15286                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15287
15288                // Quick sanity check that we're signed correctly if updating;
15289                // we'll check this again later when scanning, but we want to
15290                // bail early here before tripping over redefined permissions.
15291                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15292                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15293                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15294                                + pkg.packageName + " upgrade keys do not match the "
15295                                + "previously installed version");
15296                        return;
15297                    }
15298                } else {
15299                    try {
15300                        verifySignaturesLP(ps, pkg);
15301                    } catch (PackageManagerException e) {
15302                        res.setError(e.error, e.getMessage());
15303                        return;
15304                    }
15305                }
15306
15307                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15308                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15309                    systemApp = (ps.pkg.applicationInfo.flags &
15310                            ApplicationInfo.FLAG_SYSTEM) != 0;
15311                }
15312                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15313            }
15314
15315            // Check whether the newly-scanned package wants to define an already-defined perm
15316            int N = pkg.permissions.size();
15317            for (int i = N-1; i >= 0; i--) {
15318                PackageParser.Permission perm = pkg.permissions.get(i);
15319                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15320                if (bp != null) {
15321                    // If the defining package is signed with our cert, it's okay.  This
15322                    // also includes the "updating the same package" case, of course.
15323                    // "updating same package" could also involve key-rotation.
15324                    final boolean sigsOk;
15325                    if (bp.sourcePackage.equals(pkg.packageName)
15326                            && (bp.packageSetting instanceof PackageSetting)
15327                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15328                                    scanFlags))) {
15329                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15330                    } else {
15331                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15332                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15333                    }
15334                    if (!sigsOk) {
15335                        // If the owning package is the system itself, we log but allow
15336                        // install to proceed; we fail the install on all other permission
15337                        // redefinitions.
15338                        if (!bp.sourcePackage.equals("android")) {
15339                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15340                                    + pkg.packageName + " attempting to redeclare permission "
15341                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15342                            res.origPermission = perm.info.name;
15343                            res.origPackage = bp.sourcePackage;
15344                            return;
15345                        } else {
15346                            Slog.w(TAG, "Package " + pkg.packageName
15347                                    + " attempting to redeclare system permission "
15348                                    + perm.info.name + "; ignoring new declaration");
15349                            pkg.permissions.remove(i);
15350                        }
15351                    }
15352                }
15353            }
15354        }
15355
15356        if (systemApp) {
15357            if (onExternal) {
15358                // Abort update; system app can't be replaced with app on sdcard
15359                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15360                        "Cannot install updates to system apps on sdcard");
15361                return;
15362            } else if (ephemeral) {
15363                // Abort update; system app can't be replaced with an ephemeral app
15364                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15365                        "Cannot update a system app with an ephemeral app");
15366                return;
15367            }
15368        }
15369
15370        if (args.move != null) {
15371            // We did an in-place move, so dex is ready to roll
15372            scanFlags |= SCAN_NO_DEX;
15373            scanFlags |= SCAN_MOVE;
15374
15375            synchronized (mPackages) {
15376                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15377                if (ps == null) {
15378                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15379                            "Missing settings for moved package " + pkgName);
15380                }
15381
15382                // We moved the entire application as-is, so bring over the
15383                // previously derived ABI information.
15384                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15385                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15386            }
15387
15388        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15389            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15390            scanFlags |= SCAN_NO_DEX;
15391
15392            try {
15393                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15394                    args.abiOverride : pkg.cpuAbiOverride);
15395                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15396                        true /*extractLibs*/, mAppLib32InstallDir);
15397            } catch (PackageManagerException pme) {
15398                Slog.e(TAG, "Error deriving application ABI", pme);
15399                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15400                return;
15401            }
15402
15403            // Shared libraries for the package need to be updated.
15404            synchronized (mPackages) {
15405                try {
15406                    updateSharedLibrariesLPr(pkg, null);
15407                } catch (PackageManagerException e) {
15408                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15409                }
15410            }
15411            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15412            // Do not run PackageDexOptimizer through the local performDexOpt
15413            // method because `pkg` may not be in `mPackages` yet.
15414            //
15415            // Also, don't fail application installs if the dexopt step fails.
15416            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15417                    null /* instructionSets */, false /* checkProfiles */,
15418                    getCompilerFilterForReason(REASON_INSTALL),
15419                    getOrCreateCompilerPackageStats(pkg));
15420            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15421
15422            // Notify BackgroundDexOptService that the package has been changed.
15423            // If this is an update of a package which used to fail to compile,
15424            // BDOS will remove it from its blacklist.
15425            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15426        }
15427
15428        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15429            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15430            return;
15431        }
15432
15433        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15434
15435        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15436                "installPackageLI")) {
15437            if (replace) {
15438                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15439                        installerPackageName, res);
15440            } else {
15441                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15442                        args.user, installerPackageName, volumeUuid, res);
15443            }
15444        }
15445        synchronized (mPackages) {
15446            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15447            if (ps != null) {
15448                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15449            }
15450
15451            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15452            for (int i = 0; i < childCount; i++) {
15453                PackageParser.Package childPkg = pkg.childPackages.get(i);
15454                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15455                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15456                if (childPs != null) {
15457                    childRes.newUsers = childPs.queryInstalledUsers(
15458                            sUserManager.getUserIds(), true);
15459                }
15460            }
15461        }
15462    }
15463
15464    private void startIntentFilterVerifications(int userId, boolean replacing,
15465            PackageParser.Package pkg) {
15466        if (mIntentFilterVerifierComponent == null) {
15467            Slog.w(TAG, "No IntentFilter verification will not be done as "
15468                    + "there is no IntentFilterVerifier available!");
15469            return;
15470        }
15471
15472        final int verifierUid = getPackageUid(
15473                mIntentFilterVerifierComponent.getPackageName(),
15474                MATCH_DEBUG_TRIAGED_MISSING,
15475                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15476
15477        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15478        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15479        mHandler.sendMessage(msg);
15480
15481        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15482        for (int i = 0; i < childCount; i++) {
15483            PackageParser.Package childPkg = pkg.childPackages.get(i);
15484            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15485            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15486            mHandler.sendMessage(msg);
15487        }
15488    }
15489
15490    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15491            PackageParser.Package pkg) {
15492        int size = pkg.activities.size();
15493        if (size == 0) {
15494            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15495                    "No activity, so no need to verify any IntentFilter!");
15496            return;
15497        }
15498
15499        final boolean hasDomainURLs = hasDomainURLs(pkg);
15500        if (!hasDomainURLs) {
15501            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15502                    "No domain URLs, so no need to verify any IntentFilter!");
15503            return;
15504        }
15505
15506        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15507                + " if any IntentFilter from the " + size
15508                + " Activities needs verification ...");
15509
15510        int count = 0;
15511        final String packageName = pkg.packageName;
15512
15513        synchronized (mPackages) {
15514            // If this is a new install and we see that we've already run verification for this
15515            // package, we have nothing to do: it means the state was restored from backup.
15516            if (!replacing) {
15517                IntentFilterVerificationInfo ivi =
15518                        mSettings.getIntentFilterVerificationLPr(packageName);
15519                if (ivi != null) {
15520                    if (DEBUG_DOMAIN_VERIFICATION) {
15521                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15522                                + ivi.getStatusString());
15523                    }
15524                    return;
15525                }
15526            }
15527
15528            // If any filters need to be verified, then all need to be.
15529            boolean needToVerify = false;
15530            for (PackageParser.Activity a : pkg.activities) {
15531                for (ActivityIntentInfo filter : a.intents) {
15532                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15533                        if (DEBUG_DOMAIN_VERIFICATION) {
15534                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15535                        }
15536                        needToVerify = true;
15537                        break;
15538                    }
15539                }
15540            }
15541
15542            if (needToVerify) {
15543                final int verificationId = mIntentFilterVerificationToken++;
15544                for (PackageParser.Activity a : pkg.activities) {
15545                    for (ActivityIntentInfo filter : a.intents) {
15546                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15547                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15548                                    "Verification needed for IntentFilter:" + filter.toString());
15549                            mIntentFilterVerifier.addOneIntentFilterVerification(
15550                                    verifierUid, userId, verificationId, filter, packageName);
15551                            count++;
15552                        }
15553                    }
15554                }
15555            }
15556        }
15557
15558        if (count > 0) {
15559            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15560                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15561                    +  " for userId:" + userId);
15562            mIntentFilterVerifier.startVerifications(userId);
15563        } else {
15564            if (DEBUG_DOMAIN_VERIFICATION) {
15565                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15566            }
15567        }
15568    }
15569
15570    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15571        final ComponentName cn  = filter.activity.getComponentName();
15572        final String packageName = cn.getPackageName();
15573
15574        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15575                packageName);
15576        if (ivi == null) {
15577            return true;
15578        }
15579        int status = ivi.getStatus();
15580        switch (status) {
15581            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15582            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15583                return true;
15584
15585            default:
15586                // Nothing to do
15587                return false;
15588        }
15589    }
15590
15591    private static boolean isMultiArch(ApplicationInfo info) {
15592        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15593    }
15594
15595    private static boolean isExternal(PackageParser.Package pkg) {
15596        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15597    }
15598
15599    private static boolean isExternal(PackageSetting ps) {
15600        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15601    }
15602
15603    private static boolean isEphemeral(PackageParser.Package pkg) {
15604        return pkg.applicationInfo.isEphemeralApp();
15605    }
15606
15607    private static boolean isEphemeral(PackageSetting ps) {
15608        return ps.pkg != null && isEphemeral(ps.pkg);
15609    }
15610
15611    private static boolean isSystemApp(PackageParser.Package pkg) {
15612        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15613    }
15614
15615    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15616        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15617    }
15618
15619    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15620        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15621    }
15622
15623    private static boolean isSystemApp(PackageSetting ps) {
15624        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15625    }
15626
15627    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15628        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15629    }
15630
15631    private int packageFlagsToInstallFlags(PackageSetting ps) {
15632        int installFlags = 0;
15633        if (isEphemeral(ps)) {
15634            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15635        }
15636        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15637            // This existing package was an external ASEC install when we have
15638            // the external flag without a UUID
15639            installFlags |= PackageManager.INSTALL_EXTERNAL;
15640        }
15641        if (ps.isForwardLocked()) {
15642            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15643        }
15644        return installFlags;
15645    }
15646
15647    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15648        if (isExternal(pkg)) {
15649            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15650                return StorageManager.UUID_PRIMARY_PHYSICAL;
15651            } else {
15652                return pkg.volumeUuid;
15653            }
15654        } else {
15655            return StorageManager.UUID_PRIVATE_INTERNAL;
15656        }
15657    }
15658
15659    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15660        if (isExternal(pkg)) {
15661            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15662                return mSettings.getExternalVersion();
15663            } else {
15664                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15665            }
15666        } else {
15667            return mSettings.getInternalVersion();
15668        }
15669    }
15670
15671    private void deleteTempPackageFiles() {
15672        final FilenameFilter filter = new FilenameFilter() {
15673            public boolean accept(File dir, String name) {
15674                return name.startsWith("vmdl") && name.endsWith(".tmp");
15675            }
15676        };
15677        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15678            file.delete();
15679        }
15680    }
15681
15682    @Override
15683    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15684            int flags) {
15685        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15686                flags);
15687    }
15688
15689    @Override
15690    public void deletePackage(final String packageName,
15691            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15692        mContext.enforceCallingOrSelfPermission(
15693                android.Manifest.permission.DELETE_PACKAGES, null);
15694        Preconditions.checkNotNull(packageName);
15695        Preconditions.checkNotNull(observer);
15696        final int uid = Binder.getCallingUid();
15697        if (!isOrphaned(packageName)
15698                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15699            try {
15700                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15701                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15702                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15703                observer.onUserActionRequired(intent);
15704            } catch (RemoteException re) {
15705            }
15706            return;
15707        }
15708        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15709        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15710        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15711            mContext.enforceCallingOrSelfPermission(
15712                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15713                    "deletePackage for user " + userId);
15714        }
15715
15716        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15717            try {
15718                observer.onPackageDeleted(packageName,
15719                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15720            } catch (RemoteException re) {
15721            }
15722            return;
15723        }
15724
15725        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15726            try {
15727                observer.onPackageDeleted(packageName,
15728                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15729            } catch (RemoteException re) {
15730            }
15731            return;
15732        }
15733
15734        if (DEBUG_REMOVE) {
15735            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15736                    + " deleteAllUsers: " + deleteAllUsers );
15737        }
15738        // Queue up an async operation since the package deletion may take a little while.
15739        mHandler.post(new Runnable() {
15740            public void run() {
15741                mHandler.removeCallbacks(this);
15742                int returnCode;
15743                if (!deleteAllUsers) {
15744                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15745                } else {
15746                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15747                    // If nobody is blocking uninstall, proceed with delete for all users
15748                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15749                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15750                    } else {
15751                        // Otherwise uninstall individually for users with blockUninstalls=false
15752                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15753                        for (int userId : users) {
15754                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15755                                returnCode = deletePackageX(packageName, userId, userFlags);
15756                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15757                                    Slog.w(TAG, "Package delete failed for user " + userId
15758                                            + ", returnCode " + returnCode);
15759                                }
15760                            }
15761                        }
15762                        // The app has only been marked uninstalled for certain users.
15763                        // We still need to report that delete was blocked
15764                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15765                    }
15766                }
15767                try {
15768                    observer.onPackageDeleted(packageName, returnCode, null);
15769                } catch (RemoteException e) {
15770                    Log.i(TAG, "Observer no longer exists.");
15771                } //end catch
15772            } //end run
15773        });
15774    }
15775
15776    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15777        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15778              || callingUid == Process.SYSTEM_UID) {
15779            return true;
15780        }
15781        final int callingUserId = UserHandle.getUserId(callingUid);
15782        // If the caller installed the pkgName, then allow it to silently uninstall.
15783        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15784            return true;
15785        }
15786
15787        // Allow package verifier to silently uninstall.
15788        if (mRequiredVerifierPackage != null &&
15789                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15790            return true;
15791        }
15792
15793        // Allow package uninstaller to silently uninstall.
15794        if (mRequiredUninstallerPackage != null &&
15795                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15796            return true;
15797        }
15798
15799        // Allow storage manager to silently uninstall.
15800        if (mStorageManagerPackage != null &&
15801                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
15802            return true;
15803        }
15804        return false;
15805    }
15806
15807    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15808        int[] result = EMPTY_INT_ARRAY;
15809        for (int userId : userIds) {
15810            if (getBlockUninstallForUser(packageName, userId)) {
15811                result = ArrayUtils.appendInt(result, userId);
15812            }
15813        }
15814        return result;
15815    }
15816
15817    @Override
15818    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15819        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15820    }
15821
15822    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15823        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15824                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15825        try {
15826            if (dpm != null) {
15827                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15828                        /* callingUserOnly =*/ false);
15829                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15830                        : deviceOwnerComponentName.getPackageName();
15831                // Does the package contains the device owner?
15832                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15833                // this check is probably not needed, since DO should be registered as a device
15834                // admin on some user too. (Original bug for this: b/17657954)
15835                if (packageName.equals(deviceOwnerPackageName)) {
15836                    return true;
15837                }
15838                // Does it contain a device admin for any user?
15839                int[] users;
15840                if (userId == UserHandle.USER_ALL) {
15841                    users = sUserManager.getUserIds();
15842                } else {
15843                    users = new int[]{userId};
15844                }
15845                for (int i = 0; i < users.length; ++i) {
15846                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15847                        return true;
15848                    }
15849                }
15850            }
15851        } catch (RemoteException e) {
15852        }
15853        return false;
15854    }
15855
15856    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15857        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15858    }
15859
15860    /**
15861     *  This method is an internal method that could be get invoked either
15862     *  to delete an installed package or to clean up a failed installation.
15863     *  After deleting an installed package, a broadcast is sent to notify any
15864     *  listeners that the package has been removed. For cleaning up a failed
15865     *  installation, the broadcast is not necessary since the package's
15866     *  installation wouldn't have sent the initial broadcast either
15867     *  The key steps in deleting a package are
15868     *  deleting the package information in internal structures like mPackages,
15869     *  deleting the packages base directories through installd
15870     *  updating mSettings to reflect current status
15871     *  persisting settings for later use
15872     *  sending a broadcast if necessary
15873     */
15874    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15875        final PackageRemovedInfo info = new PackageRemovedInfo();
15876        final boolean res;
15877
15878        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15879                ? UserHandle.USER_ALL : userId;
15880
15881        if (isPackageDeviceAdmin(packageName, removeUser)) {
15882            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15883            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15884        }
15885
15886        PackageSetting uninstalledPs = null;
15887
15888        // for the uninstall-updates case and restricted profiles, remember the per-
15889        // user handle installed state
15890        int[] allUsers;
15891        synchronized (mPackages) {
15892            uninstalledPs = mSettings.mPackages.get(packageName);
15893            if (uninstalledPs == null) {
15894                Slog.w(TAG, "Not removing non-existent package " + packageName);
15895                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15896            }
15897            allUsers = sUserManager.getUserIds();
15898            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15899        }
15900
15901        final int freezeUser;
15902        if (isUpdatedSystemApp(uninstalledPs)
15903                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15904            // We're downgrading a system app, which will apply to all users, so
15905            // freeze them all during the downgrade
15906            freezeUser = UserHandle.USER_ALL;
15907        } else {
15908            freezeUser = removeUser;
15909        }
15910
15911        synchronized (mInstallLock) {
15912            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15913            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15914                    deleteFlags, "deletePackageX")) {
15915                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15916                        deleteFlags | REMOVE_CHATTY, info, true, null);
15917            }
15918            synchronized (mPackages) {
15919                if (res) {
15920                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15921                }
15922            }
15923        }
15924
15925        if (res) {
15926            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15927            info.sendPackageRemovedBroadcasts(killApp);
15928            info.sendSystemPackageUpdatedBroadcasts();
15929            info.sendSystemPackageAppearedBroadcasts();
15930        }
15931        // Force a gc here.
15932        Runtime.getRuntime().gc();
15933        // Delete the resources here after sending the broadcast to let
15934        // other processes clean up before deleting resources.
15935        if (info.args != null) {
15936            synchronized (mInstallLock) {
15937                info.args.doPostDeleteLI(true);
15938            }
15939        }
15940
15941        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15942    }
15943
15944    class PackageRemovedInfo {
15945        String removedPackage;
15946        int uid = -1;
15947        int removedAppId = -1;
15948        int[] origUsers;
15949        int[] removedUsers = null;
15950        boolean isRemovedPackageSystemUpdate = false;
15951        boolean isUpdate;
15952        boolean dataRemoved;
15953        boolean removedForAllUsers;
15954        // Clean up resources deleted packages.
15955        InstallArgs args = null;
15956        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15957        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15958
15959        void sendPackageRemovedBroadcasts(boolean killApp) {
15960            sendPackageRemovedBroadcastInternal(killApp);
15961            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15962            for (int i = 0; i < childCount; i++) {
15963                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15964                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15965            }
15966        }
15967
15968        void sendSystemPackageUpdatedBroadcasts() {
15969            if (isRemovedPackageSystemUpdate) {
15970                sendSystemPackageUpdatedBroadcastsInternal();
15971                final int childCount = (removedChildPackages != null)
15972                        ? removedChildPackages.size() : 0;
15973                for (int i = 0; i < childCount; i++) {
15974                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15975                    if (childInfo.isRemovedPackageSystemUpdate) {
15976                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15977                    }
15978                }
15979            }
15980        }
15981
15982        void sendSystemPackageAppearedBroadcasts() {
15983            final int packageCount = (appearedChildPackages != null)
15984                    ? appearedChildPackages.size() : 0;
15985            for (int i = 0; i < packageCount; i++) {
15986                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15987                sendPackageAddedForNewUsers(installedInfo.name, true,
15988                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
15989            }
15990        }
15991
15992        private void sendSystemPackageUpdatedBroadcastsInternal() {
15993            Bundle extras = new Bundle(2);
15994            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15995            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15996            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15997                    extras, 0, null, null, null);
15998            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15999                    extras, 0, null, null, null);
16000            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
16001                    null, 0, removedPackage, null, null);
16002        }
16003
16004        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
16005            Bundle extras = new Bundle(2);
16006            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
16007            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
16008            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
16009            if (isUpdate || isRemovedPackageSystemUpdate) {
16010                extras.putBoolean(Intent.EXTRA_REPLACING, true);
16011            }
16012            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
16013            if (removedPackage != null) {
16014                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
16015                        extras, 0, null, null, removedUsers);
16016                if (dataRemoved && !isRemovedPackageSystemUpdate) {
16017                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
16018                            removedPackage, extras, 0, null, null, removedUsers);
16019                }
16020            }
16021            if (removedAppId >= 0) {
16022                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
16023                        removedUsers);
16024            }
16025        }
16026    }
16027
16028    /*
16029     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
16030     * flag is not set, the data directory is removed as well.
16031     * make sure this flag is set for partially installed apps. If not its meaningless to
16032     * delete a partially installed application.
16033     */
16034    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
16035            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
16036        String packageName = ps.name;
16037        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
16038        // Retrieve object to delete permissions for shared user later on
16039        final PackageParser.Package deletedPkg;
16040        final PackageSetting deletedPs;
16041        // reader
16042        synchronized (mPackages) {
16043            deletedPkg = mPackages.get(packageName);
16044            deletedPs = mSettings.mPackages.get(packageName);
16045            if (outInfo != null) {
16046                outInfo.removedPackage = packageName;
16047                outInfo.removedUsers = deletedPs != null
16048                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
16049                        : null;
16050            }
16051        }
16052
16053        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
16054
16055        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
16056            final PackageParser.Package resolvedPkg;
16057            if (deletedPkg != null) {
16058                resolvedPkg = deletedPkg;
16059            } else {
16060                // We don't have a parsed package when it lives on an ejected
16061                // adopted storage device, so fake something together
16062                resolvedPkg = new PackageParser.Package(ps.name);
16063                resolvedPkg.setVolumeUuid(ps.volumeUuid);
16064            }
16065            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
16066                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16067            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
16068            if (outInfo != null) {
16069                outInfo.dataRemoved = true;
16070            }
16071            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
16072        }
16073
16074        // writer
16075        synchronized (mPackages) {
16076            if (deletedPs != null) {
16077                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
16078                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
16079                    clearDefaultBrowserIfNeeded(packageName);
16080                    if (outInfo != null) {
16081                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
16082                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
16083                    }
16084                    updatePermissionsLPw(deletedPs.name, null, 0);
16085                    if (deletedPs.sharedUser != null) {
16086                        // Remove permissions associated with package. Since runtime
16087                        // permissions are per user we have to kill the removed package
16088                        // or packages running under the shared user of the removed
16089                        // package if revoking the permissions requested only by the removed
16090                        // package is successful and this causes a change in gids.
16091                        for (int userId : UserManagerService.getInstance().getUserIds()) {
16092                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
16093                                    userId);
16094                            if (userIdToKill == UserHandle.USER_ALL
16095                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
16096                                // If gids changed for this user, kill all affected packages.
16097                                mHandler.post(new Runnable() {
16098                                    @Override
16099                                    public void run() {
16100                                        // This has to happen with no lock held.
16101                                        killApplication(deletedPs.name, deletedPs.appId,
16102                                                KILL_APP_REASON_GIDS_CHANGED);
16103                                    }
16104                                });
16105                                break;
16106                            }
16107                        }
16108                    }
16109                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
16110                }
16111                // make sure to preserve per-user disabled state if this removal was just
16112                // a downgrade of a system app to the factory package
16113                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
16114                    if (DEBUG_REMOVE) {
16115                        Slog.d(TAG, "Propagating install state across downgrade");
16116                    }
16117                    for (int userId : allUserHandles) {
16118                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16119                        if (DEBUG_REMOVE) {
16120                            Slog.d(TAG, "    user " + userId + " => " + installed);
16121                        }
16122                        ps.setInstalled(installed, userId);
16123                    }
16124                }
16125            }
16126            // can downgrade to reader
16127            if (writeSettings) {
16128                // Save settings now
16129                mSettings.writeLPr();
16130            }
16131        }
16132        if (outInfo != null) {
16133            // A user ID was deleted here. Go through all users and remove it
16134            // from KeyStore.
16135            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
16136        }
16137    }
16138
16139    static boolean locationIsPrivileged(File path) {
16140        try {
16141            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16142                    .getCanonicalPath();
16143            return path.getCanonicalPath().startsWith(privilegedAppDir);
16144        } catch (IOException e) {
16145            Slog.e(TAG, "Unable to access code path " + path);
16146        }
16147        return false;
16148    }
16149
16150    /*
16151     * Tries to delete system package.
16152     */
16153    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16154            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16155            boolean writeSettings) {
16156        if (deletedPs.parentPackageName != null) {
16157            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16158            return false;
16159        }
16160
16161        final boolean applyUserRestrictions
16162                = (allUserHandles != null) && (outInfo.origUsers != null);
16163        final PackageSetting disabledPs;
16164        // Confirm if the system package has been updated
16165        // An updated system app can be deleted. This will also have to restore
16166        // the system pkg from system partition
16167        // reader
16168        synchronized (mPackages) {
16169            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16170        }
16171
16172        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16173                + " disabledPs=" + disabledPs);
16174
16175        if (disabledPs == null) {
16176            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16177            return false;
16178        } else if (DEBUG_REMOVE) {
16179            Slog.d(TAG, "Deleting system pkg from data partition");
16180        }
16181
16182        if (DEBUG_REMOVE) {
16183            if (applyUserRestrictions) {
16184                Slog.d(TAG, "Remembering install states:");
16185                for (int userId : allUserHandles) {
16186                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16187                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
16188                }
16189            }
16190        }
16191
16192        // Delete the updated package
16193        outInfo.isRemovedPackageSystemUpdate = true;
16194        if (outInfo.removedChildPackages != null) {
16195            final int childCount = (deletedPs.childPackageNames != null)
16196                    ? deletedPs.childPackageNames.size() : 0;
16197            for (int i = 0; i < childCount; i++) {
16198                String childPackageName = deletedPs.childPackageNames.get(i);
16199                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16200                        .contains(childPackageName)) {
16201                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16202                            childPackageName);
16203                    if (childInfo != null) {
16204                        childInfo.isRemovedPackageSystemUpdate = true;
16205                    }
16206                }
16207            }
16208        }
16209
16210        if (disabledPs.versionCode < deletedPs.versionCode) {
16211            // Delete data for downgrades
16212            flags &= ~PackageManager.DELETE_KEEP_DATA;
16213        } else {
16214            // Preserve data by setting flag
16215            flags |= PackageManager.DELETE_KEEP_DATA;
16216        }
16217
16218        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16219                outInfo, writeSettings, disabledPs.pkg);
16220        if (!ret) {
16221            return false;
16222        }
16223
16224        // writer
16225        synchronized (mPackages) {
16226            // Reinstate the old system package
16227            enableSystemPackageLPw(disabledPs.pkg);
16228            // Remove any native libraries from the upgraded package.
16229            removeNativeBinariesLI(deletedPs);
16230        }
16231
16232        // Install the system package
16233        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16234        int parseFlags = mDefParseFlags
16235                | PackageParser.PARSE_MUST_BE_APK
16236                | PackageParser.PARSE_IS_SYSTEM
16237                | PackageParser.PARSE_IS_SYSTEM_DIR;
16238        if (locationIsPrivileged(disabledPs.codePath)) {
16239            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16240        }
16241
16242        final PackageParser.Package newPkg;
16243        try {
16244            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16245        } catch (PackageManagerException e) {
16246            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16247                    + e.getMessage());
16248            return false;
16249        }
16250        try {
16251            // update shared libraries for the newly re-installed system package
16252            updateSharedLibrariesLPr(newPkg, null);
16253        } catch (PackageManagerException e) {
16254            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16255        }
16256
16257        prepareAppDataAfterInstallLIF(newPkg);
16258
16259        // writer
16260        synchronized (mPackages) {
16261            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16262
16263            // Propagate the permissions state as we do not want to drop on the floor
16264            // runtime permissions. The update permissions method below will take
16265            // care of removing obsolete permissions and grant install permissions.
16266            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16267            updatePermissionsLPw(newPkg.packageName, newPkg,
16268                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16269
16270            if (applyUserRestrictions) {
16271                if (DEBUG_REMOVE) {
16272                    Slog.d(TAG, "Propagating install state across reinstall");
16273                }
16274                for (int userId : allUserHandles) {
16275                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16276                    if (DEBUG_REMOVE) {
16277                        Slog.d(TAG, "    user " + userId + " => " + installed);
16278                    }
16279                    ps.setInstalled(installed, userId);
16280
16281                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16282                }
16283                // Regardless of writeSettings we need to ensure that this restriction
16284                // state propagation is persisted
16285                mSettings.writeAllUsersPackageRestrictionsLPr();
16286            }
16287            // can downgrade to reader here
16288            if (writeSettings) {
16289                mSettings.writeLPr();
16290            }
16291        }
16292        return true;
16293    }
16294
16295    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16296            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16297            PackageRemovedInfo outInfo, boolean writeSettings,
16298            PackageParser.Package replacingPackage) {
16299        synchronized (mPackages) {
16300            if (outInfo != null) {
16301                outInfo.uid = ps.appId;
16302            }
16303
16304            if (outInfo != null && outInfo.removedChildPackages != null) {
16305                final int childCount = (ps.childPackageNames != null)
16306                        ? ps.childPackageNames.size() : 0;
16307                for (int i = 0; i < childCount; i++) {
16308                    String childPackageName = ps.childPackageNames.get(i);
16309                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16310                    if (childPs == null) {
16311                        return false;
16312                    }
16313                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16314                            childPackageName);
16315                    if (childInfo != null) {
16316                        childInfo.uid = childPs.appId;
16317                    }
16318                }
16319            }
16320        }
16321
16322        // Delete package data from internal structures and also remove data if flag is set
16323        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16324
16325        // Delete the child packages data
16326        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16327        for (int i = 0; i < childCount; i++) {
16328            PackageSetting childPs;
16329            synchronized (mPackages) {
16330                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16331            }
16332            if (childPs != null) {
16333                PackageRemovedInfo childOutInfo = (outInfo != null
16334                        && outInfo.removedChildPackages != null)
16335                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16336                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16337                        && (replacingPackage != null
16338                        && !replacingPackage.hasChildPackage(childPs.name))
16339                        ? flags & ~DELETE_KEEP_DATA : flags;
16340                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16341                        deleteFlags, writeSettings);
16342            }
16343        }
16344
16345        // Delete application code and resources only for parent packages
16346        if (ps.parentPackageName == null) {
16347            if (deleteCodeAndResources && (outInfo != null)) {
16348                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16349                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16350                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16351            }
16352        }
16353
16354        return true;
16355    }
16356
16357    @Override
16358    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16359            int userId) {
16360        mContext.enforceCallingOrSelfPermission(
16361                android.Manifest.permission.DELETE_PACKAGES, null);
16362        synchronized (mPackages) {
16363            PackageSetting ps = mSettings.mPackages.get(packageName);
16364            if (ps == null) {
16365                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16366                return false;
16367            }
16368            if (!ps.getInstalled(userId)) {
16369                // Can't block uninstall for an app that is not installed or enabled.
16370                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16371                return false;
16372            }
16373            ps.setBlockUninstall(blockUninstall, userId);
16374            mSettings.writePackageRestrictionsLPr(userId);
16375        }
16376        return true;
16377    }
16378
16379    @Override
16380    public boolean getBlockUninstallForUser(String packageName, int userId) {
16381        synchronized (mPackages) {
16382            PackageSetting ps = mSettings.mPackages.get(packageName);
16383            if (ps == null) {
16384                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16385                return false;
16386            }
16387            return ps.getBlockUninstall(userId);
16388        }
16389    }
16390
16391    @Override
16392    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16393        int callingUid = Binder.getCallingUid();
16394        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16395            throw new SecurityException(
16396                    "setRequiredForSystemUser can only be run by the system or root");
16397        }
16398        synchronized (mPackages) {
16399            PackageSetting ps = mSettings.mPackages.get(packageName);
16400            if (ps == null) {
16401                Log.w(TAG, "Package doesn't exist: " + packageName);
16402                return false;
16403            }
16404            if (systemUserApp) {
16405                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16406            } else {
16407                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16408            }
16409            mSettings.writeLPr();
16410        }
16411        return true;
16412    }
16413
16414    /*
16415     * This method handles package deletion in general
16416     */
16417    private boolean deletePackageLIF(String packageName, UserHandle user,
16418            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16419            PackageRemovedInfo outInfo, boolean writeSettings,
16420            PackageParser.Package replacingPackage) {
16421        if (packageName == null) {
16422            Slog.w(TAG, "Attempt to delete null packageName.");
16423            return false;
16424        }
16425
16426        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16427
16428        PackageSetting ps;
16429
16430        synchronized (mPackages) {
16431            ps = mSettings.mPackages.get(packageName);
16432            if (ps == null) {
16433                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16434                return false;
16435            }
16436
16437            if (ps.parentPackageName != null && (!isSystemApp(ps)
16438                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16439                if (DEBUG_REMOVE) {
16440                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16441                            + ((user == null) ? UserHandle.USER_ALL : user));
16442                }
16443                final int removedUserId = (user != null) ? user.getIdentifier()
16444                        : UserHandle.USER_ALL;
16445                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16446                    return false;
16447                }
16448                markPackageUninstalledForUserLPw(ps, user);
16449                scheduleWritePackageRestrictionsLocked(user);
16450                return true;
16451            }
16452        }
16453
16454        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16455                && user.getIdentifier() != UserHandle.USER_ALL)) {
16456            // The caller is asking that the package only be deleted for a single
16457            // user.  To do this, we just mark its uninstalled state and delete
16458            // its data. If this is a system app, we only allow this to happen if
16459            // they have set the special DELETE_SYSTEM_APP which requests different
16460            // semantics than normal for uninstalling system apps.
16461            markPackageUninstalledForUserLPw(ps, user);
16462
16463            if (!isSystemApp(ps)) {
16464                // Do not uninstall the APK if an app should be cached
16465                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16466                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16467                    // Other user still have this package installed, so all
16468                    // we need to do is clear this user's data and save that
16469                    // it is uninstalled.
16470                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16471                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16472                        return false;
16473                    }
16474                    scheduleWritePackageRestrictionsLocked(user);
16475                    return true;
16476                } else {
16477                    // We need to set it back to 'installed' so the uninstall
16478                    // broadcasts will be sent correctly.
16479                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16480                    ps.setInstalled(true, user.getIdentifier());
16481                }
16482            } else {
16483                // This is a system app, so we assume that the
16484                // other users still have this package installed, so all
16485                // we need to do is clear this user's data and save that
16486                // it is uninstalled.
16487                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16488                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16489                    return false;
16490                }
16491                scheduleWritePackageRestrictionsLocked(user);
16492                return true;
16493            }
16494        }
16495
16496        // If we are deleting a composite package for all users, keep track
16497        // of result for each child.
16498        if (ps.childPackageNames != null && outInfo != null) {
16499            synchronized (mPackages) {
16500                final int childCount = ps.childPackageNames.size();
16501                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16502                for (int i = 0; i < childCount; i++) {
16503                    String childPackageName = ps.childPackageNames.get(i);
16504                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16505                    childInfo.removedPackage = childPackageName;
16506                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16507                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
16508                    if (childPs != null) {
16509                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16510                    }
16511                }
16512            }
16513        }
16514
16515        boolean ret = false;
16516        if (isSystemApp(ps)) {
16517            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16518            // When an updated system application is deleted we delete the existing resources
16519            // as well and fall back to existing code in system partition
16520            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16521        } else {
16522            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16523            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16524                    outInfo, writeSettings, replacingPackage);
16525        }
16526
16527        // Take a note whether we deleted the package for all users
16528        if (outInfo != null) {
16529            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16530            if (outInfo.removedChildPackages != null) {
16531                synchronized (mPackages) {
16532                    final int childCount = outInfo.removedChildPackages.size();
16533                    for (int i = 0; i < childCount; i++) {
16534                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16535                        if (childInfo != null) {
16536                            childInfo.removedForAllUsers = mPackages.get(
16537                                    childInfo.removedPackage) == null;
16538                        }
16539                    }
16540                }
16541            }
16542            // If we uninstalled an update to a system app there may be some
16543            // child packages that appeared as they are declared in the system
16544            // app but were not declared in the update.
16545            if (isSystemApp(ps)) {
16546                synchronized (mPackages) {
16547                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
16548                    final int childCount = (updatedPs.childPackageNames != null)
16549                            ? updatedPs.childPackageNames.size() : 0;
16550                    for (int i = 0; i < childCount; i++) {
16551                        String childPackageName = updatedPs.childPackageNames.get(i);
16552                        if (outInfo.removedChildPackages == null
16553                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16554                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
16555                            if (childPs == null) {
16556                                continue;
16557                            }
16558                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16559                            installRes.name = childPackageName;
16560                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16561                            installRes.pkg = mPackages.get(childPackageName);
16562                            installRes.uid = childPs.pkg.applicationInfo.uid;
16563                            if (outInfo.appearedChildPackages == null) {
16564                                outInfo.appearedChildPackages = new ArrayMap<>();
16565                            }
16566                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16567                        }
16568                    }
16569                }
16570            }
16571        }
16572
16573        return ret;
16574    }
16575
16576    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16577        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16578                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16579        for (int nextUserId : userIds) {
16580            if (DEBUG_REMOVE) {
16581                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16582            }
16583            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16584                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16585                    false /*hidden*/, false /*suspended*/, null, null, null,
16586                    false /*blockUninstall*/,
16587                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16588        }
16589    }
16590
16591    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16592            PackageRemovedInfo outInfo) {
16593        final PackageParser.Package pkg;
16594        synchronized (mPackages) {
16595            pkg = mPackages.get(ps.name);
16596        }
16597
16598        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16599                : new int[] {userId};
16600        for (int nextUserId : userIds) {
16601            if (DEBUG_REMOVE) {
16602                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16603                        + nextUserId);
16604            }
16605
16606            destroyAppDataLIF(pkg, userId,
16607                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16608            destroyAppProfilesLIF(pkg, userId);
16609            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16610            schedulePackageCleaning(ps.name, nextUserId, false);
16611            synchronized (mPackages) {
16612                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16613                    scheduleWritePackageRestrictionsLocked(nextUserId);
16614                }
16615                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16616            }
16617        }
16618
16619        if (outInfo != null) {
16620            outInfo.removedPackage = ps.name;
16621            outInfo.removedAppId = ps.appId;
16622            outInfo.removedUsers = userIds;
16623        }
16624
16625        return true;
16626    }
16627
16628    private final class ClearStorageConnection implements ServiceConnection {
16629        IMediaContainerService mContainerService;
16630
16631        @Override
16632        public void onServiceConnected(ComponentName name, IBinder service) {
16633            synchronized (this) {
16634                mContainerService = IMediaContainerService.Stub
16635                        .asInterface(Binder.allowBlocking(service));
16636                notifyAll();
16637            }
16638        }
16639
16640        @Override
16641        public void onServiceDisconnected(ComponentName name) {
16642        }
16643    }
16644
16645    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16646        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16647
16648        final boolean mounted;
16649        if (Environment.isExternalStorageEmulated()) {
16650            mounted = true;
16651        } else {
16652            final String status = Environment.getExternalStorageState();
16653
16654            mounted = status.equals(Environment.MEDIA_MOUNTED)
16655                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16656        }
16657
16658        if (!mounted) {
16659            return;
16660        }
16661
16662        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16663        int[] users;
16664        if (userId == UserHandle.USER_ALL) {
16665            users = sUserManager.getUserIds();
16666        } else {
16667            users = new int[] { userId };
16668        }
16669        final ClearStorageConnection conn = new ClearStorageConnection();
16670        if (mContext.bindServiceAsUser(
16671                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16672            try {
16673                for (int curUser : users) {
16674                    long timeout = SystemClock.uptimeMillis() + 5000;
16675                    synchronized (conn) {
16676                        long now;
16677                        while (conn.mContainerService == null &&
16678                                (now = SystemClock.uptimeMillis()) < timeout) {
16679                            try {
16680                                conn.wait(timeout - now);
16681                            } catch (InterruptedException e) {
16682                            }
16683                        }
16684                    }
16685                    if (conn.mContainerService == null) {
16686                        return;
16687                    }
16688
16689                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16690                    clearDirectory(conn.mContainerService,
16691                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16692                    if (allData) {
16693                        clearDirectory(conn.mContainerService,
16694                                userEnv.buildExternalStorageAppDataDirs(packageName));
16695                        clearDirectory(conn.mContainerService,
16696                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16697                    }
16698                }
16699            } finally {
16700                mContext.unbindService(conn);
16701            }
16702        }
16703    }
16704
16705    @Override
16706    public void clearApplicationProfileData(String packageName) {
16707        enforceSystemOrRoot("Only the system can clear all profile data");
16708
16709        final PackageParser.Package pkg;
16710        synchronized (mPackages) {
16711            pkg = mPackages.get(packageName);
16712        }
16713
16714        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16715            synchronized (mInstallLock) {
16716                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16717                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16718                        true /* removeBaseMarker */);
16719            }
16720        }
16721    }
16722
16723    @Override
16724    public void clearApplicationUserData(final String packageName,
16725            final IPackageDataObserver observer, final int userId) {
16726        mContext.enforceCallingOrSelfPermission(
16727                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16728
16729        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16730                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16731
16732        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16733            throw new SecurityException("Cannot clear data for a protected package: "
16734                    + packageName);
16735        }
16736        // Queue up an async operation since the package deletion may take a little while.
16737        mHandler.post(new Runnable() {
16738            public void run() {
16739                mHandler.removeCallbacks(this);
16740                final boolean succeeded;
16741                try (PackageFreezer freezer = freezePackage(packageName,
16742                        "clearApplicationUserData")) {
16743                    synchronized (mInstallLock) {
16744                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16745                    }
16746                    clearExternalStorageDataSync(packageName, userId, true);
16747                }
16748                if (succeeded) {
16749                    // invoke DeviceStorageMonitor's update method to clear any notifications
16750                    DeviceStorageMonitorInternal dsm = LocalServices
16751                            .getService(DeviceStorageMonitorInternal.class);
16752                    if (dsm != null) {
16753                        dsm.checkMemory();
16754                    }
16755                }
16756                if(observer != null) {
16757                    try {
16758                        observer.onRemoveCompleted(packageName, succeeded);
16759                    } catch (RemoteException e) {
16760                        Log.i(TAG, "Observer no longer exists.");
16761                    }
16762                } //end if observer
16763            } //end run
16764        });
16765    }
16766
16767    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16768        if (packageName == null) {
16769            Slog.w(TAG, "Attempt to delete null packageName.");
16770            return false;
16771        }
16772
16773        // Try finding details about the requested package
16774        PackageParser.Package pkg;
16775        synchronized (mPackages) {
16776            pkg = mPackages.get(packageName);
16777            if (pkg == null) {
16778                final PackageSetting ps = mSettings.mPackages.get(packageName);
16779                if (ps != null) {
16780                    pkg = ps.pkg;
16781                }
16782            }
16783
16784            if (pkg == null) {
16785                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16786                return false;
16787            }
16788
16789            PackageSetting ps = (PackageSetting) pkg.mExtras;
16790            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16791        }
16792
16793        clearAppDataLIF(pkg, userId,
16794                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16795
16796        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16797        removeKeystoreDataIfNeeded(userId, appId);
16798
16799        UserManagerInternal umInternal = getUserManagerInternal();
16800        final int flags;
16801        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16802            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16803        } else if (umInternal.isUserRunning(userId)) {
16804            flags = StorageManager.FLAG_STORAGE_DE;
16805        } else {
16806            flags = 0;
16807        }
16808        prepareAppDataContentsLIF(pkg, userId, flags);
16809
16810        return true;
16811    }
16812
16813    /**
16814     * Reverts user permission state changes (permissions and flags) in
16815     * all packages for a given user.
16816     *
16817     * @param userId The device user for which to do a reset.
16818     */
16819    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16820        final int packageCount = mPackages.size();
16821        for (int i = 0; i < packageCount; i++) {
16822            PackageParser.Package pkg = mPackages.valueAt(i);
16823            PackageSetting ps = (PackageSetting) pkg.mExtras;
16824            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16825        }
16826    }
16827
16828    private void resetNetworkPolicies(int userId) {
16829        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16830    }
16831
16832    /**
16833     * Reverts user permission state changes (permissions and flags).
16834     *
16835     * @param ps The package for which to reset.
16836     * @param userId The device user for which to do a reset.
16837     */
16838    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16839            final PackageSetting ps, final int userId) {
16840        if (ps.pkg == null) {
16841            return;
16842        }
16843
16844        // These are flags that can change base on user actions.
16845        final int userSettableMask = FLAG_PERMISSION_USER_SET
16846                | FLAG_PERMISSION_USER_FIXED
16847                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16848                | FLAG_PERMISSION_REVIEW_REQUIRED;
16849
16850        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16851                | FLAG_PERMISSION_POLICY_FIXED;
16852
16853        boolean writeInstallPermissions = false;
16854        boolean writeRuntimePermissions = false;
16855
16856        final int permissionCount = ps.pkg.requestedPermissions.size();
16857        for (int i = 0; i < permissionCount; i++) {
16858            String permission = ps.pkg.requestedPermissions.get(i);
16859
16860            BasePermission bp = mSettings.mPermissions.get(permission);
16861            if (bp == null) {
16862                continue;
16863            }
16864
16865            // If shared user we just reset the state to which only this app contributed.
16866            if (ps.sharedUser != null) {
16867                boolean used = false;
16868                final int packageCount = ps.sharedUser.packages.size();
16869                for (int j = 0; j < packageCount; j++) {
16870                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16871                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16872                            && pkg.pkg.requestedPermissions.contains(permission)) {
16873                        used = true;
16874                        break;
16875                    }
16876                }
16877                if (used) {
16878                    continue;
16879                }
16880            }
16881
16882            PermissionsState permissionsState = ps.getPermissionsState();
16883
16884            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16885
16886            // Always clear the user settable flags.
16887            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16888                    bp.name) != null;
16889            // If permission review is enabled and this is a legacy app, mark the
16890            // permission as requiring a review as this is the initial state.
16891            int flags = 0;
16892            if (mPermissionReviewRequired
16893                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16894                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16895            }
16896            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16897                if (hasInstallState) {
16898                    writeInstallPermissions = true;
16899                } else {
16900                    writeRuntimePermissions = true;
16901                }
16902            }
16903
16904            // Below is only runtime permission handling.
16905            if (!bp.isRuntime()) {
16906                continue;
16907            }
16908
16909            // Never clobber system or policy.
16910            if ((oldFlags & policyOrSystemFlags) != 0) {
16911                continue;
16912            }
16913
16914            // If this permission was granted by default, make sure it is.
16915            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16916                if (permissionsState.grantRuntimePermission(bp, userId)
16917                        != PERMISSION_OPERATION_FAILURE) {
16918                    writeRuntimePermissions = true;
16919                }
16920            // If permission review is enabled the permissions for a legacy apps
16921            // are represented as constantly granted runtime ones, so don't revoke.
16922            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16923                // Otherwise, reset the permission.
16924                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16925                switch (revokeResult) {
16926                    case PERMISSION_OPERATION_SUCCESS:
16927                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16928                        writeRuntimePermissions = true;
16929                        final int appId = ps.appId;
16930                        mHandler.post(new Runnable() {
16931                            @Override
16932                            public void run() {
16933                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16934                            }
16935                        });
16936                    } break;
16937                }
16938            }
16939        }
16940
16941        // Synchronously write as we are taking permissions away.
16942        if (writeRuntimePermissions) {
16943            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16944        }
16945
16946        // Synchronously write as we are taking permissions away.
16947        if (writeInstallPermissions) {
16948            mSettings.writeLPr();
16949        }
16950    }
16951
16952    /**
16953     * Remove entries from the keystore daemon. Will only remove it if the
16954     * {@code appId} is valid.
16955     */
16956    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16957        if (appId < 0) {
16958            return;
16959        }
16960
16961        final KeyStore keyStore = KeyStore.getInstance();
16962        if (keyStore != null) {
16963            if (userId == UserHandle.USER_ALL) {
16964                for (final int individual : sUserManager.getUserIds()) {
16965                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16966                }
16967            } else {
16968                keyStore.clearUid(UserHandle.getUid(userId, appId));
16969            }
16970        } else {
16971            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16972        }
16973    }
16974
16975    @Override
16976    public void deleteApplicationCacheFiles(final String packageName,
16977            final IPackageDataObserver observer) {
16978        final int userId = UserHandle.getCallingUserId();
16979        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16980    }
16981
16982    @Override
16983    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16984            final IPackageDataObserver observer) {
16985        mContext.enforceCallingOrSelfPermission(
16986                android.Manifest.permission.DELETE_CACHE_FILES, null);
16987        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16988                /* requireFullPermission= */ true, /* checkShell= */ false,
16989                "delete application cache files");
16990
16991        final PackageParser.Package pkg;
16992        synchronized (mPackages) {
16993            pkg = mPackages.get(packageName);
16994        }
16995
16996        // Queue up an async operation since the package deletion may take a little while.
16997        mHandler.post(new Runnable() {
16998            public void run() {
16999                synchronized (mInstallLock) {
17000                    final int flags = StorageManager.FLAG_STORAGE_DE
17001                            | StorageManager.FLAG_STORAGE_CE;
17002                    // We're only clearing cache files, so we don't care if the
17003                    // app is unfrozen and still able to run
17004                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
17005                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17006                }
17007                clearExternalStorageDataSync(packageName, userId, false);
17008                if (observer != null) {
17009                    try {
17010                        observer.onRemoveCompleted(packageName, true);
17011                    } catch (RemoteException e) {
17012                        Log.i(TAG, "Observer no longer exists.");
17013                    }
17014                }
17015            }
17016        });
17017    }
17018
17019    @Override
17020    public void getPackageSizeInfo(final String packageName, int userHandle,
17021            final IPackageStatsObserver observer) {
17022        mContext.enforceCallingOrSelfPermission(
17023                android.Manifest.permission.GET_PACKAGE_SIZE, null);
17024        if (packageName == null) {
17025            throw new IllegalArgumentException("Attempt to get size of null packageName");
17026        }
17027
17028        PackageStats stats = new PackageStats(packageName, userHandle);
17029
17030        /*
17031         * Queue up an async operation since the package measurement may take a
17032         * little while.
17033         */
17034        Message msg = mHandler.obtainMessage(INIT_COPY);
17035        msg.obj = new MeasureParams(stats, observer);
17036        mHandler.sendMessage(msg);
17037    }
17038
17039    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
17040        final PackageSetting ps;
17041        synchronized (mPackages) {
17042            ps = mSettings.mPackages.get(packageName);
17043            if (ps == null) {
17044                Slog.w(TAG, "Failed to find settings for " + packageName);
17045                return false;
17046            }
17047        }
17048        try {
17049            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
17050                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
17051                    ps.getCeDataInode(userId), ps.codePathString, stats);
17052        } catch (InstallerException e) {
17053            Slog.w(TAG, String.valueOf(e));
17054            return false;
17055        }
17056
17057        // For now, ignore code size of packages on system partition
17058        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
17059            stats.codeSize = 0;
17060        }
17061
17062        return true;
17063    }
17064
17065    private int getUidTargetSdkVersionLockedLPr(int uid) {
17066        Object obj = mSettings.getUserIdLPr(uid);
17067        if (obj instanceof SharedUserSetting) {
17068            final SharedUserSetting sus = (SharedUserSetting) obj;
17069            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
17070            final Iterator<PackageSetting> it = sus.packages.iterator();
17071            while (it.hasNext()) {
17072                final PackageSetting ps = it.next();
17073                if (ps.pkg != null) {
17074                    int v = ps.pkg.applicationInfo.targetSdkVersion;
17075                    if (v < vers) vers = v;
17076                }
17077            }
17078            return vers;
17079        } else if (obj instanceof PackageSetting) {
17080            final PackageSetting ps = (PackageSetting) obj;
17081            if (ps.pkg != null) {
17082                return ps.pkg.applicationInfo.targetSdkVersion;
17083            }
17084        }
17085        return Build.VERSION_CODES.CUR_DEVELOPMENT;
17086    }
17087
17088    @Override
17089    public void addPreferredActivity(IntentFilter filter, int match,
17090            ComponentName[] set, ComponentName activity, int userId) {
17091        addPreferredActivityInternal(filter, match, set, activity, true, userId,
17092                "Adding preferred");
17093    }
17094
17095    private void addPreferredActivityInternal(IntentFilter filter, int match,
17096            ComponentName[] set, ComponentName activity, boolean always, int userId,
17097            String opname) {
17098        // writer
17099        int callingUid = Binder.getCallingUid();
17100        enforceCrossUserPermission(callingUid, userId,
17101                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
17102        if (filter.countActions() == 0) {
17103            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17104            return;
17105        }
17106        synchronized (mPackages) {
17107            if (mContext.checkCallingOrSelfPermission(
17108                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17109                    != PackageManager.PERMISSION_GRANTED) {
17110                if (getUidTargetSdkVersionLockedLPr(callingUid)
17111                        < Build.VERSION_CODES.FROYO) {
17112                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
17113                            + callingUid);
17114                    return;
17115                }
17116                mContext.enforceCallingOrSelfPermission(
17117                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17118            }
17119
17120            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
17121            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
17122                    + userId + ":");
17123            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17124            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
17125            scheduleWritePackageRestrictionsLocked(userId);
17126            postPreferredActivityChangedBroadcast(userId);
17127        }
17128    }
17129
17130    private void postPreferredActivityChangedBroadcast(int userId) {
17131        mHandler.post(() -> {
17132            final IActivityManager am = ActivityManager.getService();
17133            if (am == null) {
17134                return;
17135            }
17136
17137            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
17138            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17139            try {
17140                am.broadcastIntent(null, intent, null, null,
17141                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
17142                        null, false, false, userId);
17143            } catch (RemoteException e) {
17144            }
17145        });
17146    }
17147
17148    @Override
17149    public void replacePreferredActivity(IntentFilter filter, int match,
17150            ComponentName[] set, ComponentName activity, int userId) {
17151        if (filter.countActions() != 1) {
17152            throw new IllegalArgumentException(
17153                    "replacePreferredActivity expects filter to have only 1 action.");
17154        }
17155        if (filter.countDataAuthorities() != 0
17156                || filter.countDataPaths() != 0
17157                || filter.countDataSchemes() > 1
17158                || filter.countDataTypes() != 0) {
17159            throw new IllegalArgumentException(
17160                    "replacePreferredActivity expects filter to have no data authorities, " +
17161                    "paths, or types; and at most one scheme.");
17162        }
17163
17164        final int callingUid = Binder.getCallingUid();
17165        enforceCrossUserPermission(callingUid, userId,
17166                true /* requireFullPermission */, false /* checkShell */,
17167                "replace preferred activity");
17168        synchronized (mPackages) {
17169            if (mContext.checkCallingOrSelfPermission(
17170                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17171                    != PackageManager.PERMISSION_GRANTED) {
17172                if (getUidTargetSdkVersionLockedLPr(callingUid)
17173                        < Build.VERSION_CODES.FROYO) {
17174                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17175                            + Binder.getCallingUid());
17176                    return;
17177                }
17178                mContext.enforceCallingOrSelfPermission(
17179                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17180            }
17181
17182            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17183            if (pir != null) {
17184                // Get all of the existing entries that exactly match this filter.
17185                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17186                if (existing != null && existing.size() == 1) {
17187                    PreferredActivity cur = existing.get(0);
17188                    if (DEBUG_PREFERRED) {
17189                        Slog.i(TAG, "Checking replace of preferred:");
17190                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17191                        if (!cur.mPref.mAlways) {
17192                            Slog.i(TAG, "  -- CUR; not mAlways!");
17193                        } else {
17194                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
17195                            Slog.i(TAG, "  -- CUR: mSet="
17196                                    + Arrays.toString(cur.mPref.mSetComponents));
17197                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
17198                            Slog.i(TAG, "  -- NEW: mMatch="
17199                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
17200                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
17201                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
17202                        }
17203                    }
17204                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17205                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17206                            && cur.mPref.sameSet(set)) {
17207                        // Setting the preferred activity to what it happens to be already
17208                        if (DEBUG_PREFERRED) {
17209                            Slog.i(TAG, "Replacing with same preferred activity "
17210                                    + cur.mPref.mShortComponent + " for user "
17211                                    + userId + ":");
17212                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17213                        }
17214                        return;
17215                    }
17216                }
17217
17218                if (existing != null) {
17219                    if (DEBUG_PREFERRED) {
17220                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17221                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17222                    }
17223                    for (int i = 0; i < existing.size(); i++) {
17224                        PreferredActivity pa = existing.get(i);
17225                        if (DEBUG_PREFERRED) {
17226                            Slog.i(TAG, "Removing existing preferred activity "
17227                                    + pa.mPref.mComponent + ":");
17228                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17229                        }
17230                        pir.removeFilter(pa);
17231                    }
17232                }
17233            }
17234            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17235                    "Replacing preferred");
17236        }
17237    }
17238
17239    @Override
17240    public void clearPackagePreferredActivities(String packageName) {
17241        final int uid = Binder.getCallingUid();
17242        // writer
17243        synchronized (mPackages) {
17244            PackageParser.Package pkg = mPackages.get(packageName);
17245            if (pkg == null || pkg.applicationInfo.uid != uid) {
17246                if (mContext.checkCallingOrSelfPermission(
17247                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17248                        != PackageManager.PERMISSION_GRANTED) {
17249                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17250                            < Build.VERSION_CODES.FROYO) {
17251                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17252                                + Binder.getCallingUid());
17253                        return;
17254                    }
17255                    mContext.enforceCallingOrSelfPermission(
17256                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17257                }
17258            }
17259
17260            int user = UserHandle.getCallingUserId();
17261            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17262                scheduleWritePackageRestrictionsLocked(user);
17263            }
17264        }
17265    }
17266
17267    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17268    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17269        ArrayList<PreferredActivity> removed = null;
17270        boolean changed = false;
17271        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17272            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17273            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17274            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17275                continue;
17276            }
17277            Iterator<PreferredActivity> it = pir.filterIterator();
17278            while (it.hasNext()) {
17279                PreferredActivity pa = it.next();
17280                // Mark entry for removal only if it matches the package name
17281                // and the entry is of type "always".
17282                if (packageName == null ||
17283                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17284                                && pa.mPref.mAlways)) {
17285                    if (removed == null) {
17286                        removed = new ArrayList<PreferredActivity>();
17287                    }
17288                    removed.add(pa);
17289                }
17290            }
17291            if (removed != null) {
17292                for (int j=0; j<removed.size(); j++) {
17293                    PreferredActivity pa = removed.get(j);
17294                    pir.removeFilter(pa);
17295                }
17296                changed = true;
17297            }
17298        }
17299        if (changed) {
17300            postPreferredActivityChangedBroadcast(userId);
17301        }
17302        return changed;
17303    }
17304
17305    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17306    private void clearIntentFilterVerificationsLPw(int userId) {
17307        final int packageCount = mPackages.size();
17308        for (int i = 0; i < packageCount; i++) {
17309            PackageParser.Package pkg = mPackages.valueAt(i);
17310            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17311        }
17312    }
17313
17314    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17315    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17316        if (userId == UserHandle.USER_ALL) {
17317            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17318                    sUserManager.getUserIds())) {
17319                for (int oneUserId : sUserManager.getUserIds()) {
17320                    scheduleWritePackageRestrictionsLocked(oneUserId);
17321                }
17322            }
17323        } else {
17324            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17325                scheduleWritePackageRestrictionsLocked(userId);
17326            }
17327        }
17328    }
17329
17330    void clearDefaultBrowserIfNeeded(String packageName) {
17331        for (int oneUserId : sUserManager.getUserIds()) {
17332            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17333            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17334            if (packageName.equals(defaultBrowserPackageName)) {
17335                setDefaultBrowserPackageName(null, oneUserId);
17336            }
17337        }
17338    }
17339
17340    @Override
17341    public void resetApplicationPreferences(int userId) {
17342        mContext.enforceCallingOrSelfPermission(
17343                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17344        final long identity = Binder.clearCallingIdentity();
17345        // writer
17346        try {
17347            synchronized (mPackages) {
17348                clearPackagePreferredActivitiesLPw(null, userId);
17349                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17350                // TODO: We have to reset the default SMS and Phone. This requires
17351                // significant refactoring to keep all default apps in the package
17352                // manager (cleaner but more work) or have the services provide
17353                // callbacks to the package manager to request a default app reset.
17354                applyFactoryDefaultBrowserLPw(userId);
17355                clearIntentFilterVerificationsLPw(userId);
17356                primeDomainVerificationsLPw(userId);
17357                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17358                scheduleWritePackageRestrictionsLocked(userId);
17359            }
17360            resetNetworkPolicies(userId);
17361        } finally {
17362            Binder.restoreCallingIdentity(identity);
17363        }
17364    }
17365
17366    @Override
17367    public int getPreferredActivities(List<IntentFilter> outFilters,
17368            List<ComponentName> outActivities, String packageName) {
17369
17370        int num = 0;
17371        final int userId = UserHandle.getCallingUserId();
17372        // reader
17373        synchronized (mPackages) {
17374            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17375            if (pir != null) {
17376                final Iterator<PreferredActivity> it = pir.filterIterator();
17377                while (it.hasNext()) {
17378                    final PreferredActivity pa = it.next();
17379                    if (packageName == null
17380                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17381                                    && pa.mPref.mAlways)) {
17382                        if (outFilters != null) {
17383                            outFilters.add(new IntentFilter(pa));
17384                        }
17385                        if (outActivities != null) {
17386                            outActivities.add(pa.mPref.mComponent);
17387                        }
17388                    }
17389                }
17390            }
17391        }
17392
17393        return num;
17394    }
17395
17396    @Override
17397    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17398            int userId) {
17399        int callingUid = Binder.getCallingUid();
17400        if (callingUid != Process.SYSTEM_UID) {
17401            throw new SecurityException(
17402                    "addPersistentPreferredActivity can only be run by the system");
17403        }
17404        if (filter.countActions() == 0) {
17405            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17406            return;
17407        }
17408        synchronized (mPackages) {
17409            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17410                    ":");
17411            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17412            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17413                    new PersistentPreferredActivity(filter, activity));
17414            scheduleWritePackageRestrictionsLocked(userId);
17415            postPreferredActivityChangedBroadcast(userId);
17416        }
17417    }
17418
17419    @Override
17420    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17421        int callingUid = Binder.getCallingUid();
17422        if (callingUid != Process.SYSTEM_UID) {
17423            throw new SecurityException(
17424                    "clearPackagePersistentPreferredActivities can only be run by the system");
17425        }
17426        ArrayList<PersistentPreferredActivity> removed = null;
17427        boolean changed = false;
17428        synchronized (mPackages) {
17429            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17430                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17431                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17432                        .valueAt(i);
17433                if (userId != thisUserId) {
17434                    continue;
17435                }
17436                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17437                while (it.hasNext()) {
17438                    PersistentPreferredActivity ppa = it.next();
17439                    // Mark entry for removal only if it matches the package name.
17440                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17441                        if (removed == null) {
17442                            removed = new ArrayList<PersistentPreferredActivity>();
17443                        }
17444                        removed.add(ppa);
17445                    }
17446                }
17447                if (removed != null) {
17448                    for (int j=0; j<removed.size(); j++) {
17449                        PersistentPreferredActivity ppa = removed.get(j);
17450                        ppir.removeFilter(ppa);
17451                    }
17452                    changed = true;
17453                }
17454            }
17455
17456            if (changed) {
17457                scheduleWritePackageRestrictionsLocked(userId);
17458                postPreferredActivityChangedBroadcast(userId);
17459            }
17460        }
17461    }
17462
17463    /**
17464     * Common machinery for picking apart a restored XML blob and passing
17465     * it to a caller-supplied functor to be applied to the running system.
17466     */
17467    private void restoreFromXml(XmlPullParser parser, int userId,
17468            String expectedStartTag, BlobXmlRestorer functor)
17469            throws IOException, XmlPullParserException {
17470        int type;
17471        while ((type = parser.next()) != XmlPullParser.START_TAG
17472                && type != XmlPullParser.END_DOCUMENT) {
17473        }
17474        if (type != XmlPullParser.START_TAG) {
17475            // oops didn't find a start tag?!
17476            if (DEBUG_BACKUP) {
17477                Slog.e(TAG, "Didn't find start tag during restore");
17478            }
17479            return;
17480        }
17481Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17482        // this is supposed to be TAG_PREFERRED_BACKUP
17483        if (!expectedStartTag.equals(parser.getName())) {
17484            if (DEBUG_BACKUP) {
17485                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17486            }
17487            return;
17488        }
17489
17490        // skip interfering stuff, then we're aligned with the backing implementation
17491        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17492Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17493        functor.apply(parser, userId);
17494    }
17495
17496    private interface BlobXmlRestorer {
17497        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17498    }
17499
17500    /**
17501     * Non-Binder method, support for the backup/restore mechanism: write the
17502     * full set of preferred activities in its canonical XML format.  Returns the
17503     * XML output as a byte array, or null if there is none.
17504     */
17505    @Override
17506    public byte[] getPreferredActivityBackup(int userId) {
17507        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17508            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17509        }
17510
17511        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17512        try {
17513            final XmlSerializer serializer = new FastXmlSerializer();
17514            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17515            serializer.startDocument(null, true);
17516            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17517
17518            synchronized (mPackages) {
17519                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17520            }
17521
17522            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17523            serializer.endDocument();
17524            serializer.flush();
17525        } catch (Exception e) {
17526            if (DEBUG_BACKUP) {
17527                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17528            }
17529            return null;
17530        }
17531
17532        return dataStream.toByteArray();
17533    }
17534
17535    @Override
17536    public void restorePreferredActivities(byte[] backup, int userId) {
17537        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17538            throw new SecurityException("Only the system may call restorePreferredActivities()");
17539        }
17540
17541        try {
17542            final XmlPullParser parser = Xml.newPullParser();
17543            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17544            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17545                    new BlobXmlRestorer() {
17546                        @Override
17547                        public void apply(XmlPullParser parser, int userId)
17548                                throws XmlPullParserException, IOException {
17549                            synchronized (mPackages) {
17550                                mSettings.readPreferredActivitiesLPw(parser, userId);
17551                            }
17552                        }
17553                    } );
17554        } catch (Exception e) {
17555            if (DEBUG_BACKUP) {
17556                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17557            }
17558        }
17559    }
17560
17561    /**
17562     * Non-Binder method, support for the backup/restore mechanism: write the
17563     * default browser (etc) settings in its canonical XML format.  Returns the default
17564     * browser XML representation as a byte array, or null if there is none.
17565     */
17566    @Override
17567    public byte[] getDefaultAppsBackup(int userId) {
17568        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17569            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17570        }
17571
17572        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17573        try {
17574            final XmlSerializer serializer = new FastXmlSerializer();
17575            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17576            serializer.startDocument(null, true);
17577            serializer.startTag(null, TAG_DEFAULT_APPS);
17578
17579            synchronized (mPackages) {
17580                mSettings.writeDefaultAppsLPr(serializer, userId);
17581            }
17582
17583            serializer.endTag(null, TAG_DEFAULT_APPS);
17584            serializer.endDocument();
17585            serializer.flush();
17586        } catch (Exception e) {
17587            if (DEBUG_BACKUP) {
17588                Slog.e(TAG, "Unable to write default apps for backup", e);
17589            }
17590            return null;
17591        }
17592
17593        return dataStream.toByteArray();
17594    }
17595
17596    @Override
17597    public void restoreDefaultApps(byte[] backup, int userId) {
17598        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17599            throw new SecurityException("Only the system may call restoreDefaultApps()");
17600        }
17601
17602        try {
17603            final XmlPullParser parser = Xml.newPullParser();
17604            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17605            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17606                    new BlobXmlRestorer() {
17607                        @Override
17608                        public void apply(XmlPullParser parser, int userId)
17609                                throws XmlPullParserException, IOException {
17610                            synchronized (mPackages) {
17611                                mSettings.readDefaultAppsLPw(parser, userId);
17612                            }
17613                        }
17614                    } );
17615        } catch (Exception e) {
17616            if (DEBUG_BACKUP) {
17617                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17618            }
17619        }
17620    }
17621
17622    @Override
17623    public byte[] getIntentFilterVerificationBackup(int userId) {
17624        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17625            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17626        }
17627
17628        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17629        try {
17630            final XmlSerializer serializer = new FastXmlSerializer();
17631            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17632            serializer.startDocument(null, true);
17633            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17634
17635            synchronized (mPackages) {
17636                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17637            }
17638
17639            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17640            serializer.endDocument();
17641            serializer.flush();
17642        } catch (Exception e) {
17643            if (DEBUG_BACKUP) {
17644                Slog.e(TAG, "Unable to write default apps for backup", e);
17645            }
17646            return null;
17647        }
17648
17649        return dataStream.toByteArray();
17650    }
17651
17652    @Override
17653    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17654        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17655            throw new SecurityException("Only the system may call restorePreferredActivities()");
17656        }
17657
17658        try {
17659            final XmlPullParser parser = Xml.newPullParser();
17660            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17661            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17662                    new BlobXmlRestorer() {
17663                        @Override
17664                        public void apply(XmlPullParser parser, int userId)
17665                                throws XmlPullParserException, IOException {
17666                            synchronized (mPackages) {
17667                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17668                                mSettings.writeLPr();
17669                            }
17670                        }
17671                    } );
17672        } catch (Exception e) {
17673            if (DEBUG_BACKUP) {
17674                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17675            }
17676        }
17677    }
17678
17679    @Override
17680    public byte[] getPermissionGrantBackup(int userId) {
17681        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17682            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17683        }
17684
17685        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17686        try {
17687            final XmlSerializer serializer = new FastXmlSerializer();
17688            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17689            serializer.startDocument(null, true);
17690            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17691
17692            synchronized (mPackages) {
17693                serializeRuntimePermissionGrantsLPr(serializer, userId);
17694            }
17695
17696            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17697            serializer.endDocument();
17698            serializer.flush();
17699        } catch (Exception e) {
17700            if (DEBUG_BACKUP) {
17701                Slog.e(TAG, "Unable to write default apps for backup", e);
17702            }
17703            return null;
17704        }
17705
17706        return dataStream.toByteArray();
17707    }
17708
17709    @Override
17710    public void restorePermissionGrants(byte[] backup, int userId) {
17711        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17712            throw new SecurityException("Only the system may call restorePermissionGrants()");
17713        }
17714
17715        try {
17716            final XmlPullParser parser = Xml.newPullParser();
17717            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17718            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17719                    new BlobXmlRestorer() {
17720                        @Override
17721                        public void apply(XmlPullParser parser, int userId)
17722                                throws XmlPullParserException, IOException {
17723                            synchronized (mPackages) {
17724                                processRestoredPermissionGrantsLPr(parser, userId);
17725                            }
17726                        }
17727                    } );
17728        } catch (Exception e) {
17729            if (DEBUG_BACKUP) {
17730                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17731            }
17732        }
17733    }
17734
17735    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17736            throws IOException {
17737        serializer.startTag(null, TAG_ALL_GRANTS);
17738
17739        final int N = mSettings.mPackages.size();
17740        for (int i = 0; i < N; i++) {
17741            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17742            boolean pkgGrantsKnown = false;
17743
17744            PermissionsState packagePerms = ps.getPermissionsState();
17745
17746            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17747                final int grantFlags = state.getFlags();
17748                // only look at grants that are not system/policy fixed
17749                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17750                    final boolean isGranted = state.isGranted();
17751                    // And only back up the user-twiddled state bits
17752                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17753                        final String packageName = mSettings.mPackages.keyAt(i);
17754                        if (!pkgGrantsKnown) {
17755                            serializer.startTag(null, TAG_GRANT);
17756                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17757                            pkgGrantsKnown = true;
17758                        }
17759
17760                        final boolean userSet =
17761                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17762                        final boolean userFixed =
17763                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17764                        final boolean revoke =
17765                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17766
17767                        serializer.startTag(null, TAG_PERMISSION);
17768                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17769                        if (isGranted) {
17770                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17771                        }
17772                        if (userSet) {
17773                            serializer.attribute(null, ATTR_USER_SET, "true");
17774                        }
17775                        if (userFixed) {
17776                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17777                        }
17778                        if (revoke) {
17779                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17780                        }
17781                        serializer.endTag(null, TAG_PERMISSION);
17782                    }
17783                }
17784            }
17785
17786            if (pkgGrantsKnown) {
17787                serializer.endTag(null, TAG_GRANT);
17788            }
17789        }
17790
17791        serializer.endTag(null, TAG_ALL_GRANTS);
17792    }
17793
17794    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17795            throws XmlPullParserException, IOException {
17796        String pkgName = null;
17797        int outerDepth = parser.getDepth();
17798        int type;
17799        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17800                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17801            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17802                continue;
17803            }
17804
17805            final String tagName = parser.getName();
17806            if (tagName.equals(TAG_GRANT)) {
17807                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17808                if (DEBUG_BACKUP) {
17809                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17810                }
17811            } else if (tagName.equals(TAG_PERMISSION)) {
17812
17813                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17814                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17815
17816                int newFlagSet = 0;
17817                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17818                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17819                }
17820                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17821                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17822                }
17823                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17824                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17825                }
17826                if (DEBUG_BACKUP) {
17827                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17828                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17829                }
17830                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17831                if (ps != null) {
17832                    // Already installed so we apply the grant immediately
17833                    if (DEBUG_BACKUP) {
17834                        Slog.v(TAG, "        + already installed; applying");
17835                    }
17836                    PermissionsState perms = ps.getPermissionsState();
17837                    BasePermission bp = mSettings.mPermissions.get(permName);
17838                    if (bp != null) {
17839                        if (isGranted) {
17840                            perms.grantRuntimePermission(bp, userId);
17841                        }
17842                        if (newFlagSet != 0) {
17843                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17844                        }
17845                    }
17846                } else {
17847                    // Need to wait for post-restore install to apply the grant
17848                    if (DEBUG_BACKUP) {
17849                        Slog.v(TAG, "        - not yet installed; saving for later");
17850                    }
17851                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17852                            isGranted, newFlagSet, userId);
17853                }
17854            } else {
17855                PackageManagerService.reportSettingsProblem(Log.WARN,
17856                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17857                XmlUtils.skipCurrentTag(parser);
17858            }
17859        }
17860
17861        scheduleWriteSettingsLocked();
17862        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17863    }
17864
17865    @Override
17866    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17867            int sourceUserId, int targetUserId, int flags) {
17868        mContext.enforceCallingOrSelfPermission(
17869                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17870        int callingUid = Binder.getCallingUid();
17871        enforceOwnerRights(ownerPackage, callingUid);
17872        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17873        if (intentFilter.countActions() == 0) {
17874            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17875            return;
17876        }
17877        synchronized (mPackages) {
17878            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17879                    ownerPackage, targetUserId, flags);
17880            CrossProfileIntentResolver resolver =
17881                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17882            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17883            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17884            if (existing != null) {
17885                int size = existing.size();
17886                for (int i = 0; i < size; i++) {
17887                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17888                        return;
17889                    }
17890                }
17891            }
17892            resolver.addFilter(newFilter);
17893            scheduleWritePackageRestrictionsLocked(sourceUserId);
17894        }
17895    }
17896
17897    @Override
17898    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17899        mContext.enforceCallingOrSelfPermission(
17900                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17901        int callingUid = Binder.getCallingUid();
17902        enforceOwnerRights(ownerPackage, callingUid);
17903        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17904        synchronized (mPackages) {
17905            CrossProfileIntentResolver resolver =
17906                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17907            ArraySet<CrossProfileIntentFilter> set =
17908                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17909            for (CrossProfileIntentFilter filter : set) {
17910                if (filter.getOwnerPackage().equals(ownerPackage)) {
17911                    resolver.removeFilter(filter);
17912                }
17913            }
17914            scheduleWritePackageRestrictionsLocked(sourceUserId);
17915        }
17916    }
17917
17918    // Enforcing that callingUid is owning pkg on userId
17919    private void enforceOwnerRights(String pkg, int callingUid) {
17920        // The system owns everything.
17921        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17922            return;
17923        }
17924        int callingUserId = UserHandle.getUserId(callingUid);
17925        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17926        if (pi == null) {
17927            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17928                    + callingUserId);
17929        }
17930        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17931            throw new SecurityException("Calling uid " + callingUid
17932                    + " does not own package " + pkg);
17933        }
17934    }
17935
17936    @Override
17937    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17938        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17939    }
17940
17941    private Intent getHomeIntent() {
17942        Intent intent = new Intent(Intent.ACTION_MAIN);
17943        intent.addCategory(Intent.CATEGORY_HOME);
17944        intent.addCategory(Intent.CATEGORY_DEFAULT);
17945        return intent;
17946    }
17947
17948    private IntentFilter getHomeFilter() {
17949        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17950        filter.addCategory(Intent.CATEGORY_HOME);
17951        filter.addCategory(Intent.CATEGORY_DEFAULT);
17952        return filter;
17953    }
17954
17955    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17956            int userId) {
17957        Intent intent  = getHomeIntent();
17958        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17959                PackageManager.GET_META_DATA, userId);
17960        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17961                true, false, false, userId);
17962
17963        allHomeCandidates.clear();
17964        if (list != null) {
17965            for (ResolveInfo ri : list) {
17966                allHomeCandidates.add(ri);
17967            }
17968        }
17969        return (preferred == null || preferred.activityInfo == null)
17970                ? null
17971                : new ComponentName(preferred.activityInfo.packageName,
17972                        preferred.activityInfo.name);
17973    }
17974
17975    @Override
17976    public void setHomeActivity(ComponentName comp, int userId) {
17977        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17978        getHomeActivitiesAsUser(homeActivities, userId);
17979
17980        boolean found = false;
17981
17982        final int size = homeActivities.size();
17983        final ComponentName[] set = new ComponentName[size];
17984        for (int i = 0; i < size; i++) {
17985            final ResolveInfo candidate = homeActivities.get(i);
17986            final ActivityInfo info = candidate.activityInfo;
17987            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17988            set[i] = activityName;
17989            if (!found && activityName.equals(comp)) {
17990                found = true;
17991            }
17992        }
17993        if (!found) {
17994            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17995                    + userId);
17996        }
17997        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17998                set, comp, userId);
17999    }
18000
18001    private @Nullable String getSetupWizardPackageName() {
18002        final Intent intent = new Intent(Intent.ACTION_MAIN);
18003        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
18004
18005        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18006                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18007                        | MATCH_DISABLED_COMPONENTS,
18008                UserHandle.myUserId());
18009        if (matches.size() == 1) {
18010            return matches.get(0).getComponentInfo().packageName;
18011        } else {
18012            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
18013                    + ": matches=" + matches);
18014            return null;
18015        }
18016    }
18017
18018    private @Nullable String getStorageManagerPackageName() {
18019        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
18020
18021        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18022                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18023                        | MATCH_DISABLED_COMPONENTS,
18024                UserHandle.myUserId());
18025        if (matches.size() == 1) {
18026            return matches.get(0).getComponentInfo().packageName;
18027        } else {
18028            Slog.e(TAG, "There should probably be exactly one storage manager; found "
18029                    + matches.size() + ": matches=" + matches);
18030            return null;
18031        }
18032    }
18033
18034    @Override
18035    public void setApplicationEnabledSetting(String appPackageName,
18036            int newState, int flags, int userId, String callingPackage) {
18037        if (!sUserManager.exists(userId)) return;
18038        if (callingPackage == null) {
18039            callingPackage = Integer.toString(Binder.getCallingUid());
18040        }
18041        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
18042    }
18043
18044    @Override
18045    public void setComponentEnabledSetting(ComponentName componentName,
18046            int newState, int flags, int userId) {
18047        if (!sUserManager.exists(userId)) return;
18048        setEnabledSetting(componentName.getPackageName(),
18049                componentName.getClassName(), newState, flags, userId, null);
18050    }
18051
18052    private void setEnabledSetting(final String packageName, String className, int newState,
18053            final int flags, int userId, String callingPackage) {
18054        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
18055              || newState == COMPONENT_ENABLED_STATE_ENABLED
18056              || newState == COMPONENT_ENABLED_STATE_DISABLED
18057              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18058              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
18059            throw new IllegalArgumentException("Invalid new component state: "
18060                    + newState);
18061        }
18062        PackageSetting pkgSetting;
18063        final int uid = Binder.getCallingUid();
18064        final int permission;
18065        if (uid == Process.SYSTEM_UID) {
18066            permission = PackageManager.PERMISSION_GRANTED;
18067        } else {
18068            permission = mContext.checkCallingOrSelfPermission(
18069                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18070        }
18071        enforceCrossUserPermission(uid, userId,
18072                false /* requireFullPermission */, true /* checkShell */, "set enabled");
18073        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18074        boolean sendNow = false;
18075        boolean isApp = (className == null);
18076        String componentName = isApp ? packageName : className;
18077        int packageUid = -1;
18078        ArrayList<String> components;
18079
18080        // writer
18081        synchronized (mPackages) {
18082            pkgSetting = mSettings.mPackages.get(packageName);
18083            if (pkgSetting == null) {
18084                if (className == null) {
18085                    throw new IllegalArgumentException("Unknown package: " + packageName);
18086                }
18087                throw new IllegalArgumentException(
18088                        "Unknown component: " + packageName + "/" + className);
18089            }
18090        }
18091
18092        // Limit who can change which apps
18093        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
18094            // Don't allow apps that don't have permission to modify other apps
18095            if (!allowedByPermission) {
18096                throw new SecurityException(
18097                        "Permission Denial: attempt to change component state from pid="
18098                        + Binder.getCallingPid()
18099                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
18100            }
18101            // Don't allow changing protected packages.
18102            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
18103                throw new SecurityException("Cannot disable a protected package: " + packageName);
18104            }
18105        }
18106
18107        synchronized (mPackages) {
18108            if (uid == Process.SHELL_UID
18109                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
18110                // Shell can only change whole packages between ENABLED and DISABLED_USER states
18111                // unless it is a test package.
18112                int oldState = pkgSetting.getEnabled(userId);
18113                if (className == null
18114                    &&
18115                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
18116                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
18117                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
18118                    &&
18119                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18120                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
18121                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
18122                    // ok
18123                } else {
18124                    throw new SecurityException(
18125                            "Shell cannot change component state for " + packageName + "/"
18126                            + className + " to " + newState);
18127                }
18128            }
18129            if (className == null) {
18130                // We're dealing with an application/package level state change
18131                if (pkgSetting.getEnabled(userId) == newState) {
18132                    // Nothing to do
18133                    return;
18134                }
18135                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
18136                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
18137                    // Don't care about who enables an app.
18138                    callingPackage = null;
18139                }
18140                pkgSetting.setEnabled(newState, userId, callingPackage);
18141                // pkgSetting.pkg.mSetEnabled = newState;
18142            } else {
18143                // We're dealing with a component level state change
18144                // First, verify that this is a valid class name.
18145                PackageParser.Package pkg = pkgSetting.pkg;
18146                if (pkg == null || !pkg.hasComponentClassName(className)) {
18147                    if (pkg != null &&
18148                            pkg.applicationInfo.targetSdkVersion >=
18149                                    Build.VERSION_CODES.JELLY_BEAN) {
18150                        throw new IllegalArgumentException("Component class " + className
18151                                + " does not exist in " + packageName);
18152                    } else {
18153                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18154                                + className + " does not exist in " + packageName);
18155                    }
18156                }
18157                switch (newState) {
18158                case COMPONENT_ENABLED_STATE_ENABLED:
18159                    if (!pkgSetting.enableComponentLPw(className, userId)) {
18160                        return;
18161                    }
18162                    break;
18163                case COMPONENT_ENABLED_STATE_DISABLED:
18164                    if (!pkgSetting.disableComponentLPw(className, userId)) {
18165                        return;
18166                    }
18167                    break;
18168                case COMPONENT_ENABLED_STATE_DEFAULT:
18169                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
18170                        return;
18171                    }
18172                    break;
18173                default:
18174                    Slog.e(TAG, "Invalid new component state: " + newState);
18175                    return;
18176                }
18177            }
18178            scheduleWritePackageRestrictionsLocked(userId);
18179            components = mPendingBroadcasts.get(userId, packageName);
18180            final boolean newPackage = components == null;
18181            if (newPackage) {
18182                components = new ArrayList<String>();
18183            }
18184            if (!components.contains(componentName)) {
18185                components.add(componentName);
18186            }
18187            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18188                sendNow = true;
18189                // Purge entry from pending broadcast list if another one exists already
18190                // since we are sending one right away.
18191                mPendingBroadcasts.remove(userId, packageName);
18192            } else {
18193                if (newPackage) {
18194                    mPendingBroadcasts.put(userId, packageName, components);
18195                }
18196                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18197                    // Schedule a message
18198                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18199                }
18200            }
18201        }
18202
18203        long callingId = Binder.clearCallingIdentity();
18204        try {
18205            if (sendNow) {
18206                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18207                sendPackageChangedBroadcast(packageName,
18208                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18209            }
18210        } finally {
18211            Binder.restoreCallingIdentity(callingId);
18212        }
18213    }
18214
18215    @Override
18216    public void flushPackageRestrictionsAsUser(int userId) {
18217        if (!sUserManager.exists(userId)) {
18218            return;
18219        }
18220        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18221                false /* checkShell */, "flushPackageRestrictions");
18222        synchronized (mPackages) {
18223            mSettings.writePackageRestrictionsLPr(userId);
18224            mDirtyUsers.remove(userId);
18225            if (mDirtyUsers.isEmpty()) {
18226                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18227            }
18228        }
18229    }
18230
18231    private void sendPackageChangedBroadcast(String packageName,
18232            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18233        if (DEBUG_INSTALL)
18234            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18235                    + componentNames);
18236        Bundle extras = new Bundle(4);
18237        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18238        String nameList[] = new String[componentNames.size()];
18239        componentNames.toArray(nameList);
18240        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18241        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18242        extras.putInt(Intent.EXTRA_UID, packageUid);
18243        // If this is not reporting a change of the overall package, then only send it
18244        // to registered receivers.  We don't want to launch a swath of apps for every
18245        // little component state change.
18246        final int flags = !componentNames.contains(packageName)
18247                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18248        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18249                new int[] {UserHandle.getUserId(packageUid)});
18250    }
18251
18252    @Override
18253    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18254        if (!sUserManager.exists(userId)) return;
18255        final int uid = Binder.getCallingUid();
18256        final int permission = mContext.checkCallingOrSelfPermission(
18257                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18258        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18259        enforceCrossUserPermission(uid, userId,
18260                true /* requireFullPermission */, true /* checkShell */, "stop package");
18261        // writer
18262        synchronized (mPackages) {
18263            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18264                    allowedByPermission, uid, userId)) {
18265                scheduleWritePackageRestrictionsLocked(userId);
18266            }
18267        }
18268    }
18269
18270    @Override
18271    public String getInstallerPackageName(String packageName) {
18272        // reader
18273        synchronized (mPackages) {
18274            return mSettings.getInstallerPackageNameLPr(packageName);
18275        }
18276    }
18277
18278    public boolean isOrphaned(String packageName) {
18279        // reader
18280        synchronized (mPackages) {
18281            return mSettings.isOrphaned(packageName);
18282        }
18283    }
18284
18285    @Override
18286    public int getApplicationEnabledSetting(String packageName, int userId) {
18287        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18288        int uid = Binder.getCallingUid();
18289        enforceCrossUserPermission(uid, userId,
18290                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18291        // reader
18292        synchronized (mPackages) {
18293            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18294        }
18295    }
18296
18297    @Override
18298    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18299        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18300        int uid = Binder.getCallingUid();
18301        enforceCrossUserPermission(uid, userId,
18302                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18303        // reader
18304        synchronized (mPackages) {
18305            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18306        }
18307    }
18308
18309    @Override
18310    public void enterSafeMode() {
18311        enforceSystemOrRoot("Only the system can request entering safe mode");
18312
18313        if (!mSystemReady) {
18314            mSafeMode = true;
18315        }
18316    }
18317
18318    @Override
18319    public void systemReady() {
18320        mSystemReady = true;
18321
18322        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18323        // disabled after already being started.
18324        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18325                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18326
18327        // Read the compatibilty setting when the system is ready.
18328        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18329                mContext.getContentResolver(),
18330                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18331        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18332        if (DEBUG_SETTINGS) {
18333            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18334        }
18335
18336        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18337
18338        synchronized (mPackages) {
18339            // Verify that all of the preferred activity components actually
18340            // exist.  It is possible for applications to be updated and at
18341            // that point remove a previously declared activity component that
18342            // had been set as a preferred activity.  We try to clean this up
18343            // the next time we encounter that preferred activity, but it is
18344            // possible for the user flow to never be able to return to that
18345            // situation so here we do a sanity check to make sure we haven't
18346            // left any junk around.
18347            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18348            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18349                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18350                removed.clear();
18351                for (PreferredActivity pa : pir.filterSet()) {
18352                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18353                        removed.add(pa);
18354                    }
18355                }
18356                if (removed.size() > 0) {
18357                    for (int r=0; r<removed.size(); r++) {
18358                        PreferredActivity pa = removed.get(r);
18359                        Slog.w(TAG, "Removing dangling preferred activity: "
18360                                + pa.mPref.mComponent);
18361                        pir.removeFilter(pa);
18362                    }
18363                    mSettings.writePackageRestrictionsLPr(
18364                            mSettings.mPreferredActivities.keyAt(i));
18365                }
18366            }
18367
18368            for (int userId : UserManagerService.getInstance().getUserIds()) {
18369                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18370                    grantPermissionsUserIds = ArrayUtils.appendInt(
18371                            grantPermissionsUserIds, userId);
18372                }
18373            }
18374        }
18375        sUserManager.systemReady();
18376
18377        // If we upgraded grant all default permissions before kicking off.
18378        for (int userId : grantPermissionsUserIds) {
18379            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18380        }
18381
18382        // If we did not grant default permissions, we preload from this the
18383        // default permission exceptions lazily to ensure we don't hit the
18384        // disk on a new user creation.
18385        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18386            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18387        }
18388
18389        // Kick off any messages waiting for system ready
18390        if (mPostSystemReadyMessages != null) {
18391            for (Message msg : mPostSystemReadyMessages) {
18392                msg.sendToTarget();
18393            }
18394            mPostSystemReadyMessages = null;
18395        }
18396
18397        // Watch for external volumes that come and go over time
18398        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18399        storage.registerListener(mStorageListener);
18400
18401        mInstallerService.systemReady();
18402        mPackageDexOptimizer.systemReady();
18403
18404        MountServiceInternal mountServiceInternal = LocalServices.getService(
18405                MountServiceInternal.class);
18406        mountServiceInternal.addExternalStoragePolicy(
18407                new MountServiceInternal.ExternalStorageMountPolicy() {
18408            @Override
18409            public int getMountMode(int uid, String packageName) {
18410                if (Process.isIsolated(uid)) {
18411                    return Zygote.MOUNT_EXTERNAL_NONE;
18412                }
18413                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18414                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18415                }
18416                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18417                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18418                }
18419                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18420                    return Zygote.MOUNT_EXTERNAL_READ;
18421                }
18422                return Zygote.MOUNT_EXTERNAL_WRITE;
18423            }
18424
18425            @Override
18426            public boolean hasExternalStorage(int uid, String packageName) {
18427                return true;
18428            }
18429        });
18430
18431        // Now that we're mostly running, clean up stale users and apps
18432        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18433        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18434    }
18435
18436    @Override
18437    public boolean isSafeMode() {
18438        return mSafeMode;
18439    }
18440
18441    @Override
18442    public boolean hasSystemUidErrors() {
18443        return mHasSystemUidErrors;
18444    }
18445
18446    static String arrayToString(int[] array) {
18447        StringBuffer buf = new StringBuffer(128);
18448        buf.append('[');
18449        if (array != null) {
18450            for (int i=0; i<array.length; i++) {
18451                if (i > 0) buf.append(", ");
18452                buf.append(array[i]);
18453            }
18454        }
18455        buf.append(']');
18456        return buf.toString();
18457    }
18458
18459    static class DumpState {
18460        public static final int DUMP_LIBS = 1 << 0;
18461        public static final int DUMP_FEATURES = 1 << 1;
18462        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18463        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18464        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18465        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18466        public static final int DUMP_PERMISSIONS = 1 << 6;
18467        public static final int DUMP_PACKAGES = 1 << 7;
18468        public static final int DUMP_SHARED_USERS = 1 << 8;
18469        public static final int DUMP_MESSAGES = 1 << 9;
18470        public static final int DUMP_PROVIDERS = 1 << 10;
18471        public static final int DUMP_VERIFIERS = 1 << 11;
18472        public static final int DUMP_PREFERRED = 1 << 12;
18473        public static final int DUMP_PREFERRED_XML = 1 << 13;
18474        public static final int DUMP_KEYSETS = 1 << 14;
18475        public static final int DUMP_VERSION = 1 << 15;
18476        public static final int DUMP_INSTALLS = 1 << 16;
18477        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18478        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18479        public static final int DUMP_FROZEN = 1 << 19;
18480        public static final int DUMP_DEXOPT = 1 << 20;
18481        public static final int DUMP_COMPILER_STATS = 1 << 21;
18482
18483        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18484
18485        private int mTypes;
18486
18487        private int mOptions;
18488
18489        private boolean mTitlePrinted;
18490
18491        private SharedUserSetting mSharedUser;
18492
18493        public boolean isDumping(int type) {
18494            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18495                return true;
18496            }
18497
18498            return (mTypes & type) != 0;
18499        }
18500
18501        public void setDump(int type) {
18502            mTypes |= type;
18503        }
18504
18505        public boolean isOptionEnabled(int option) {
18506            return (mOptions & option) != 0;
18507        }
18508
18509        public void setOptionEnabled(int option) {
18510            mOptions |= option;
18511        }
18512
18513        public boolean onTitlePrinted() {
18514            final boolean printed = mTitlePrinted;
18515            mTitlePrinted = true;
18516            return printed;
18517        }
18518
18519        public boolean getTitlePrinted() {
18520            return mTitlePrinted;
18521        }
18522
18523        public void setTitlePrinted(boolean enabled) {
18524            mTitlePrinted = enabled;
18525        }
18526
18527        public SharedUserSetting getSharedUser() {
18528            return mSharedUser;
18529        }
18530
18531        public void setSharedUser(SharedUserSetting user) {
18532            mSharedUser = user;
18533        }
18534    }
18535
18536    @Override
18537    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18538            FileDescriptor err, String[] args, ShellCallback callback,
18539            ResultReceiver resultReceiver) {
18540        (new PackageManagerShellCommand(this)).exec(
18541                this, in, out, err, args, callback, resultReceiver);
18542    }
18543
18544    @Override
18545    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18546        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18547                != PackageManager.PERMISSION_GRANTED) {
18548            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18549                    + Binder.getCallingPid()
18550                    + ", uid=" + Binder.getCallingUid()
18551                    + " without permission "
18552                    + android.Manifest.permission.DUMP);
18553            return;
18554        }
18555
18556        DumpState dumpState = new DumpState();
18557        boolean fullPreferred = false;
18558        boolean checkin = false;
18559
18560        String packageName = null;
18561        ArraySet<String> permissionNames = null;
18562
18563        int opti = 0;
18564        while (opti < args.length) {
18565            String opt = args[opti];
18566            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18567                break;
18568            }
18569            opti++;
18570
18571            if ("-a".equals(opt)) {
18572                // Right now we only know how to print all.
18573            } else if ("-h".equals(opt)) {
18574                pw.println("Package manager dump options:");
18575                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18576                pw.println("    --checkin: dump for a checkin");
18577                pw.println("    -f: print details of intent filters");
18578                pw.println("    -h: print this help");
18579                pw.println("  cmd may be one of:");
18580                pw.println("    l[ibraries]: list known shared libraries");
18581                pw.println("    f[eatures]: list device features");
18582                pw.println("    k[eysets]: print known keysets");
18583                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18584                pw.println("    perm[issions]: dump permissions");
18585                pw.println("    permission [name ...]: dump declaration and use of given permission");
18586                pw.println("    pref[erred]: print preferred package settings");
18587                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18588                pw.println("    prov[iders]: dump content providers");
18589                pw.println("    p[ackages]: dump installed packages");
18590                pw.println("    s[hared-users]: dump shared user IDs");
18591                pw.println("    m[essages]: print collected runtime messages");
18592                pw.println("    v[erifiers]: print package verifier info");
18593                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18594                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18595                pw.println("    version: print database version info");
18596                pw.println("    write: write current settings now");
18597                pw.println("    installs: details about install sessions");
18598                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18599                pw.println("    dexopt: dump dexopt state");
18600                pw.println("    compiler-stats: dump compiler statistics");
18601                pw.println("    <package.name>: info about given package");
18602                return;
18603            } else if ("--checkin".equals(opt)) {
18604                checkin = true;
18605            } else if ("-f".equals(opt)) {
18606                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18607            } else {
18608                pw.println("Unknown argument: " + opt + "; use -h for help");
18609            }
18610        }
18611
18612        // Is the caller requesting to dump a particular piece of data?
18613        if (opti < args.length) {
18614            String cmd = args[opti];
18615            opti++;
18616            // Is this a package name?
18617            if ("android".equals(cmd) || cmd.contains(".")) {
18618                packageName = cmd;
18619                // When dumping a single package, we always dump all of its
18620                // filter information since the amount of data will be reasonable.
18621                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18622            } else if ("check-permission".equals(cmd)) {
18623                if (opti >= args.length) {
18624                    pw.println("Error: check-permission missing permission argument");
18625                    return;
18626                }
18627                String perm = args[opti];
18628                opti++;
18629                if (opti >= args.length) {
18630                    pw.println("Error: check-permission missing package argument");
18631                    return;
18632                }
18633                String pkg = args[opti];
18634                opti++;
18635                int user = UserHandle.getUserId(Binder.getCallingUid());
18636                if (opti < args.length) {
18637                    try {
18638                        user = Integer.parseInt(args[opti]);
18639                    } catch (NumberFormatException e) {
18640                        pw.println("Error: check-permission user argument is not a number: "
18641                                + args[opti]);
18642                        return;
18643                    }
18644                }
18645                pw.println(checkPermission(perm, pkg, user));
18646                return;
18647            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18648                dumpState.setDump(DumpState.DUMP_LIBS);
18649            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18650                dumpState.setDump(DumpState.DUMP_FEATURES);
18651            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18652                if (opti >= args.length) {
18653                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18654                            | DumpState.DUMP_SERVICE_RESOLVERS
18655                            | DumpState.DUMP_RECEIVER_RESOLVERS
18656                            | DumpState.DUMP_CONTENT_RESOLVERS);
18657                } else {
18658                    while (opti < args.length) {
18659                        String name = args[opti];
18660                        if ("a".equals(name) || "activity".equals(name)) {
18661                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18662                        } else if ("s".equals(name) || "service".equals(name)) {
18663                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18664                        } else if ("r".equals(name) || "receiver".equals(name)) {
18665                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18666                        } else if ("c".equals(name) || "content".equals(name)) {
18667                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18668                        } else {
18669                            pw.println("Error: unknown resolver table type: " + name);
18670                            return;
18671                        }
18672                        opti++;
18673                    }
18674                }
18675            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18676                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18677            } else if ("permission".equals(cmd)) {
18678                if (opti >= args.length) {
18679                    pw.println("Error: permission requires permission name");
18680                    return;
18681                }
18682                permissionNames = new ArraySet<>();
18683                while (opti < args.length) {
18684                    permissionNames.add(args[opti]);
18685                    opti++;
18686                }
18687                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18688                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18689            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18690                dumpState.setDump(DumpState.DUMP_PREFERRED);
18691            } else if ("preferred-xml".equals(cmd)) {
18692                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18693                if (opti < args.length && "--full".equals(args[opti])) {
18694                    fullPreferred = true;
18695                    opti++;
18696                }
18697            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18698                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18699            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18700                dumpState.setDump(DumpState.DUMP_PACKAGES);
18701            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18702                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18703            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18704                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18705            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18706                dumpState.setDump(DumpState.DUMP_MESSAGES);
18707            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18708                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18709            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18710                    || "intent-filter-verifiers".equals(cmd)) {
18711                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18712            } else if ("version".equals(cmd)) {
18713                dumpState.setDump(DumpState.DUMP_VERSION);
18714            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18715                dumpState.setDump(DumpState.DUMP_KEYSETS);
18716            } else if ("installs".equals(cmd)) {
18717                dumpState.setDump(DumpState.DUMP_INSTALLS);
18718            } else if ("frozen".equals(cmd)) {
18719                dumpState.setDump(DumpState.DUMP_FROZEN);
18720            } else if ("dexopt".equals(cmd)) {
18721                dumpState.setDump(DumpState.DUMP_DEXOPT);
18722            } else if ("compiler-stats".equals(cmd)) {
18723                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18724            } else if ("write".equals(cmd)) {
18725                synchronized (mPackages) {
18726                    mSettings.writeLPr();
18727                    pw.println("Settings written.");
18728                    return;
18729                }
18730            }
18731        }
18732
18733        if (checkin) {
18734            pw.println("vers,1");
18735        }
18736
18737        // reader
18738        synchronized (mPackages) {
18739            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18740                if (!checkin) {
18741                    if (dumpState.onTitlePrinted())
18742                        pw.println();
18743                    pw.println("Database versions:");
18744                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18745                }
18746            }
18747
18748            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18749                if (!checkin) {
18750                    if (dumpState.onTitlePrinted())
18751                        pw.println();
18752                    pw.println("Verifiers:");
18753                    pw.print("  Required: ");
18754                    pw.print(mRequiredVerifierPackage);
18755                    pw.print(" (uid=");
18756                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18757                            UserHandle.USER_SYSTEM));
18758                    pw.println(")");
18759                } else if (mRequiredVerifierPackage != null) {
18760                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18761                    pw.print(",");
18762                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18763                            UserHandle.USER_SYSTEM));
18764                }
18765            }
18766
18767            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18768                    packageName == null) {
18769                if (mIntentFilterVerifierComponent != null) {
18770                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18771                    if (!checkin) {
18772                        if (dumpState.onTitlePrinted())
18773                            pw.println();
18774                        pw.println("Intent Filter Verifier:");
18775                        pw.print("  Using: ");
18776                        pw.print(verifierPackageName);
18777                        pw.print(" (uid=");
18778                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18779                                UserHandle.USER_SYSTEM));
18780                        pw.println(")");
18781                    } else if (verifierPackageName != null) {
18782                        pw.print("ifv,"); pw.print(verifierPackageName);
18783                        pw.print(",");
18784                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18785                                UserHandle.USER_SYSTEM));
18786                    }
18787                } else {
18788                    pw.println();
18789                    pw.println("No Intent Filter Verifier available!");
18790                }
18791            }
18792
18793            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18794                boolean printedHeader = false;
18795                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18796                while (it.hasNext()) {
18797                    String name = it.next();
18798                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18799                    if (!checkin) {
18800                        if (!printedHeader) {
18801                            if (dumpState.onTitlePrinted())
18802                                pw.println();
18803                            pw.println("Libraries:");
18804                            printedHeader = true;
18805                        }
18806                        pw.print("  ");
18807                    } else {
18808                        pw.print("lib,");
18809                    }
18810                    pw.print(name);
18811                    if (!checkin) {
18812                        pw.print(" -> ");
18813                    }
18814                    if (ent.path != null) {
18815                        if (!checkin) {
18816                            pw.print("(jar) ");
18817                            pw.print(ent.path);
18818                        } else {
18819                            pw.print(",jar,");
18820                            pw.print(ent.path);
18821                        }
18822                    } else {
18823                        if (!checkin) {
18824                            pw.print("(apk) ");
18825                            pw.print(ent.apk);
18826                        } else {
18827                            pw.print(",apk,");
18828                            pw.print(ent.apk);
18829                        }
18830                    }
18831                    pw.println();
18832                }
18833            }
18834
18835            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18836                if (dumpState.onTitlePrinted())
18837                    pw.println();
18838                if (!checkin) {
18839                    pw.println("Features:");
18840                }
18841
18842                for (FeatureInfo feat : mAvailableFeatures.values()) {
18843                    if (checkin) {
18844                        pw.print("feat,");
18845                        pw.print(feat.name);
18846                        pw.print(",");
18847                        pw.println(feat.version);
18848                    } else {
18849                        pw.print("  ");
18850                        pw.print(feat.name);
18851                        if (feat.version > 0) {
18852                            pw.print(" version=");
18853                            pw.print(feat.version);
18854                        }
18855                        pw.println();
18856                    }
18857                }
18858            }
18859
18860            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18861                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18862                        : "Activity Resolver Table:", "  ", packageName,
18863                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18864                    dumpState.setTitlePrinted(true);
18865                }
18866            }
18867            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18868                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18869                        : "Receiver Resolver Table:", "  ", packageName,
18870                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18871                    dumpState.setTitlePrinted(true);
18872                }
18873            }
18874            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18875                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18876                        : "Service Resolver Table:", "  ", packageName,
18877                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18878                    dumpState.setTitlePrinted(true);
18879                }
18880            }
18881            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18882                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18883                        : "Provider Resolver Table:", "  ", packageName,
18884                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18885                    dumpState.setTitlePrinted(true);
18886                }
18887            }
18888
18889            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18890                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18891                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18892                    int user = mSettings.mPreferredActivities.keyAt(i);
18893                    if (pir.dump(pw,
18894                            dumpState.getTitlePrinted()
18895                                ? "\nPreferred Activities User " + user + ":"
18896                                : "Preferred Activities User " + user + ":", "  ",
18897                            packageName, true, false)) {
18898                        dumpState.setTitlePrinted(true);
18899                    }
18900                }
18901            }
18902
18903            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18904                pw.flush();
18905                FileOutputStream fout = new FileOutputStream(fd);
18906                BufferedOutputStream str = new BufferedOutputStream(fout);
18907                XmlSerializer serializer = new FastXmlSerializer();
18908                try {
18909                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18910                    serializer.startDocument(null, true);
18911                    serializer.setFeature(
18912                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18913                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18914                    serializer.endDocument();
18915                    serializer.flush();
18916                } catch (IllegalArgumentException e) {
18917                    pw.println("Failed writing: " + e);
18918                } catch (IllegalStateException e) {
18919                    pw.println("Failed writing: " + e);
18920                } catch (IOException e) {
18921                    pw.println("Failed writing: " + e);
18922                }
18923            }
18924
18925            if (!checkin
18926                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18927                    && packageName == null) {
18928                pw.println();
18929                int count = mSettings.mPackages.size();
18930                if (count == 0) {
18931                    pw.println("No applications!");
18932                    pw.println();
18933                } else {
18934                    final String prefix = "  ";
18935                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18936                    if (allPackageSettings.size() == 0) {
18937                        pw.println("No domain preferred apps!");
18938                        pw.println();
18939                    } else {
18940                        pw.println("App verification status:");
18941                        pw.println();
18942                        count = 0;
18943                        for (PackageSetting ps : allPackageSettings) {
18944                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18945                            if (ivi == null || ivi.getPackageName() == null) continue;
18946                            pw.println(prefix + "Package: " + ivi.getPackageName());
18947                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18948                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18949                            pw.println();
18950                            count++;
18951                        }
18952                        if (count == 0) {
18953                            pw.println(prefix + "No app verification established.");
18954                            pw.println();
18955                        }
18956                        for (int userId : sUserManager.getUserIds()) {
18957                            pw.println("App linkages for user " + userId + ":");
18958                            pw.println();
18959                            count = 0;
18960                            for (PackageSetting ps : allPackageSettings) {
18961                                final long status = ps.getDomainVerificationStatusForUser(userId);
18962                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18963                                    continue;
18964                                }
18965                                pw.println(prefix + "Package: " + ps.name);
18966                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18967                                String statusStr = IntentFilterVerificationInfo.
18968                                        getStatusStringFromValue(status);
18969                                pw.println(prefix + "Status:  " + statusStr);
18970                                pw.println();
18971                                count++;
18972                            }
18973                            if (count == 0) {
18974                                pw.println(prefix + "No configured app linkages.");
18975                                pw.println();
18976                            }
18977                        }
18978                    }
18979                }
18980            }
18981
18982            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18983                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18984                if (packageName == null && permissionNames == null) {
18985                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18986                        if (iperm == 0) {
18987                            if (dumpState.onTitlePrinted())
18988                                pw.println();
18989                            pw.println("AppOp Permissions:");
18990                        }
18991                        pw.print("  AppOp Permission ");
18992                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18993                        pw.println(":");
18994                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18995                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18996                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18997                        }
18998                    }
18999                }
19000            }
19001
19002            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
19003                boolean printedSomething = false;
19004                for (PackageParser.Provider p : mProviders.mProviders.values()) {
19005                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19006                        continue;
19007                    }
19008                    if (!printedSomething) {
19009                        if (dumpState.onTitlePrinted())
19010                            pw.println();
19011                        pw.println("Registered ContentProviders:");
19012                        printedSomething = true;
19013                    }
19014                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
19015                    pw.print("    "); pw.println(p.toString());
19016                }
19017                printedSomething = false;
19018                for (Map.Entry<String, PackageParser.Provider> entry :
19019                        mProvidersByAuthority.entrySet()) {
19020                    PackageParser.Provider p = entry.getValue();
19021                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19022                        continue;
19023                    }
19024                    if (!printedSomething) {
19025                        if (dumpState.onTitlePrinted())
19026                            pw.println();
19027                        pw.println("ContentProvider Authorities:");
19028                        printedSomething = true;
19029                    }
19030                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
19031                    pw.print("    "); pw.println(p.toString());
19032                    if (p.info != null && p.info.applicationInfo != null) {
19033                        final String appInfo = p.info.applicationInfo.toString();
19034                        pw.print("      applicationInfo="); pw.println(appInfo);
19035                    }
19036                }
19037            }
19038
19039            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
19040                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
19041            }
19042
19043            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
19044                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
19045            }
19046
19047            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
19048                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
19049            }
19050
19051            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
19052                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
19053            }
19054
19055            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
19056                // XXX should handle packageName != null by dumping only install data that
19057                // the given package is involved with.
19058                if (dumpState.onTitlePrinted()) pw.println();
19059                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
19060            }
19061
19062            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
19063                // XXX should handle packageName != null by dumping only install data that
19064                // the given package is involved with.
19065                if (dumpState.onTitlePrinted()) pw.println();
19066
19067                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19068                ipw.println();
19069                ipw.println("Frozen packages:");
19070                ipw.increaseIndent();
19071                if (mFrozenPackages.size() == 0) {
19072                    ipw.println("(none)");
19073                } else {
19074                    for (int i = 0; i < mFrozenPackages.size(); i++) {
19075                        ipw.println(mFrozenPackages.valueAt(i));
19076                    }
19077                }
19078                ipw.decreaseIndent();
19079            }
19080
19081            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
19082                if (dumpState.onTitlePrinted()) pw.println();
19083                dumpDexoptStateLPr(pw, packageName);
19084            }
19085
19086            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
19087                if (dumpState.onTitlePrinted()) pw.println();
19088                dumpCompilerStatsLPr(pw, packageName);
19089            }
19090
19091            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
19092                if (dumpState.onTitlePrinted()) pw.println();
19093                mSettings.dumpReadMessagesLPr(pw, dumpState);
19094
19095                pw.println();
19096                pw.println("Package warning messages:");
19097                BufferedReader in = null;
19098                String line = null;
19099                try {
19100                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19101                    while ((line = in.readLine()) != null) {
19102                        if (line.contains("ignored: updated version")) continue;
19103                        pw.println(line);
19104                    }
19105                } catch (IOException ignored) {
19106                } finally {
19107                    IoUtils.closeQuietly(in);
19108                }
19109            }
19110
19111            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
19112                BufferedReader in = null;
19113                String line = null;
19114                try {
19115                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19116                    while ((line = in.readLine()) != null) {
19117                        if (line.contains("ignored: updated version")) continue;
19118                        pw.print("msg,");
19119                        pw.println(line);
19120                    }
19121                } catch (IOException ignored) {
19122                } finally {
19123                    IoUtils.closeQuietly(in);
19124                }
19125            }
19126        }
19127    }
19128
19129    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
19130        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19131        ipw.println();
19132        ipw.println("Dexopt state:");
19133        ipw.increaseIndent();
19134        Collection<PackageParser.Package> packages = null;
19135        if (packageName != null) {
19136            PackageParser.Package targetPackage = mPackages.get(packageName);
19137            if (targetPackage != null) {
19138                packages = Collections.singletonList(targetPackage);
19139            } else {
19140                ipw.println("Unable to find package: " + packageName);
19141                return;
19142            }
19143        } else {
19144            packages = mPackages.values();
19145        }
19146
19147        for (PackageParser.Package pkg : packages) {
19148            ipw.println("[" + pkg.packageName + "]");
19149            ipw.increaseIndent();
19150            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19151            ipw.decreaseIndent();
19152        }
19153    }
19154
19155    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19156        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19157        ipw.println();
19158        ipw.println("Compiler stats:");
19159        ipw.increaseIndent();
19160        Collection<PackageParser.Package> packages = null;
19161        if (packageName != null) {
19162            PackageParser.Package targetPackage = mPackages.get(packageName);
19163            if (targetPackage != null) {
19164                packages = Collections.singletonList(targetPackage);
19165            } else {
19166                ipw.println("Unable to find package: " + packageName);
19167                return;
19168            }
19169        } else {
19170            packages = mPackages.values();
19171        }
19172
19173        for (PackageParser.Package pkg : packages) {
19174            ipw.println("[" + pkg.packageName + "]");
19175            ipw.increaseIndent();
19176
19177            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19178            if (stats == null) {
19179                ipw.println("(No recorded stats)");
19180            } else {
19181                stats.dump(ipw);
19182            }
19183            ipw.decreaseIndent();
19184        }
19185    }
19186
19187    private String dumpDomainString(String packageName) {
19188        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19189                .getList();
19190        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19191
19192        ArraySet<String> result = new ArraySet<>();
19193        if (iviList.size() > 0) {
19194            for (IntentFilterVerificationInfo ivi : iviList) {
19195                for (String host : ivi.getDomains()) {
19196                    result.add(host);
19197                }
19198            }
19199        }
19200        if (filters != null && filters.size() > 0) {
19201            for (IntentFilter filter : filters) {
19202                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19203                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19204                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19205                    result.addAll(filter.getHostsList());
19206                }
19207            }
19208        }
19209
19210        StringBuilder sb = new StringBuilder(result.size() * 16);
19211        for (String domain : result) {
19212            if (sb.length() > 0) sb.append(" ");
19213            sb.append(domain);
19214        }
19215        return sb.toString();
19216    }
19217
19218    // ------- apps on sdcard specific code -------
19219    static final boolean DEBUG_SD_INSTALL = false;
19220
19221    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19222
19223    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19224
19225    private boolean mMediaMounted = false;
19226
19227    static String getEncryptKey() {
19228        try {
19229            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19230                    SD_ENCRYPTION_KEYSTORE_NAME);
19231            if (sdEncKey == null) {
19232                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19233                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19234                if (sdEncKey == null) {
19235                    Slog.e(TAG, "Failed to create encryption keys");
19236                    return null;
19237                }
19238            }
19239            return sdEncKey;
19240        } catch (NoSuchAlgorithmException nsae) {
19241            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19242            return null;
19243        } catch (IOException ioe) {
19244            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19245            return null;
19246        }
19247    }
19248
19249    /*
19250     * Update media status on PackageManager.
19251     */
19252    @Override
19253    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19254        int callingUid = Binder.getCallingUid();
19255        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19256            throw new SecurityException("Media status can only be updated by the system");
19257        }
19258        // reader; this apparently protects mMediaMounted, but should probably
19259        // be a different lock in that case.
19260        synchronized (mPackages) {
19261            Log.i(TAG, "Updating external media status from "
19262                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19263                    + (mediaStatus ? "mounted" : "unmounted"));
19264            if (DEBUG_SD_INSTALL)
19265                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19266                        + ", mMediaMounted=" + mMediaMounted);
19267            if (mediaStatus == mMediaMounted) {
19268                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19269                        : 0, -1);
19270                mHandler.sendMessage(msg);
19271                return;
19272            }
19273            mMediaMounted = mediaStatus;
19274        }
19275        // Queue up an async operation since the package installation may take a
19276        // little while.
19277        mHandler.post(new Runnable() {
19278            public void run() {
19279                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19280            }
19281        });
19282    }
19283
19284    /**
19285     * Called by MountService when the initial ASECs to scan are available.
19286     * Should block until all the ASEC containers are finished being scanned.
19287     */
19288    public void scanAvailableAsecs() {
19289        updateExternalMediaStatusInner(true, false, false);
19290    }
19291
19292    /*
19293     * Collect information of applications on external media, map them against
19294     * existing containers and update information based on current mount status.
19295     * Please note that we always have to report status if reportStatus has been
19296     * set to true especially when unloading packages.
19297     */
19298    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19299            boolean externalStorage) {
19300        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19301        int[] uidArr = EmptyArray.INT;
19302
19303        final String[] list = PackageHelper.getSecureContainerList();
19304        if (ArrayUtils.isEmpty(list)) {
19305            Log.i(TAG, "No secure containers found");
19306        } else {
19307            // Process list of secure containers and categorize them
19308            // as active or stale based on their package internal state.
19309
19310            // reader
19311            synchronized (mPackages) {
19312                for (String cid : list) {
19313                    // Leave stages untouched for now; installer service owns them
19314                    if (PackageInstallerService.isStageName(cid)) continue;
19315
19316                    if (DEBUG_SD_INSTALL)
19317                        Log.i(TAG, "Processing container " + cid);
19318                    String pkgName = getAsecPackageName(cid);
19319                    if (pkgName == null) {
19320                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19321                        continue;
19322                    }
19323                    if (DEBUG_SD_INSTALL)
19324                        Log.i(TAG, "Looking for pkg : " + pkgName);
19325
19326                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19327                    if (ps == null) {
19328                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19329                        continue;
19330                    }
19331
19332                    /*
19333                     * Skip packages that are not external if we're unmounting
19334                     * external storage.
19335                     */
19336                    if (externalStorage && !isMounted && !isExternal(ps)) {
19337                        continue;
19338                    }
19339
19340                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19341                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19342                    // The package status is changed only if the code path
19343                    // matches between settings and the container id.
19344                    if (ps.codePathString != null
19345                            && ps.codePathString.startsWith(args.getCodePath())) {
19346                        if (DEBUG_SD_INSTALL) {
19347                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19348                                    + " at code path: " + ps.codePathString);
19349                        }
19350
19351                        // We do have a valid package installed on sdcard
19352                        processCids.put(args, ps.codePathString);
19353                        final int uid = ps.appId;
19354                        if (uid != -1) {
19355                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19356                        }
19357                    } else {
19358                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19359                                + ps.codePathString);
19360                    }
19361                }
19362            }
19363
19364            Arrays.sort(uidArr);
19365        }
19366
19367        // Process packages with valid entries.
19368        if (isMounted) {
19369            if (DEBUG_SD_INSTALL)
19370                Log.i(TAG, "Loading packages");
19371            loadMediaPackages(processCids, uidArr, externalStorage);
19372            startCleaningPackages();
19373            mInstallerService.onSecureContainersAvailable();
19374        } else {
19375            if (DEBUG_SD_INSTALL)
19376                Log.i(TAG, "Unloading packages");
19377            unloadMediaPackages(processCids, uidArr, reportStatus);
19378        }
19379    }
19380
19381    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19382            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19383        final int size = infos.size();
19384        final String[] packageNames = new String[size];
19385        final int[] packageUids = new int[size];
19386        for (int i = 0; i < size; i++) {
19387            final ApplicationInfo info = infos.get(i);
19388            packageNames[i] = info.packageName;
19389            packageUids[i] = info.uid;
19390        }
19391        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19392                finishedReceiver);
19393    }
19394
19395    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19396            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19397        sendResourcesChangedBroadcast(mediaStatus, replacing,
19398                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19399    }
19400
19401    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19402            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19403        int size = pkgList.length;
19404        if (size > 0) {
19405            // Send broadcasts here
19406            Bundle extras = new Bundle();
19407            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19408            if (uidArr != null) {
19409                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19410            }
19411            if (replacing) {
19412                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19413            }
19414            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19415                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19416            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19417        }
19418    }
19419
19420   /*
19421     * Look at potentially valid container ids from processCids If package
19422     * information doesn't match the one on record or package scanning fails,
19423     * the cid is added to list of removeCids. We currently don't delete stale
19424     * containers.
19425     */
19426    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19427            boolean externalStorage) {
19428        ArrayList<String> pkgList = new ArrayList<String>();
19429        Set<AsecInstallArgs> keys = processCids.keySet();
19430
19431        for (AsecInstallArgs args : keys) {
19432            String codePath = processCids.get(args);
19433            if (DEBUG_SD_INSTALL)
19434                Log.i(TAG, "Loading container : " + args.cid);
19435            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19436            try {
19437                // Make sure there are no container errors first.
19438                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19439                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19440                            + " when installing from sdcard");
19441                    continue;
19442                }
19443                // Check code path here.
19444                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19445                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19446                            + " does not match one in settings " + codePath);
19447                    continue;
19448                }
19449                // Parse package
19450                int parseFlags = mDefParseFlags;
19451                if (args.isExternalAsec()) {
19452                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19453                }
19454                if (args.isFwdLocked()) {
19455                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19456                }
19457
19458                synchronized (mInstallLock) {
19459                    PackageParser.Package pkg = null;
19460                    try {
19461                        // Sadly we don't know the package name yet to freeze it
19462                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19463                                SCAN_IGNORE_FROZEN, 0, null);
19464                    } catch (PackageManagerException e) {
19465                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19466                    }
19467                    // Scan the package
19468                    if (pkg != null) {
19469                        /*
19470                         * TODO why is the lock being held? doPostInstall is
19471                         * called in other places without the lock. This needs
19472                         * to be straightened out.
19473                         */
19474                        // writer
19475                        synchronized (mPackages) {
19476                            retCode = PackageManager.INSTALL_SUCCEEDED;
19477                            pkgList.add(pkg.packageName);
19478                            // Post process args
19479                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19480                                    pkg.applicationInfo.uid);
19481                        }
19482                    } else {
19483                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19484                    }
19485                }
19486
19487            } finally {
19488                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19489                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19490                }
19491            }
19492        }
19493        // writer
19494        synchronized (mPackages) {
19495            // If the platform SDK has changed since the last time we booted,
19496            // we need to re-grant app permission to catch any new ones that
19497            // appear. This is really a hack, and means that apps can in some
19498            // cases get permissions that the user didn't initially explicitly
19499            // allow... it would be nice to have some better way to handle
19500            // this situation.
19501            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19502                    : mSettings.getInternalVersion();
19503            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19504                    : StorageManager.UUID_PRIVATE_INTERNAL;
19505
19506            int updateFlags = UPDATE_PERMISSIONS_ALL;
19507            if (ver.sdkVersion != mSdkVersion) {
19508                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19509                        + mSdkVersion + "; regranting permissions for external");
19510                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19511            }
19512            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19513
19514            // Yay, everything is now upgraded
19515            ver.forceCurrent();
19516
19517            // can downgrade to reader
19518            // Persist settings
19519            mSettings.writeLPr();
19520        }
19521        // Send a broadcast to let everyone know we are done processing
19522        if (pkgList.size() > 0) {
19523            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19524        }
19525    }
19526
19527   /*
19528     * Utility method to unload a list of specified containers
19529     */
19530    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19531        // Just unmount all valid containers.
19532        for (AsecInstallArgs arg : cidArgs) {
19533            synchronized (mInstallLock) {
19534                arg.doPostDeleteLI(false);
19535           }
19536       }
19537   }
19538
19539    /*
19540     * Unload packages mounted on external media. This involves deleting package
19541     * data from internal structures, sending broadcasts about disabled packages,
19542     * gc'ing to free up references, unmounting all secure containers
19543     * corresponding to packages on external media, and posting a
19544     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19545     * that we always have to post this message if status has been requested no
19546     * matter what.
19547     */
19548    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19549            final boolean reportStatus) {
19550        if (DEBUG_SD_INSTALL)
19551            Log.i(TAG, "unloading media packages");
19552        ArrayList<String> pkgList = new ArrayList<String>();
19553        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19554        final Set<AsecInstallArgs> keys = processCids.keySet();
19555        for (AsecInstallArgs args : keys) {
19556            String pkgName = args.getPackageName();
19557            if (DEBUG_SD_INSTALL)
19558                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19559            // Delete package internally
19560            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19561            synchronized (mInstallLock) {
19562                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19563                final boolean res;
19564                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19565                        "unloadMediaPackages")) {
19566                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19567                            null);
19568                }
19569                if (res) {
19570                    pkgList.add(pkgName);
19571                } else {
19572                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19573                    failedList.add(args);
19574                }
19575            }
19576        }
19577
19578        // reader
19579        synchronized (mPackages) {
19580            // We didn't update the settings after removing each package;
19581            // write them now for all packages.
19582            mSettings.writeLPr();
19583        }
19584
19585        // We have to absolutely send UPDATED_MEDIA_STATUS only
19586        // after confirming that all the receivers processed the ordered
19587        // broadcast when packages get disabled, force a gc to clean things up.
19588        // and unload all the containers.
19589        if (pkgList.size() > 0) {
19590            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19591                    new IIntentReceiver.Stub() {
19592                public void performReceive(Intent intent, int resultCode, String data,
19593                        Bundle extras, boolean ordered, boolean sticky,
19594                        int sendingUser) throws RemoteException {
19595                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19596                            reportStatus ? 1 : 0, 1, keys);
19597                    mHandler.sendMessage(msg);
19598                }
19599            });
19600        } else {
19601            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19602                    keys);
19603            mHandler.sendMessage(msg);
19604        }
19605    }
19606
19607    private void loadPrivatePackages(final VolumeInfo vol) {
19608        mHandler.post(new Runnable() {
19609            @Override
19610            public void run() {
19611                loadPrivatePackagesInner(vol);
19612            }
19613        });
19614    }
19615
19616    private void loadPrivatePackagesInner(VolumeInfo vol) {
19617        final String volumeUuid = vol.fsUuid;
19618        if (TextUtils.isEmpty(volumeUuid)) {
19619            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19620            return;
19621        }
19622
19623        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19624        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19625        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19626
19627        final VersionInfo ver;
19628        final List<PackageSetting> packages;
19629        synchronized (mPackages) {
19630            ver = mSettings.findOrCreateVersion(volumeUuid);
19631            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19632        }
19633
19634        for (PackageSetting ps : packages) {
19635            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19636            synchronized (mInstallLock) {
19637                final PackageParser.Package pkg;
19638                try {
19639                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19640                    loaded.add(pkg.applicationInfo);
19641
19642                } catch (PackageManagerException e) {
19643                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19644                }
19645
19646                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19647                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19648                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19649                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19650                }
19651            }
19652        }
19653
19654        // Reconcile app data for all started/unlocked users
19655        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19656        final UserManager um = mContext.getSystemService(UserManager.class);
19657        UserManagerInternal umInternal = getUserManagerInternal();
19658        for (UserInfo user : um.getUsers()) {
19659            final int flags;
19660            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19661                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19662            } else if (umInternal.isUserRunning(user.id)) {
19663                flags = StorageManager.FLAG_STORAGE_DE;
19664            } else {
19665                continue;
19666            }
19667
19668            try {
19669                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19670                synchronized (mInstallLock) {
19671                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
19672                }
19673            } catch (IllegalStateException e) {
19674                // Device was probably ejected, and we'll process that event momentarily
19675                Slog.w(TAG, "Failed to prepare storage: " + e);
19676            }
19677        }
19678
19679        synchronized (mPackages) {
19680            int updateFlags = UPDATE_PERMISSIONS_ALL;
19681            if (ver.sdkVersion != mSdkVersion) {
19682                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19683                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19684                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19685            }
19686            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19687
19688            // Yay, everything is now upgraded
19689            ver.forceCurrent();
19690
19691            mSettings.writeLPr();
19692        }
19693
19694        for (PackageFreezer freezer : freezers) {
19695            freezer.close();
19696        }
19697
19698        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19699        sendResourcesChangedBroadcast(true, false, loaded, null);
19700    }
19701
19702    private void unloadPrivatePackages(final VolumeInfo vol) {
19703        mHandler.post(new Runnable() {
19704            @Override
19705            public void run() {
19706                unloadPrivatePackagesInner(vol);
19707            }
19708        });
19709    }
19710
19711    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19712        final String volumeUuid = vol.fsUuid;
19713        if (TextUtils.isEmpty(volumeUuid)) {
19714            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19715            return;
19716        }
19717
19718        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19719        synchronized (mInstallLock) {
19720        synchronized (mPackages) {
19721            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19722            for (PackageSetting ps : packages) {
19723                if (ps.pkg == null) continue;
19724
19725                final ApplicationInfo info = ps.pkg.applicationInfo;
19726                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19727                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19728
19729                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19730                        "unloadPrivatePackagesInner")) {
19731                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19732                            false, null)) {
19733                        unloaded.add(info);
19734                    } else {
19735                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19736                    }
19737                }
19738
19739                // Try very hard to release any references to this package
19740                // so we don't risk the system server being killed due to
19741                // open FDs
19742                AttributeCache.instance().removePackage(ps.name);
19743            }
19744
19745            mSettings.writeLPr();
19746        }
19747        }
19748
19749        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19750        sendResourcesChangedBroadcast(false, false, unloaded, null);
19751
19752        // Try very hard to release any references to this path so we don't risk
19753        // the system server being killed due to open FDs
19754        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19755
19756        for (int i = 0; i < 3; i++) {
19757            System.gc();
19758            System.runFinalization();
19759        }
19760    }
19761
19762    /**
19763     * Prepare storage areas for given user on all mounted devices.
19764     */
19765    void prepareUserData(int userId, int userSerial, int flags) {
19766        synchronized (mInstallLock) {
19767            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19768            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19769                final String volumeUuid = vol.getFsUuid();
19770                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19771            }
19772        }
19773    }
19774
19775    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19776            boolean allowRecover) {
19777        // Prepare storage and verify that serial numbers are consistent; if
19778        // there's a mismatch we need to destroy to avoid leaking data
19779        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19780        try {
19781            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19782
19783            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19784                UserManagerService.enforceSerialNumber(
19785                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19786                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19787                    UserManagerService.enforceSerialNumber(
19788                            Environment.getDataSystemDeDirectory(userId), userSerial);
19789                }
19790            }
19791            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19792                UserManagerService.enforceSerialNumber(
19793                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19794                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19795                    UserManagerService.enforceSerialNumber(
19796                            Environment.getDataSystemCeDirectory(userId), userSerial);
19797                }
19798            }
19799
19800            synchronized (mInstallLock) {
19801                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19802            }
19803        } catch (Exception e) {
19804            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19805                    + " because we failed to prepare: " + e);
19806            destroyUserDataLI(volumeUuid, userId,
19807                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19808
19809            if (allowRecover) {
19810                // Try one last time; if we fail again we're really in trouble
19811                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19812            }
19813        }
19814    }
19815
19816    /**
19817     * Destroy storage areas for given user on all mounted devices.
19818     */
19819    void destroyUserData(int userId, int flags) {
19820        synchronized (mInstallLock) {
19821            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19822            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19823                final String volumeUuid = vol.getFsUuid();
19824                destroyUserDataLI(volumeUuid, userId, flags);
19825            }
19826        }
19827    }
19828
19829    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19830        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19831        try {
19832            // Clean up app data, profile data, and media data
19833            mInstaller.destroyUserData(volumeUuid, userId, flags);
19834
19835            // Clean up system data
19836            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19837                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19838                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19839                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19840                }
19841                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19842                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19843                }
19844            }
19845
19846            // Data with special labels is now gone, so finish the job
19847            storage.destroyUserStorage(volumeUuid, userId, flags);
19848
19849        } catch (Exception e) {
19850            logCriticalInfo(Log.WARN,
19851                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19852        }
19853    }
19854
19855    /**
19856     * Examine all users present on given mounted volume, and destroy data
19857     * belonging to users that are no longer valid, or whose user ID has been
19858     * recycled.
19859     */
19860    private void reconcileUsers(String volumeUuid) {
19861        final List<File> files = new ArrayList<>();
19862        Collections.addAll(files, FileUtils
19863                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19864        Collections.addAll(files, FileUtils
19865                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19866        Collections.addAll(files, FileUtils
19867                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19868        Collections.addAll(files, FileUtils
19869                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19870        for (File file : files) {
19871            if (!file.isDirectory()) continue;
19872
19873            final int userId;
19874            final UserInfo info;
19875            try {
19876                userId = Integer.parseInt(file.getName());
19877                info = sUserManager.getUserInfo(userId);
19878            } catch (NumberFormatException e) {
19879                Slog.w(TAG, "Invalid user directory " + file);
19880                continue;
19881            }
19882
19883            boolean destroyUser = false;
19884            if (info == null) {
19885                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19886                        + " because no matching user was found");
19887                destroyUser = true;
19888            } else if (!mOnlyCore) {
19889                try {
19890                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19891                } catch (IOException e) {
19892                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19893                            + " because we failed to enforce serial number: " + e);
19894                    destroyUser = true;
19895                }
19896            }
19897
19898            if (destroyUser) {
19899                synchronized (mInstallLock) {
19900                    destroyUserDataLI(volumeUuid, userId,
19901                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19902                }
19903            }
19904        }
19905    }
19906
19907    private void assertPackageKnown(String volumeUuid, String packageName)
19908            throws PackageManagerException {
19909        synchronized (mPackages) {
19910            final PackageSetting ps = mSettings.mPackages.get(packageName);
19911            if (ps == null) {
19912                throw new PackageManagerException("Package " + packageName + " is unknown");
19913            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19914                throw new PackageManagerException(
19915                        "Package " + packageName + " found on unknown volume " + volumeUuid
19916                                + "; expected volume " + ps.volumeUuid);
19917            }
19918        }
19919    }
19920
19921    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19922            throws PackageManagerException {
19923        synchronized (mPackages) {
19924            final PackageSetting ps = mSettings.mPackages.get(packageName);
19925            if (ps == null) {
19926                throw new PackageManagerException("Package " + packageName + " is unknown");
19927            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19928                throw new PackageManagerException(
19929                        "Package " + packageName + " found on unknown volume " + volumeUuid
19930                                + "; expected volume " + ps.volumeUuid);
19931            } else if (!ps.getInstalled(userId)) {
19932                throw new PackageManagerException(
19933                        "Package " + packageName + " not installed for user " + userId);
19934            }
19935        }
19936    }
19937
19938    /**
19939     * Examine all apps present on given mounted volume, and destroy apps that
19940     * aren't expected, either due to uninstallation or reinstallation on
19941     * another volume.
19942     */
19943    private void reconcileApps(String volumeUuid) {
19944        final File[] files = FileUtils
19945                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19946        for (File file : files) {
19947            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19948                    && !PackageInstallerService.isStageName(file.getName());
19949            if (!isPackage) {
19950                // Ignore entries which are not packages
19951                continue;
19952            }
19953
19954            try {
19955                final PackageLite pkg = PackageParser.parsePackageLite(file,
19956                        PackageParser.PARSE_MUST_BE_APK);
19957                assertPackageKnown(volumeUuid, pkg.packageName);
19958
19959            } catch (PackageParserException | PackageManagerException e) {
19960                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19961                synchronized (mInstallLock) {
19962                    removeCodePathLI(file);
19963                }
19964            }
19965        }
19966    }
19967
19968    /**
19969     * Reconcile all app data for the given user.
19970     * <p>
19971     * Verifies that directories exist and that ownership and labeling is
19972     * correct for all installed apps on all mounted volumes.
19973     */
19974    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
19975        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19976        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19977            final String volumeUuid = vol.getFsUuid();
19978            synchronized (mInstallLock) {
19979                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
19980            }
19981        }
19982    }
19983
19984    /**
19985     * Reconcile all app data on given mounted volume.
19986     * <p>
19987     * Destroys app data that isn't expected, either due to uninstallation or
19988     * reinstallation on another volume.
19989     * <p>
19990     * Verifies that directories exist and that ownership and labeling is
19991     * correct for all installed apps.
19992     */
19993    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
19994            boolean migrateAppData) {
19995        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19996                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
19997
19998        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19999        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
20000
20001        // First look for stale data that doesn't belong, and check if things
20002        // have changed since we did our last restorecon
20003        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20004            if (StorageManager.isFileEncryptedNativeOrEmulated()
20005                    && !StorageManager.isUserKeyUnlocked(userId)) {
20006                throw new RuntimeException(
20007                        "Yikes, someone asked us to reconcile CE storage while " + userId
20008                                + " was still locked; this would have caused massive data loss!");
20009            }
20010
20011            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
20012            for (File file : files) {
20013                final String packageName = file.getName();
20014                try {
20015                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20016                } catch (PackageManagerException e) {
20017                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20018                    try {
20019                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20020                                StorageManager.FLAG_STORAGE_CE, 0);
20021                    } catch (InstallerException e2) {
20022                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20023                    }
20024                }
20025            }
20026        }
20027        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20028            final File[] files = FileUtils.listFilesOrEmpty(deDir);
20029            for (File file : files) {
20030                final String packageName = file.getName();
20031                try {
20032                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20033                } catch (PackageManagerException e) {
20034                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20035                    try {
20036                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20037                                StorageManager.FLAG_STORAGE_DE, 0);
20038                    } catch (InstallerException e2) {
20039                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20040                    }
20041                }
20042            }
20043        }
20044
20045        // Ensure that data directories are ready to roll for all packages
20046        // installed for this volume and user
20047        final List<PackageSetting> packages;
20048        synchronized (mPackages) {
20049            packages = mSettings.getVolumePackagesLPr(volumeUuid);
20050        }
20051        int preparedCount = 0;
20052        for (PackageSetting ps : packages) {
20053            final String packageName = ps.name;
20054            if (ps.pkg == null) {
20055                Slog.w(TAG, "Odd, missing scanned package " + packageName);
20056                // TODO: might be due to legacy ASEC apps; we should circle back
20057                // and reconcile again once they're scanned
20058                continue;
20059            }
20060
20061            if (ps.getInstalled(userId)) {
20062                prepareAppDataLIF(ps.pkg, userId, flags);
20063
20064                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
20065                    // We may have just shuffled around app data directories, so
20066                    // prepare them one more time
20067                    prepareAppDataLIF(ps.pkg, userId, flags);
20068                }
20069
20070                preparedCount++;
20071            }
20072        }
20073
20074        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
20075    }
20076
20077    /**
20078     * Prepare app data for the given app just after it was installed or
20079     * upgraded. This method carefully only touches users that it's installed
20080     * for, and it forces a restorecon to handle any seinfo changes.
20081     * <p>
20082     * Verifies that directories exist and that ownership and labeling is
20083     * correct for all installed apps. If there is an ownership mismatch, it
20084     * will try recovering system apps by wiping data; third-party app data is
20085     * left intact.
20086     * <p>
20087     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
20088     */
20089    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
20090        final PackageSetting ps;
20091        synchronized (mPackages) {
20092            ps = mSettings.mPackages.get(pkg.packageName);
20093            mSettings.writeKernelMappingLPr(ps);
20094        }
20095
20096        final UserManager um = mContext.getSystemService(UserManager.class);
20097        UserManagerInternal umInternal = getUserManagerInternal();
20098        for (UserInfo user : um.getUsers()) {
20099            final int flags;
20100            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20101                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20102            } else if (umInternal.isUserRunning(user.id)) {
20103                flags = StorageManager.FLAG_STORAGE_DE;
20104            } else {
20105                continue;
20106            }
20107
20108            if (ps.getInstalled(user.id)) {
20109                // TODO: when user data is locked, mark that we're still dirty
20110                prepareAppDataLIF(pkg, user.id, flags);
20111            }
20112        }
20113    }
20114
20115    /**
20116     * Prepare app data for the given app.
20117     * <p>
20118     * Verifies that directories exist and that ownership and labeling is
20119     * correct for all installed apps. If there is an ownership mismatch, this
20120     * will try recovering system apps by wiping data; third-party app data is
20121     * left intact.
20122     */
20123    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
20124        if (pkg == null) {
20125            Slog.wtf(TAG, "Package was null!", new Throwable());
20126            return;
20127        }
20128        prepareAppDataLeafLIF(pkg, userId, flags);
20129        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20130        for (int i = 0; i < childCount; i++) {
20131            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
20132        }
20133    }
20134
20135    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20136        if (DEBUG_APP_DATA) {
20137            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
20138                    + Integer.toHexString(flags));
20139        }
20140
20141        final String volumeUuid = pkg.volumeUuid;
20142        final String packageName = pkg.packageName;
20143        final ApplicationInfo app = pkg.applicationInfo;
20144        final int appId = UserHandle.getAppId(app.uid);
20145
20146        Preconditions.checkNotNull(app.seinfo);
20147
20148        try {
20149            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20150                    appId, app.seinfo, app.targetSdkVersion);
20151        } catch (InstallerException e) {
20152            if (app.isSystemApp()) {
20153                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20154                        + ", but trying to recover: " + e);
20155                destroyAppDataLeafLIF(pkg, userId, flags);
20156                try {
20157                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20158                            appId, app.seinfo, app.targetSdkVersion);
20159                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20160                } catch (InstallerException e2) {
20161                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
20162                }
20163            } else {
20164                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20165            }
20166        }
20167
20168        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20169            try {
20170                // CE storage is unlocked right now, so read out the inode and
20171                // remember for use later when it's locked
20172                // TODO: mark this structure as dirty so we persist it!
20173                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
20174                        StorageManager.FLAG_STORAGE_CE);
20175                synchronized (mPackages) {
20176                    final PackageSetting ps = mSettings.mPackages.get(packageName);
20177                    if (ps != null) {
20178                        ps.setCeDataInode(ceDataInode, userId);
20179                    }
20180                }
20181            } catch (InstallerException e) {
20182                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
20183            }
20184        }
20185
20186        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20187    }
20188
20189    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20190        if (pkg == null) {
20191            Slog.wtf(TAG, "Package was null!", new Throwable());
20192            return;
20193        }
20194        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20195        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20196        for (int i = 0; i < childCount; i++) {
20197            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20198        }
20199    }
20200
20201    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20202        final String volumeUuid = pkg.volumeUuid;
20203        final String packageName = pkg.packageName;
20204        final ApplicationInfo app = pkg.applicationInfo;
20205
20206        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20207            // Create a native library symlink only if we have native libraries
20208            // and if the native libraries are 32 bit libraries. We do not provide
20209            // this symlink for 64 bit libraries.
20210            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20211                final String nativeLibPath = app.nativeLibraryDir;
20212                try {
20213                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20214                            nativeLibPath, userId);
20215                } catch (InstallerException e) {
20216                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20217                }
20218            }
20219        }
20220    }
20221
20222    /**
20223     * For system apps on non-FBE devices, this method migrates any existing
20224     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20225     * requested by the app.
20226     */
20227    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20228        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20229                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20230            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20231                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20232            try {
20233                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20234                        storageTarget);
20235            } catch (InstallerException e) {
20236                logCriticalInfo(Log.WARN,
20237                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20238            }
20239            return true;
20240        } else {
20241            return false;
20242        }
20243    }
20244
20245    public PackageFreezer freezePackage(String packageName, String killReason) {
20246        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20247    }
20248
20249    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20250        return new PackageFreezer(packageName, userId, killReason);
20251    }
20252
20253    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20254            String killReason) {
20255        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20256    }
20257
20258    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20259            String killReason) {
20260        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20261            return new PackageFreezer();
20262        } else {
20263            return freezePackage(packageName, userId, killReason);
20264        }
20265    }
20266
20267    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20268            String killReason) {
20269        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20270    }
20271
20272    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20273            String killReason) {
20274        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20275            return new PackageFreezer();
20276        } else {
20277            return freezePackage(packageName, userId, killReason);
20278        }
20279    }
20280
20281    /**
20282     * Class that freezes and kills the given package upon creation, and
20283     * unfreezes it upon closing. This is typically used when doing surgery on
20284     * app code/data to prevent the app from running while you're working.
20285     */
20286    private class PackageFreezer implements AutoCloseable {
20287        private final String mPackageName;
20288        private final PackageFreezer[] mChildren;
20289
20290        private final boolean mWeFroze;
20291
20292        private final AtomicBoolean mClosed = new AtomicBoolean();
20293        private final CloseGuard mCloseGuard = CloseGuard.get();
20294
20295        /**
20296         * Create and return a stub freezer that doesn't actually do anything,
20297         * typically used when someone requested
20298         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20299         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20300         */
20301        public PackageFreezer() {
20302            mPackageName = null;
20303            mChildren = null;
20304            mWeFroze = false;
20305            mCloseGuard.open("close");
20306        }
20307
20308        public PackageFreezer(String packageName, int userId, String killReason) {
20309            synchronized (mPackages) {
20310                mPackageName = packageName;
20311                mWeFroze = mFrozenPackages.add(mPackageName);
20312
20313                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20314                if (ps != null) {
20315                    killApplication(ps.name, ps.appId, userId, killReason);
20316                }
20317
20318                final PackageParser.Package p = mPackages.get(packageName);
20319                if (p != null && p.childPackages != null) {
20320                    final int N = p.childPackages.size();
20321                    mChildren = new PackageFreezer[N];
20322                    for (int i = 0; i < N; i++) {
20323                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20324                                userId, killReason);
20325                    }
20326                } else {
20327                    mChildren = null;
20328                }
20329            }
20330            mCloseGuard.open("close");
20331        }
20332
20333        @Override
20334        protected void finalize() throws Throwable {
20335            try {
20336                mCloseGuard.warnIfOpen();
20337                close();
20338            } finally {
20339                super.finalize();
20340            }
20341        }
20342
20343        @Override
20344        public void close() {
20345            mCloseGuard.close();
20346            if (mClosed.compareAndSet(false, true)) {
20347                synchronized (mPackages) {
20348                    if (mWeFroze) {
20349                        mFrozenPackages.remove(mPackageName);
20350                    }
20351
20352                    if (mChildren != null) {
20353                        for (PackageFreezer freezer : mChildren) {
20354                            freezer.close();
20355                        }
20356                    }
20357                }
20358            }
20359        }
20360    }
20361
20362    /**
20363     * Verify that given package is currently frozen.
20364     */
20365    private void checkPackageFrozen(String packageName) {
20366        synchronized (mPackages) {
20367            if (!mFrozenPackages.contains(packageName)) {
20368                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20369            }
20370        }
20371    }
20372
20373    @Override
20374    public int movePackage(final String packageName, final String volumeUuid) {
20375        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20376
20377        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20378        final int moveId = mNextMoveId.getAndIncrement();
20379        mHandler.post(new Runnable() {
20380            @Override
20381            public void run() {
20382                try {
20383                    movePackageInternal(packageName, volumeUuid, moveId, user);
20384                } catch (PackageManagerException e) {
20385                    Slog.w(TAG, "Failed to move " + packageName, e);
20386                    mMoveCallbacks.notifyStatusChanged(moveId,
20387                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20388                }
20389            }
20390        });
20391        return moveId;
20392    }
20393
20394    private void movePackageInternal(final String packageName, final String volumeUuid,
20395            final int moveId, UserHandle user) throws PackageManagerException {
20396        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20397        final PackageManager pm = mContext.getPackageManager();
20398
20399        final boolean currentAsec;
20400        final String currentVolumeUuid;
20401        final File codeFile;
20402        final String installerPackageName;
20403        final String packageAbiOverride;
20404        final int appId;
20405        final String seinfo;
20406        final String label;
20407        final int targetSdkVersion;
20408        final PackageFreezer freezer;
20409        final int[] installedUserIds;
20410
20411        // reader
20412        synchronized (mPackages) {
20413            final PackageParser.Package pkg = mPackages.get(packageName);
20414            final PackageSetting ps = mSettings.mPackages.get(packageName);
20415            if (pkg == null || ps == null) {
20416                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20417            }
20418
20419            if (pkg.applicationInfo.isSystemApp()) {
20420                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20421                        "Cannot move system application");
20422            }
20423
20424            if (pkg.applicationInfo.isExternalAsec()) {
20425                currentAsec = true;
20426                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20427            } else if (pkg.applicationInfo.isForwardLocked()) {
20428                currentAsec = true;
20429                currentVolumeUuid = "forward_locked";
20430            } else {
20431                currentAsec = false;
20432                currentVolumeUuid = ps.volumeUuid;
20433
20434                final File probe = new File(pkg.codePath);
20435                final File probeOat = new File(probe, "oat");
20436                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20437                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20438                            "Move only supported for modern cluster style installs");
20439                }
20440            }
20441
20442            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20443                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20444                        "Package already moved to " + volumeUuid);
20445            }
20446            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20447                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20448                        "Device admin cannot be moved");
20449            }
20450
20451            if (mFrozenPackages.contains(packageName)) {
20452                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20453                        "Failed to move already frozen package");
20454            }
20455
20456            codeFile = new File(pkg.codePath);
20457            installerPackageName = ps.installerPackageName;
20458            packageAbiOverride = ps.cpuAbiOverrideString;
20459            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20460            seinfo = pkg.applicationInfo.seinfo;
20461            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20462            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20463            freezer = freezePackage(packageName, "movePackageInternal");
20464            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20465        }
20466
20467        final Bundle extras = new Bundle();
20468        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20469        extras.putString(Intent.EXTRA_TITLE, label);
20470        mMoveCallbacks.notifyCreated(moveId, extras);
20471
20472        int installFlags;
20473        final boolean moveCompleteApp;
20474        final File measurePath;
20475
20476        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20477            installFlags = INSTALL_INTERNAL;
20478            moveCompleteApp = !currentAsec;
20479            measurePath = Environment.getDataAppDirectory(volumeUuid);
20480        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20481            installFlags = INSTALL_EXTERNAL;
20482            moveCompleteApp = false;
20483            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20484        } else {
20485            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20486            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20487                    || !volume.isMountedWritable()) {
20488                freezer.close();
20489                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20490                        "Move location not mounted private volume");
20491            }
20492
20493            Preconditions.checkState(!currentAsec);
20494
20495            installFlags = INSTALL_INTERNAL;
20496            moveCompleteApp = true;
20497            measurePath = Environment.getDataAppDirectory(volumeUuid);
20498        }
20499
20500        final PackageStats stats = new PackageStats(null, -1);
20501        synchronized (mInstaller) {
20502            for (int userId : installedUserIds) {
20503                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20504                    freezer.close();
20505                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20506                            "Failed to measure package size");
20507                }
20508            }
20509        }
20510
20511        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20512                + stats.dataSize);
20513
20514        final long startFreeBytes = measurePath.getFreeSpace();
20515        final long sizeBytes;
20516        if (moveCompleteApp) {
20517            sizeBytes = stats.codeSize + stats.dataSize;
20518        } else {
20519            sizeBytes = stats.codeSize;
20520        }
20521
20522        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20523            freezer.close();
20524            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20525                    "Not enough free space to move");
20526        }
20527
20528        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20529
20530        final CountDownLatch installedLatch = new CountDownLatch(1);
20531        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20532            @Override
20533            public void onUserActionRequired(Intent intent) throws RemoteException {
20534                throw new IllegalStateException();
20535            }
20536
20537            @Override
20538            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20539                    Bundle extras) throws RemoteException {
20540                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20541                        + PackageManager.installStatusToString(returnCode, msg));
20542
20543                installedLatch.countDown();
20544                freezer.close();
20545
20546                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20547                switch (status) {
20548                    case PackageInstaller.STATUS_SUCCESS:
20549                        mMoveCallbacks.notifyStatusChanged(moveId,
20550                                PackageManager.MOVE_SUCCEEDED);
20551                        break;
20552                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20553                        mMoveCallbacks.notifyStatusChanged(moveId,
20554                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20555                        break;
20556                    default:
20557                        mMoveCallbacks.notifyStatusChanged(moveId,
20558                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20559                        break;
20560                }
20561            }
20562        };
20563
20564        final MoveInfo move;
20565        if (moveCompleteApp) {
20566            // Kick off a thread to report progress estimates
20567            new Thread() {
20568                @Override
20569                public void run() {
20570                    while (true) {
20571                        try {
20572                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20573                                break;
20574                            }
20575                        } catch (InterruptedException ignored) {
20576                        }
20577
20578                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20579                        final int progress = 10 + (int) MathUtils.constrain(
20580                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20581                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20582                    }
20583                }
20584            }.start();
20585
20586            final String dataAppName = codeFile.getName();
20587            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20588                    dataAppName, appId, seinfo, targetSdkVersion);
20589        } else {
20590            move = null;
20591        }
20592
20593        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20594
20595        final Message msg = mHandler.obtainMessage(INIT_COPY);
20596        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20597        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20598                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20599                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20600        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20601        msg.obj = params;
20602
20603        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20604                System.identityHashCode(msg.obj));
20605        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20606                System.identityHashCode(msg.obj));
20607
20608        mHandler.sendMessage(msg);
20609    }
20610
20611    @Override
20612    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20613        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20614
20615        final int realMoveId = mNextMoveId.getAndIncrement();
20616        final Bundle extras = new Bundle();
20617        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20618        mMoveCallbacks.notifyCreated(realMoveId, extras);
20619
20620        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20621            @Override
20622            public void onCreated(int moveId, Bundle extras) {
20623                // Ignored
20624            }
20625
20626            @Override
20627            public void onStatusChanged(int moveId, int status, long estMillis) {
20628                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20629            }
20630        };
20631
20632        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20633        storage.setPrimaryStorageUuid(volumeUuid, callback);
20634        return realMoveId;
20635    }
20636
20637    @Override
20638    public int getMoveStatus(int moveId) {
20639        mContext.enforceCallingOrSelfPermission(
20640                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20641        return mMoveCallbacks.mLastStatus.get(moveId);
20642    }
20643
20644    @Override
20645    public void registerMoveCallback(IPackageMoveObserver callback) {
20646        mContext.enforceCallingOrSelfPermission(
20647                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20648        mMoveCallbacks.register(callback);
20649    }
20650
20651    @Override
20652    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20653        mContext.enforceCallingOrSelfPermission(
20654                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20655        mMoveCallbacks.unregister(callback);
20656    }
20657
20658    @Override
20659    public boolean setInstallLocation(int loc) {
20660        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20661                null);
20662        if (getInstallLocation() == loc) {
20663            return true;
20664        }
20665        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20666                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20667            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20668                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20669            return true;
20670        }
20671        return false;
20672   }
20673
20674    @Override
20675    public int getInstallLocation() {
20676        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20677                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20678                PackageHelper.APP_INSTALL_AUTO);
20679    }
20680
20681    /** Called by UserManagerService */
20682    void cleanUpUser(UserManagerService userManager, int userHandle) {
20683        synchronized (mPackages) {
20684            mDirtyUsers.remove(userHandle);
20685            mUserNeedsBadging.delete(userHandle);
20686            mSettings.removeUserLPw(userHandle);
20687            mPendingBroadcasts.remove(userHandle);
20688            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20689            removeUnusedPackagesLPw(userManager, userHandle);
20690        }
20691    }
20692
20693    /**
20694     * We're removing userHandle and would like to remove any downloaded packages
20695     * that are no longer in use by any other user.
20696     * @param userHandle the user being removed
20697     */
20698    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20699        final boolean DEBUG_CLEAN_APKS = false;
20700        int [] users = userManager.getUserIds();
20701        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20702        while (psit.hasNext()) {
20703            PackageSetting ps = psit.next();
20704            if (ps.pkg == null) {
20705                continue;
20706            }
20707            final String packageName = ps.pkg.packageName;
20708            // Skip over if system app
20709            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20710                continue;
20711            }
20712            if (DEBUG_CLEAN_APKS) {
20713                Slog.i(TAG, "Checking package " + packageName);
20714            }
20715            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20716            if (keep) {
20717                if (DEBUG_CLEAN_APKS) {
20718                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20719                }
20720            } else {
20721                for (int i = 0; i < users.length; i++) {
20722                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20723                        keep = true;
20724                        if (DEBUG_CLEAN_APKS) {
20725                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20726                                    + users[i]);
20727                        }
20728                        break;
20729                    }
20730                }
20731            }
20732            if (!keep) {
20733                if (DEBUG_CLEAN_APKS) {
20734                    Slog.i(TAG, "  Removing package " + packageName);
20735                }
20736                mHandler.post(new Runnable() {
20737                    public void run() {
20738                        deletePackageX(packageName, userHandle, 0);
20739                    } //end run
20740                });
20741            }
20742        }
20743    }
20744
20745    /** Called by UserManagerService */
20746    void createNewUser(int userId, String[] disallowedPackages) {
20747        synchronized (mInstallLock) {
20748            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
20749        }
20750        synchronized (mPackages) {
20751            scheduleWritePackageRestrictionsLocked(userId);
20752            scheduleWritePackageListLocked(userId);
20753            applyFactoryDefaultBrowserLPw(userId);
20754            primeDomainVerificationsLPw(userId);
20755        }
20756    }
20757
20758    void onNewUserCreated(final int userId) {
20759        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20760        // If permission review for legacy apps is required, we represent
20761        // dagerous permissions for such apps as always granted runtime
20762        // permissions to keep per user flag state whether review is needed.
20763        // Hence, if a new user is added we have to propagate dangerous
20764        // permission grants for these legacy apps.
20765        if (mPermissionReviewRequired) {
20766            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20767                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20768        }
20769    }
20770
20771    @Override
20772    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20773        mContext.enforceCallingOrSelfPermission(
20774                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20775                "Only package verification agents can read the verifier device identity");
20776
20777        synchronized (mPackages) {
20778            return mSettings.getVerifierDeviceIdentityLPw();
20779        }
20780    }
20781
20782    @Override
20783    public void setPermissionEnforced(String permission, boolean enforced) {
20784        // TODO: Now that we no longer change GID for storage, this should to away.
20785        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20786                "setPermissionEnforced");
20787        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20788            synchronized (mPackages) {
20789                if (mSettings.mReadExternalStorageEnforced == null
20790                        || mSettings.mReadExternalStorageEnforced != enforced) {
20791                    mSettings.mReadExternalStorageEnforced = enforced;
20792                    mSettings.writeLPr();
20793                }
20794            }
20795            // kill any non-foreground processes so we restart them and
20796            // grant/revoke the GID.
20797            final IActivityManager am = ActivityManager.getService();
20798            if (am != null) {
20799                final long token = Binder.clearCallingIdentity();
20800                try {
20801                    am.killProcessesBelowForeground("setPermissionEnforcement");
20802                } catch (RemoteException e) {
20803                } finally {
20804                    Binder.restoreCallingIdentity(token);
20805                }
20806            }
20807        } else {
20808            throw new IllegalArgumentException("No selective enforcement for " + permission);
20809        }
20810    }
20811
20812    @Override
20813    @Deprecated
20814    public boolean isPermissionEnforced(String permission) {
20815        return true;
20816    }
20817
20818    @Override
20819    public boolean isStorageLow() {
20820        final long token = Binder.clearCallingIdentity();
20821        try {
20822            final DeviceStorageMonitorInternal
20823                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20824            if (dsm != null) {
20825                return dsm.isMemoryLow();
20826            } else {
20827                return false;
20828            }
20829        } finally {
20830            Binder.restoreCallingIdentity(token);
20831        }
20832    }
20833
20834    @Override
20835    public IPackageInstaller getPackageInstaller() {
20836        return mInstallerService;
20837    }
20838
20839    private boolean userNeedsBadging(int userId) {
20840        int index = mUserNeedsBadging.indexOfKey(userId);
20841        if (index < 0) {
20842            final UserInfo userInfo;
20843            final long token = Binder.clearCallingIdentity();
20844            try {
20845                userInfo = sUserManager.getUserInfo(userId);
20846            } finally {
20847                Binder.restoreCallingIdentity(token);
20848            }
20849            final boolean b;
20850            if (userInfo != null && userInfo.isManagedProfile()) {
20851                b = true;
20852            } else {
20853                b = false;
20854            }
20855            mUserNeedsBadging.put(userId, b);
20856            return b;
20857        }
20858        return mUserNeedsBadging.valueAt(index);
20859    }
20860
20861    @Override
20862    public KeySet getKeySetByAlias(String packageName, String alias) {
20863        if (packageName == null || alias == null) {
20864            return null;
20865        }
20866        synchronized(mPackages) {
20867            final PackageParser.Package pkg = mPackages.get(packageName);
20868            if (pkg == null) {
20869                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20870                throw new IllegalArgumentException("Unknown package: " + packageName);
20871            }
20872            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20873            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20874        }
20875    }
20876
20877    @Override
20878    public KeySet getSigningKeySet(String packageName) {
20879        if (packageName == null) {
20880            return null;
20881        }
20882        synchronized(mPackages) {
20883            final PackageParser.Package pkg = mPackages.get(packageName);
20884            if (pkg == null) {
20885                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20886                throw new IllegalArgumentException("Unknown package: " + packageName);
20887            }
20888            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20889                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20890                throw new SecurityException("May not access signing KeySet of other apps.");
20891            }
20892            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20893            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20894        }
20895    }
20896
20897    @Override
20898    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20899        if (packageName == null || ks == null) {
20900            return false;
20901        }
20902        synchronized(mPackages) {
20903            final PackageParser.Package pkg = mPackages.get(packageName);
20904            if (pkg == null) {
20905                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20906                throw new IllegalArgumentException("Unknown package: " + packageName);
20907            }
20908            IBinder ksh = ks.getToken();
20909            if (ksh instanceof KeySetHandle) {
20910                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20911                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20912            }
20913            return false;
20914        }
20915    }
20916
20917    @Override
20918    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20919        if (packageName == null || ks == null) {
20920            return false;
20921        }
20922        synchronized(mPackages) {
20923            final PackageParser.Package pkg = mPackages.get(packageName);
20924            if (pkg == null) {
20925                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20926                throw new IllegalArgumentException("Unknown package: " + packageName);
20927            }
20928            IBinder ksh = ks.getToken();
20929            if (ksh instanceof KeySetHandle) {
20930                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20931                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20932            }
20933            return false;
20934        }
20935    }
20936
20937    private void deletePackageIfUnusedLPr(final String packageName) {
20938        PackageSetting ps = mSettings.mPackages.get(packageName);
20939        if (ps == null) {
20940            return;
20941        }
20942        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20943            // TODO Implement atomic delete if package is unused
20944            // It is currently possible that the package will be deleted even if it is installed
20945            // after this method returns.
20946            mHandler.post(new Runnable() {
20947                public void run() {
20948                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20949                }
20950            });
20951        }
20952    }
20953
20954    /**
20955     * Check and throw if the given before/after packages would be considered a
20956     * downgrade.
20957     */
20958    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20959            throws PackageManagerException {
20960        if (after.versionCode < before.mVersionCode) {
20961            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20962                    "Update version code " + after.versionCode + " is older than current "
20963                    + before.mVersionCode);
20964        } else if (after.versionCode == before.mVersionCode) {
20965            if (after.baseRevisionCode < before.baseRevisionCode) {
20966                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20967                        "Update base revision code " + after.baseRevisionCode
20968                        + " is older than current " + before.baseRevisionCode);
20969            }
20970
20971            if (!ArrayUtils.isEmpty(after.splitNames)) {
20972                for (int i = 0; i < after.splitNames.length; i++) {
20973                    final String splitName = after.splitNames[i];
20974                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20975                    if (j != -1) {
20976                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20977                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20978                                    "Update split " + splitName + " revision code "
20979                                    + after.splitRevisionCodes[i] + " is older than current "
20980                                    + before.splitRevisionCodes[j]);
20981                        }
20982                    }
20983                }
20984            }
20985        }
20986    }
20987
20988    private static class MoveCallbacks extends Handler {
20989        private static final int MSG_CREATED = 1;
20990        private static final int MSG_STATUS_CHANGED = 2;
20991
20992        private final RemoteCallbackList<IPackageMoveObserver>
20993                mCallbacks = new RemoteCallbackList<>();
20994
20995        private final SparseIntArray mLastStatus = new SparseIntArray();
20996
20997        public MoveCallbacks(Looper looper) {
20998            super(looper);
20999        }
21000
21001        public void register(IPackageMoveObserver callback) {
21002            mCallbacks.register(callback);
21003        }
21004
21005        public void unregister(IPackageMoveObserver callback) {
21006            mCallbacks.unregister(callback);
21007        }
21008
21009        @Override
21010        public void handleMessage(Message msg) {
21011            final SomeArgs args = (SomeArgs) msg.obj;
21012            final int n = mCallbacks.beginBroadcast();
21013            for (int i = 0; i < n; i++) {
21014                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
21015                try {
21016                    invokeCallback(callback, msg.what, args);
21017                } catch (RemoteException ignored) {
21018                }
21019            }
21020            mCallbacks.finishBroadcast();
21021            args.recycle();
21022        }
21023
21024        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
21025                throws RemoteException {
21026            switch (what) {
21027                case MSG_CREATED: {
21028                    callback.onCreated(args.argi1, (Bundle) args.arg2);
21029                    break;
21030                }
21031                case MSG_STATUS_CHANGED: {
21032                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
21033                    break;
21034                }
21035            }
21036        }
21037
21038        private void notifyCreated(int moveId, Bundle extras) {
21039            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
21040
21041            final SomeArgs args = SomeArgs.obtain();
21042            args.argi1 = moveId;
21043            args.arg2 = extras;
21044            obtainMessage(MSG_CREATED, args).sendToTarget();
21045        }
21046
21047        private void notifyStatusChanged(int moveId, int status) {
21048            notifyStatusChanged(moveId, status, -1);
21049        }
21050
21051        private void notifyStatusChanged(int moveId, int status, long estMillis) {
21052            Slog.v(TAG, "Move " + moveId + " status " + status);
21053
21054            final SomeArgs args = SomeArgs.obtain();
21055            args.argi1 = moveId;
21056            args.argi2 = status;
21057            args.arg3 = estMillis;
21058            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
21059
21060            synchronized (mLastStatus) {
21061                mLastStatus.put(moveId, status);
21062            }
21063        }
21064    }
21065
21066    private final static class OnPermissionChangeListeners extends Handler {
21067        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
21068
21069        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
21070                new RemoteCallbackList<>();
21071
21072        public OnPermissionChangeListeners(Looper looper) {
21073            super(looper);
21074        }
21075
21076        @Override
21077        public void handleMessage(Message msg) {
21078            switch (msg.what) {
21079                case MSG_ON_PERMISSIONS_CHANGED: {
21080                    final int uid = msg.arg1;
21081                    handleOnPermissionsChanged(uid);
21082                } break;
21083            }
21084        }
21085
21086        public void addListenerLocked(IOnPermissionsChangeListener listener) {
21087            mPermissionListeners.register(listener);
21088
21089        }
21090
21091        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
21092            mPermissionListeners.unregister(listener);
21093        }
21094
21095        public void onPermissionsChanged(int uid) {
21096            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
21097                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
21098            }
21099        }
21100
21101        private void handleOnPermissionsChanged(int uid) {
21102            final int count = mPermissionListeners.beginBroadcast();
21103            try {
21104                for (int i = 0; i < count; i++) {
21105                    IOnPermissionsChangeListener callback = mPermissionListeners
21106                            .getBroadcastItem(i);
21107                    try {
21108                        callback.onPermissionsChanged(uid);
21109                    } catch (RemoteException e) {
21110                        Log.e(TAG, "Permission listener is dead", e);
21111                    }
21112                }
21113            } finally {
21114                mPermissionListeners.finishBroadcast();
21115            }
21116        }
21117    }
21118
21119    private class PackageManagerInternalImpl extends PackageManagerInternal {
21120        @Override
21121        public void setLocationPackagesProvider(PackagesProvider provider) {
21122            synchronized (mPackages) {
21123                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
21124            }
21125        }
21126
21127        @Override
21128        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
21129            synchronized (mPackages) {
21130                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
21131            }
21132        }
21133
21134        @Override
21135        public void setSmsAppPackagesProvider(PackagesProvider provider) {
21136            synchronized (mPackages) {
21137                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
21138            }
21139        }
21140
21141        @Override
21142        public void setDialerAppPackagesProvider(PackagesProvider provider) {
21143            synchronized (mPackages) {
21144                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21145            }
21146        }
21147
21148        @Override
21149        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21150            synchronized (mPackages) {
21151                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21152            }
21153        }
21154
21155        @Override
21156        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21157            synchronized (mPackages) {
21158                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21159            }
21160        }
21161
21162        @Override
21163        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21164            synchronized (mPackages) {
21165                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21166                        packageName, userId);
21167            }
21168        }
21169
21170        @Override
21171        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21172            synchronized (mPackages) {
21173                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21174                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21175                        packageName, userId);
21176            }
21177        }
21178
21179        @Override
21180        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21181            synchronized (mPackages) {
21182                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21183                        packageName, userId);
21184            }
21185        }
21186
21187        @Override
21188        public void setKeepUninstalledPackages(final List<String> packageList) {
21189            Preconditions.checkNotNull(packageList);
21190            List<String> removedFromList = null;
21191            synchronized (mPackages) {
21192                if (mKeepUninstalledPackages != null) {
21193                    final int packagesCount = mKeepUninstalledPackages.size();
21194                    for (int i = 0; i < packagesCount; i++) {
21195                        String oldPackage = mKeepUninstalledPackages.get(i);
21196                        if (packageList != null && packageList.contains(oldPackage)) {
21197                            continue;
21198                        }
21199                        if (removedFromList == null) {
21200                            removedFromList = new ArrayList<>();
21201                        }
21202                        removedFromList.add(oldPackage);
21203                    }
21204                }
21205                mKeepUninstalledPackages = new ArrayList<>(packageList);
21206                if (removedFromList != null) {
21207                    final int removedCount = removedFromList.size();
21208                    for (int i = 0; i < removedCount; i++) {
21209                        deletePackageIfUnusedLPr(removedFromList.get(i));
21210                    }
21211                }
21212            }
21213        }
21214
21215        @Override
21216        public boolean isPermissionsReviewRequired(String packageName, int userId) {
21217            synchronized (mPackages) {
21218                // If we do not support permission review, done.
21219                if (!mPermissionReviewRequired) {
21220                    return false;
21221                }
21222
21223                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21224                if (packageSetting == null) {
21225                    return false;
21226                }
21227
21228                // Permission review applies only to apps not supporting the new permission model.
21229                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21230                    return false;
21231                }
21232
21233                // Legacy apps have the permission and get user consent on launch.
21234                PermissionsState permissionsState = packageSetting.getPermissionsState();
21235                return permissionsState.isPermissionReviewRequired(userId);
21236            }
21237        }
21238
21239        @Override
21240        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21241            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21242        }
21243
21244        @Override
21245        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21246                int userId) {
21247            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21248        }
21249
21250        @Override
21251        public void setDeviceAndProfileOwnerPackages(
21252                int deviceOwnerUserId, String deviceOwnerPackage,
21253                SparseArray<String> profileOwnerPackages) {
21254            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21255                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21256        }
21257
21258        @Override
21259        public boolean isPackageDataProtected(int userId, String packageName) {
21260            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21261        }
21262
21263        @Override
21264        public boolean isPackageEphemeral(int userId, String packageName) {
21265            synchronized (mPackages) {
21266                PackageParser.Package p = mPackages.get(packageName);
21267                return p != null ? p.applicationInfo.isEphemeralApp() : false;
21268            }
21269        }
21270
21271        @Override
21272        public boolean wasPackageEverLaunched(String packageName, int userId) {
21273            synchronized (mPackages) {
21274                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21275            }
21276        }
21277
21278        @Override
21279        public void grantRuntimePermission(String packageName, String name, int userId,
21280                boolean overridePolicy) {
21281            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
21282                    overridePolicy);
21283        }
21284
21285        @Override
21286        public void revokeRuntimePermission(String packageName, String name, int userId,
21287                boolean overridePolicy) {
21288            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
21289                    overridePolicy);
21290        }
21291
21292        @Override
21293        public String getNameForUid(int uid) {
21294            return PackageManagerService.this.getNameForUid(uid);
21295        }
21296    }
21297
21298    @Override
21299    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21300        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21301        synchronized (mPackages) {
21302            final long identity = Binder.clearCallingIdentity();
21303            try {
21304                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21305                        packageNames, userId);
21306            } finally {
21307                Binder.restoreCallingIdentity(identity);
21308            }
21309        }
21310    }
21311
21312    private static void enforceSystemOrPhoneCaller(String tag) {
21313        int callingUid = Binder.getCallingUid();
21314        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21315            throw new SecurityException(
21316                    "Cannot call " + tag + " from UID " + callingUid);
21317        }
21318    }
21319
21320    boolean isHistoricalPackageUsageAvailable() {
21321        return mPackageUsage.isHistoricalPackageUsageAvailable();
21322    }
21323
21324    /**
21325     * Return a <b>copy</b> of the collection of packages known to the package manager.
21326     * @return A copy of the values of mPackages.
21327     */
21328    Collection<PackageParser.Package> getPackages() {
21329        synchronized (mPackages) {
21330            return new ArrayList<>(mPackages.values());
21331        }
21332    }
21333
21334    /**
21335     * Logs process start information (including base APK hash) to the security log.
21336     * @hide
21337     */
21338    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21339            String apkFile, int pid) {
21340        if (!SecurityLog.isLoggingEnabled()) {
21341            return;
21342        }
21343        Bundle data = new Bundle();
21344        data.putLong("startTimestamp", System.currentTimeMillis());
21345        data.putString("processName", processName);
21346        data.putInt("uid", uid);
21347        data.putString("seinfo", seinfo);
21348        data.putString("apkFile", apkFile);
21349        data.putInt("pid", pid);
21350        Message msg = mProcessLoggingHandler.obtainMessage(
21351                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21352        msg.setData(data);
21353        mProcessLoggingHandler.sendMessage(msg);
21354    }
21355
21356    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21357        return mCompilerStats.getPackageStats(pkgName);
21358    }
21359
21360    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21361        return getOrCreateCompilerPackageStats(pkg.packageName);
21362    }
21363
21364    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21365        return mCompilerStats.getOrCreatePackageStats(pkgName);
21366    }
21367
21368    public void deleteCompilerPackageStats(String pkgName) {
21369        mCompilerStats.deletePackageStats(pkgName);
21370    }
21371}
21372