PackageManagerService.java revision be7b0d18a7d68aa79dc8256ee904f0a94767d5d9
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
61import static android.content.pm.PackageManager.MATCH_ALL;
62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
63import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
65import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
66import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
67import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
68import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
69import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
70import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
71import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
72import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
73import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
74import static android.content.pm.PackageManager.PERMISSION_DENIED;
75import static android.content.pm.PackageManager.PERMISSION_GRANTED;
76import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
77import static android.content.pm.PackageParser.isApkFile;
78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
79import static android.system.OsConstants.O_CREAT;
80import static android.system.OsConstants.O_RDWR;
81
82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
86import static com.android.internal.util.ArrayUtils.appendInt;
87import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
93import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
99
100import android.Manifest;
101import android.annotation.NonNull;
102import android.annotation.Nullable;
103import android.app.ActivityManager;
104import android.app.ActivityManagerNative;
105import android.app.IActivityManager;
106import android.app.ResourcesManager;
107import android.app.admin.IDevicePolicyManager;
108import android.app.admin.SecurityLog;
109import android.app.backup.IBackupManager;
110import android.content.BroadcastReceiver;
111import android.content.ComponentName;
112import android.content.ContentResolver;
113import android.content.Context;
114import android.content.IIntentReceiver;
115import android.content.Intent;
116import android.content.IntentFilter;
117import android.content.IntentSender;
118import android.content.IntentSender.SendIntentException;
119import android.content.ServiceConnection;
120import android.content.pm.ActivityInfo;
121import android.content.pm.ApplicationInfo;
122import android.content.pm.AppsQueryHelper;
123import android.content.pm.ComponentInfo;
124import android.content.pm.EphemeralApplicationInfo;
125import android.content.pm.EphemeralResolveInfo;
126import android.content.pm.EphemeralResolveInfo.EphemeralDigest;
127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
128import android.content.pm.FeatureInfo;
129import android.content.pm.IOnPermissionsChangeListener;
130import android.content.pm.IPackageDataObserver;
131import android.content.pm.IPackageDeleteObserver;
132import android.content.pm.IPackageDeleteObserver2;
133import android.content.pm.IPackageInstallObserver2;
134import android.content.pm.IPackageInstaller;
135import android.content.pm.IPackageManager;
136import android.content.pm.IPackageMoveObserver;
137import android.content.pm.IPackageStatsObserver;
138import android.content.pm.InstrumentationInfo;
139import android.content.pm.IntentFilterVerificationInfo;
140import android.content.pm.KeySet;
141import android.content.pm.PackageCleanItem;
142import android.content.pm.PackageInfo;
143import android.content.pm.PackageInfoLite;
144import android.content.pm.PackageInstaller;
145import android.content.pm.PackageManager;
146import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
147import android.content.pm.PackageManagerInternal;
148import android.content.pm.PackageParser;
149import android.content.pm.PackageParser.ActivityIntentInfo;
150import android.content.pm.PackageParser.PackageLite;
151import android.content.pm.PackageParser.PackageParserException;
152import android.content.pm.PackageStats;
153import android.content.pm.PackageUserState;
154import android.content.pm.ParceledListSlice;
155import android.content.pm.PermissionGroupInfo;
156import android.content.pm.PermissionInfo;
157import android.content.pm.ProviderInfo;
158import android.content.pm.ResolveInfo;
159import android.content.pm.ServiceInfo;
160import android.content.pm.Signature;
161import android.content.pm.UserInfo;
162import android.content.pm.VerifierDeviceIdentity;
163import android.content.pm.VerifierInfo;
164import android.content.res.Resources;
165import android.graphics.Bitmap;
166import android.hardware.display.DisplayManager;
167import android.net.Uri;
168import android.os.Binder;
169import android.os.Build;
170import android.os.Bundle;
171import android.os.Debug;
172import android.os.Environment;
173import android.os.Environment.UserEnvironment;
174import android.os.FileUtils;
175import android.os.Handler;
176import android.os.IBinder;
177import android.os.Looper;
178import android.os.Message;
179import android.os.Parcel;
180import android.os.ParcelFileDescriptor;
181import android.os.PatternMatcher;
182import android.os.Process;
183import android.os.RemoteCallbackList;
184import android.os.RemoteException;
185import android.os.ResultReceiver;
186import android.os.SELinux;
187import android.os.ServiceManager;
188import android.os.SystemClock;
189import android.os.SystemProperties;
190import android.os.Trace;
191import android.os.UserHandle;
192import android.os.UserManager;
193import android.os.UserManagerInternal;
194import android.os.storage.IMountService;
195import android.os.storage.MountServiceInternal;
196import android.os.storage.StorageEventListener;
197import android.os.storage.StorageManager;
198import android.os.storage.VolumeInfo;
199import android.os.storage.VolumeRecord;
200import android.provider.Settings.Global;
201import android.provider.Settings.Secure;
202import android.security.KeyStore;
203import android.security.SystemKeyStore;
204import android.system.ErrnoException;
205import android.system.Os;
206import android.text.TextUtils;
207import android.text.format.DateUtils;
208import android.util.ArrayMap;
209import android.util.ArraySet;
210import android.util.DisplayMetrics;
211import android.util.EventLog;
212import android.util.ExceptionUtils;
213import android.util.Log;
214import android.util.LogPrinter;
215import android.util.MathUtils;
216import android.util.Pair;
217import android.util.PrintStreamPrinter;
218import android.util.Slog;
219import android.util.SparseArray;
220import android.util.SparseBooleanArray;
221import android.util.SparseIntArray;
222import android.util.Xml;
223import android.util.jar.StrictJarFile;
224import android.view.Display;
225
226import com.android.internal.R;
227import com.android.internal.annotations.GuardedBy;
228import com.android.internal.app.IMediaContainerService;
229import com.android.internal.app.ResolverActivity;
230import com.android.internal.content.NativeLibraryHelper;
231import com.android.internal.content.PackageHelper;
232import com.android.internal.logging.MetricsLogger;
233import com.android.internal.os.IParcelFileDescriptorFactory;
234import com.android.internal.os.SomeArgs;
235import com.android.internal.os.Zygote;
236import com.android.internal.telephony.CarrierAppUtils;
237import com.android.internal.util.ArrayUtils;
238import com.android.internal.util.FastPrintWriter;
239import com.android.internal.util.FastXmlSerializer;
240import com.android.internal.util.IndentingPrintWriter;
241import com.android.internal.util.Preconditions;
242import com.android.internal.util.XmlUtils;
243import com.android.server.AttributeCache;
244import com.android.server.EventLogTags;
245import com.android.server.FgThread;
246import com.android.server.IntentResolver;
247import com.android.server.LocalServices;
248import com.android.server.ServiceThread;
249import com.android.server.SystemConfig;
250import com.android.server.Watchdog;
251import com.android.server.net.NetworkPolicyManagerInternal;
252import com.android.server.pm.Installer.InstallerException;
253import com.android.server.pm.PermissionsState.PermissionState;
254import com.android.server.pm.Settings.DatabaseVersion;
255import com.android.server.pm.Settings.VersionInfo;
256import com.android.server.pm.dex.DexManager;
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.HashMap;
300import java.util.Iterator;
301import java.util.List;
302import java.util.Map;
303import java.util.Objects;
304import java.util.Set;
305import java.util.concurrent.CountDownLatch;
306import java.util.concurrent.TimeUnit;
307import java.util.concurrent.atomic.AtomicBoolean;
308import java.util.concurrent.atomic.AtomicInteger;
309
310/**
311 * Keep track of all those APKs everywhere.
312 * <p>
313 * Internally there are two important locks:
314 * <ul>
315 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
316 * and other related state. It is a fine-grained lock that should only be held
317 * momentarily, as it's one of the most contended locks in the system.
318 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
319 * operations typically involve heavy lifting of application data on disk. Since
320 * {@code installd} is single-threaded, and it's operations can often be slow,
321 * this lock should never be acquired while already holding {@link #mPackages}.
322 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
323 * holding {@link #mInstallLock}.
324 * </ul>
325 * Many internal methods rely on the caller to hold the appropriate locks, and
326 * this contract is expressed through method name suffixes:
327 * <ul>
328 * <li>fooLI(): the caller must hold {@link #mInstallLock}
329 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
330 * being modified must be frozen
331 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
332 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
333 * </ul>
334 * <p>
335 * Because this class is very central to the platform's security; please run all
336 * CTS and unit tests whenever making modifications:
337 *
338 * <pre>
339 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
340 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
341 * </pre>
342 */
343public class PackageManagerService extends IPackageManager.Stub {
344    static final String TAG = "PackageManager";
345    static final boolean DEBUG_SETTINGS = false;
346    static final boolean DEBUG_PREFERRED = false;
347    static final boolean DEBUG_UPGRADE = false;
348    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
349    private static final boolean DEBUG_BACKUP = false;
350    private static final boolean DEBUG_INSTALL = false;
351    private static final boolean DEBUG_REMOVE = false;
352    private static final boolean DEBUG_BROADCASTS = false;
353    private static final boolean DEBUG_SHOW_INFO = false;
354    private static final boolean DEBUG_PACKAGE_INFO = false;
355    private static final boolean DEBUG_INTENT_MATCHING = false;
356    private static final boolean DEBUG_PACKAGE_SCANNING = false;
357    private static final boolean DEBUG_VERIFY = false;
358    private static final boolean DEBUG_FILTERS = false;
359
360    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
361    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
362    // user, but by default initialize to this.
363    static final boolean DEBUG_DEXOPT = false;
364
365    private static final boolean DEBUG_ABI_SELECTION = false;
366    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
367    private static final boolean DEBUG_TRIAGED_MISSING = false;
368    private static final boolean DEBUG_APP_DATA = false;
369
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 boolean ENABLE_QUOTA =
376            SystemProperties.getBoolean("persist.fw.quota", false);
377
378    private static final int RADIO_UID = Process.PHONE_UID;
379    private static final int LOG_UID = Process.LOG_UID;
380    private static final int NFC_UID = Process.NFC_UID;
381    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
382    private static final int SHELL_UID = Process.SHELL_UID;
383
384    // Cap the size of permission trees that 3rd party apps can define
385    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
386
387    // Suffix used during package installation when copying/moving
388    // package apks to install directory.
389    private static final String INSTALL_PACKAGE_SUFFIX = "-";
390
391    static final int SCAN_NO_DEX = 1<<1;
392    static final int SCAN_FORCE_DEX = 1<<2;
393    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
394    static final int SCAN_NEW_INSTALL = 1<<4;
395    static final int SCAN_NO_PATHS = 1<<5;
396    static final int SCAN_UPDATE_TIME = 1<<6;
397    static final int SCAN_DEFER_DEX = 1<<7;
398    static final int SCAN_BOOTING = 1<<8;
399    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
400    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
401    static final int SCAN_REPLACING = 1<<11;
402    static final int SCAN_REQUIRE_KNOWN = 1<<12;
403    static final int SCAN_MOVE = 1<<13;
404    static final int SCAN_INITIAL = 1<<14;
405    static final int SCAN_CHECK_ONLY = 1<<15;
406    static final int SCAN_DONT_KILL_APP = 1<<17;
407    static final int SCAN_IGNORE_FROZEN = 1<<18;
408
409    static final int REMOVE_CHATTY = 1<<16;
410
411    private static final int[] EMPTY_INT_ARRAY = new int[0];
412
413    /**
414     * Timeout (in milliseconds) after which the watchdog should declare that
415     * our handler thread is wedged.  The usual default for such things is one
416     * minute but we sometimes do very lengthy I/O operations on this thread,
417     * such as installing multi-gigabyte applications, so ours needs to be longer.
418     */
419    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
420
421    /**
422     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
423     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
424     * settings entry if available, otherwise we use the hardcoded default.  If it's been
425     * more than this long since the last fstrim, we force one during the boot sequence.
426     *
427     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
428     * one gets run at the next available charging+idle time.  This final mandatory
429     * no-fstrim check kicks in only of the other scheduling criteria is never met.
430     */
431    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
432
433    /**
434     * Whether verification is enabled by default.
435     */
436    private static final boolean DEFAULT_VERIFY_ENABLE = true;
437
438    /**
439     * The default maximum time to wait for the verification agent to return in
440     * milliseconds.
441     */
442    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
443
444    /**
445     * The default response for package verification timeout.
446     *
447     * This can be either PackageManager.VERIFICATION_ALLOW or
448     * PackageManager.VERIFICATION_REJECT.
449     */
450    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
451
452    static final String PLATFORM_PACKAGE_NAME = "android";
453
454    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
455
456    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
457            DEFAULT_CONTAINER_PACKAGE,
458            "com.android.defcontainer.DefaultContainerService");
459
460    private static final String KILL_APP_REASON_GIDS_CHANGED =
461            "permission grant or revoke changed gids";
462
463    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
464            "permissions revoked";
465
466    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
467
468    private static final String PACKAGE_SCHEME = "package";
469
470    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
471    /**
472     * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
473     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
474     * VENDOR_OVERLAY_DIR.
475     */
476    private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
477
478    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
479    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
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    final ServiceThread mHandlerThread;
528
529    final PackageHandler mHandler;
530
531    private final ProcessLoggingHandler mProcessLoggingHandler;
532
533    /**
534     * Messages for {@link #mHandler} that need to wait for system ready before
535     * being dispatched.
536     */
537    private ArrayList<Message> mPostSystemReadyMessages;
538
539    final int mSdkVersion = Build.VERSION.SDK_INT;
540
541    final Context mContext;
542    final boolean mFactoryTest;
543    final boolean mOnlyCore;
544    final DisplayMetrics mMetrics;
545    final int mDefParseFlags;
546    final String[] mSeparateProcesses;
547    final boolean mIsUpgrade;
548    final boolean mIsPreNUpgrade;
549    final boolean mIsPreNMR1Upgrade;
550
551    @GuardedBy("mPackages")
552    private boolean mDexOptDialogShown;
553
554    /** The location for ASEC container files on internal storage. */
555    final String mAsecInternalPath;
556
557    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
558    // LOCK HELD.  Can be called with mInstallLock held.
559    @GuardedBy("mInstallLock")
560    final Installer mInstaller;
561
562    /** Directory where installed third-party apps stored */
563    final File mAppInstallDir;
564    final File mEphemeralInstallDir;
565
566    /**
567     * Directory to which applications installed internally have their
568     * 32 bit native libraries copied.
569     */
570    private File mAppLib32InstallDir;
571
572    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
573    // apps.
574    final File mDrmAppPrivateInstallDir;
575
576    // ----------------------------------------------------------------
577
578    // Lock for state used when installing and doing other long running
579    // operations.  Methods that must be called with this lock held have
580    // the suffix "LI".
581    final Object mInstallLock = new Object();
582
583    // ----------------------------------------------------------------
584
585    // Keys are String (package name), values are Package.  This also serves
586    // as the lock for the global state.  Methods that must be called with
587    // this lock held have the prefix "LP".
588    @GuardedBy("mPackages")
589    final ArrayMap<String, PackageParser.Package> mPackages =
590            new ArrayMap<String, PackageParser.Package>();
591
592    final ArrayMap<String, Set<String>> mKnownCodebase =
593            new ArrayMap<String, Set<String>>();
594
595    // Tracks available target package names -> overlay package paths.
596    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
597        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
598
599    /**
600     * Tracks new system packages [received in an OTA] that we expect to
601     * find updated user-installed versions. Keys are package name, values
602     * are package location.
603     */
604    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
605    /**
606     * Tracks high priority intent filters for protected actions. During boot, certain
607     * filter actions are protected and should never be allowed to have a high priority
608     * intent filter for them. However, there is one, and only one exception -- the
609     * setup wizard. It must be able to define a high priority intent filter for these
610     * actions to ensure there are no escapes from the wizard. We need to delay processing
611     * of these during boot as we need to look at all of the system packages in order
612     * to know which component is the setup wizard.
613     */
614    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
615    /**
616     * Whether or not processing protected filters should be deferred.
617     */
618    private boolean mDeferProtectedFilters = true;
619
620    /**
621     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
622     */
623    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
624    /**
625     * Whether or not system app permissions should be promoted from install to runtime.
626     */
627    boolean mPromoteSystemApps;
628
629    @GuardedBy("mPackages")
630    final Settings mSettings;
631
632    /**
633     * Set of package names that are currently "frozen", which means active
634     * surgery is being done on the code/data for that package. The platform
635     * will refuse to launch frozen packages to avoid race conditions.
636     *
637     * @see PackageFreezer
638     */
639    @GuardedBy("mPackages")
640    final ArraySet<String> mFrozenPackages = new ArraySet<>();
641
642    final ProtectedPackages mProtectedPackages;
643
644    boolean mFirstBoot;
645
646    // System configuration read by SystemConfig.
647    final int[] mGlobalGids;
648    final SparseArray<ArraySet<String>> mSystemPermissions;
649    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
650
651    // If mac_permissions.xml was found for seinfo labeling.
652    boolean mFoundPolicyFile;
653
654    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
655
656    public static final class SharedLibraryEntry {
657        public final String path;
658        public final String apk;
659
660        SharedLibraryEntry(String _path, String _apk) {
661            path = _path;
662            apk = _apk;
663        }
664    }
665
666    // Currently known shared libraries.
667    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
668            new ArrayMap<String, SharedLibraryEntry>();
669
670    // All available activities, for your resolving pleasure.
671    final ActivityIntentResolver mActivities =
672            new ActivityIntentResolver();
673
674    // All available receivers, for your resolving pleasure.
675    final ActivityIntentResolver mReceivers =
676            new ActivityIntentResolver();
677
678    // All available services, for your resolving pleasure.
679    final ServiceIntentResolver mServices = new ServiceIntentResolver();
680
681    // All available providers, for your resolving pleasure.
682    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
683
684    // Mapping from provider base names (first directory in content URI codePath)
685    // to the provider information.
686    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
687            new ArrayMap<String, PackageParser.Provider>();
688
689    // Mapping from instrumentation class names to info about them.
690    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
691            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
692
693    // Mapping from permission names to info about them.
694    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
695            new ArrayMap<String, PackageParser.PermissionGroup>();
696
697    // Packages whose data we have transfered into another package, thus
698    // should no longer exist.
699    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
700
701    // Broadcast actions that are only available to the system.
702    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
703
704    /** List of packages waiting for verification. */
705    final SparseArray<PackageVerificationState> mPendingVerification
706            = new SparseArray<PackageVerificationState>();
707
708    /** Set of packages associated with each app op permission. */
709    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
710
711    final PackageInstallerService mInstallerService;
712
713    private final PackageDexOptimizer mPackageDexOptimizer;
714    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
715    // is used by other apps).
716    private final DexManager mDexManager;
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                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
823                synchronized (mPackages) {
824                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
825                            packageName, domainsList) != null) {
826                        scheduleWriteSettingsLocked();
827                    }
828                }
829                sendVerificationRequest(userId, verificationId, ivs);
830            }
831            mCurrentIntentFilterVerifications.clear();
832        }
833
834        private void sendVerificationRequest(int userId, int verificationId,
835                IntentFilterVerificationState ivs) {
836
837            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
838            verificationIntent.putExtra(
839                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
840                    verificationId);
841            verificationIntent.putExtra(
842                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
843                    getDefaultScheme());
844            verificationIntent.putExtra(
845                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
846                    ivs.getHostsString());
847            verificationIntent.putExtra(
848                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
849                    ivs.getPackageName());
850            verificationIntent.setComponent(mIntentFilterVerifierComponent);
851            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
852
853            UserHandle user = new UserHandle(userId);
854            mContext.sendBroadcastAsUser(verificationIntent, user);
855            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
856                    "Sending IntentFilter verification broadcast");
857        }
858
859        public void receiveVerificationResponse(int verificationId) {
860            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
861
862            final boolean verified = ivs.isVerified();
863
864            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
865            final int count = filters.size();
866            if (DEBUG_DOMAIN_VERIFICATION) {
867                Slog.i(TAG, "Received verification response " + verificationId
868                        + " for " + count + " filters, verified=" + verified);
869            }
870            for (int n=0; n<count; n++) {
871                PackageParser.ActivityIntentInfo filter = filters.get(n);
872                filter.setVerified(verified);
873
874                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
875                        + " verified with result:" + verified + " and hosts:"
876                        + ivs.getHostsString());
877            }
878
879            mIntentFilterVerificationStates.remove(verificationId);
880
881            final String packageName = ivs.getPackageName();
882            IntentFilterVerificationInfo ivi = null;
883
884            synchronized (mPackages) {
885                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
886            }
887            if (ivi == null) {
888                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
889                        + verificationId + " packageName:" + packageName);
890                return;
891            }
892            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
893                    "Updating IntentFilterVerificationInfo for package " + packageName
894                            +" verificationId:" + verificationId);
895
896            synchronized (mPackages) {
897                if (verified) {
898                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
899                } else {
900                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
901                }
902                scheduleWriteSettingsLocked();
903
904                final int userId = ivs.getUserId();
905                if (userId != UserHandle.USER_ALL) {
906                    final int userStatus =
907                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
908
909                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
910                    boolean needUpdate = false;
911
912                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
913                    // already been set by the User thru the Disambiguation dialog
914                    switch (userStatus) {
915                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
916                            if (verified) {
917                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
918                            } else {
919                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
920                            }
921                            needUpdate = true;
922                            break;
923
924                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
925                            if (verified) {
926                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
927                                needUpdate = true;
928                            }
929                            break;
930
931                        default:
932                            // Nothing to do
933                    }
934
935                    if (needUpdate) {
936                        mSettings.updateIntentFilterVerificationStatusLPw(
937                                packageName, updatedStatus, userId);
938                        scheduleWritePackageRestrictionsLocked(userId);
939                    }
940                }
941            }
942        }
943
944        @Override
945        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
946                    ActivityIntentInfo filter, String packageName) {
947            if (!hasValidDomains(filter)) {
948                return false;
949            }
950            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
951            if (ivs == null) {
952                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
953                        packageName);
954            }
955            if (DEBUG_DOMAIN_VERIFICATION) {
956                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
957            }
958            ivs.addFilter(filter);
959            return true;
960        }
961
962        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
963                int userId, int verificationId, String packageName) {
964            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
965                    verifierUid, userId, packageName);
966            ivs.setPendingState();
967            synchronized (mPackages) {
968                mIntentFilterVerificationStates.append(verificationId, ivs);
969                mCurrentIntentFilterVerifications.add(verificationId);
970            }
971            return ivs;
972        }
973    }
974
975    private static boolean hasValidDomains(ActivityIntentInfo filter) {
976        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
977                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
978                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
979    }
980
981    // Set of pending broadcasts for aggregating enable/disable of components.
982    static class PendingPackageBroadcasts {
983        // for each user id, a map of <package name -> components within that package>
984        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
985
986        public PendingPackageBroadcasts() {
987            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
988        }
989
990        public ArrayList<String> get(int userId, String packageName) {
991            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
992            return packages.get(packageName);
993        }
994
995        public void put(int userId, String packageName, ArrayList<String> components) {
996            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
997            packages.put(packageName, components);
998        }
999
1000        public void remove(int userId, String packageName) {
1001            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1002            if (packages != null) {
1003                packages.remove(packageName);
1004            }
1005        }
1006
1007        public void remove(int userId) {
1008            mUidMap.remove(userId);
1009        }
1010
1011        public int userIdCount() {
1012            return mUidMap.size();
1013        }
1014
1015        public int userIdAt(int n) {
1016            return mUidMap.keyAt(n);
1017        }
1018
1019        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1020            return mUidMap.get(userId);
1021        }
1022
1023        public int size() {
1024            // total number of pending broadcast entries across all userIds
1025            int num = 0;
1026            for (int i = 0; i< mUidMap.size(); i++) {
1027                num += mUidMap.valueAt(i).size();
1028            }
1029            return num;
1030        }
1031
1032        public void clear() {
1033            mUidMap.clear();
1034        }
1035
1036        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1037            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1038            if (map == null) {
1039                map = new ArrayMap<String, ArrayList<String>>();
1040                mUidMap.put(userId, map);
1041            }
1042            return map;
1043        }
1044    }
1045    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1046
1047    // Service Connection to remote media container service to copy
1048    // package uri's from external media onto secure containers
1049    // or internal storage.
1050    private IMediaContainerService mContainerService = null;
1051
1052    static final int SEND_PENDING_BROADCAST = 1;
1053    static final int MCS_BOUND = 3;
1054    static final int END_COPY = 4;
1055    static final int INIT_COPY = 5;
1056    static final int MCS_UNBIND = 6;
1057    static final int START_CLEANING_PACKAGE = 7;
1058    static final int FIND_INSTALL_LOC = 8;
1059    static final int POST_INSTALL = 9;
1060    static final int MCS_RECONNECT = 10;
1061    static final int MCS_GIVE_UP = 11;
1062    static final int UPDATED_MEDIA_STATUS = 12;
1063    static final int WRITE_SETTINGS = 13;
1064    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1065    static final int PACKAGE_VERIFIED = 15;
1066    static final int CHECK_PENDING_VERIFICATION = 16;
1067    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1068    static final int INTENT_FILTER_VERIFIED = 18;
1069    static final int WRITE_PACKAGE_LIST = 19;
1070
1071    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1072
1073    // Delay time in millisecs
1074    static final int BROADCAST_DELAY = 10 * 1000;
1075
1076    static UserManagerService sUserManager;
1077
1078    // Stores a list of users whose package restrictions file needs to be updated
1079    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1080
1081    final private DefaultContainerConnection mDefContainerConn =
1082            new DefaultContainerConnection();
1083    class DefaultContainerConnection implements ServiceConnection {
1084        public void onServiceConnected(ComponentName name, IBinder service) {
1085            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1086            IMediaContainerService imcs =
1087                IMediaContainerService.Stub.asInterface(service);
1088            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1089        }
1090
1091        public void onServiceDisconnected(ComponentName name) {
1092            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1093        }
1094    }
1095
1096    // Recordkeeping of restore-after-install operations that are currently in flight
1097    // between the Package Manager and the Backup Manager
1098    static class PostInstallData {
1099        public InstallArgs args;
1100        public PackageInstalledInfo res;
1101
1102        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1103            args = _a;
1104            res = _r;
1105        }
1106    }
1107
1108    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1109    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1110
1111    // XML tags for backup/restore of various bits of state
1112    private static final String TAG_PREFERRED_BACKUP = "pa";
1113    private static final String TAG_DEFAULT_APPS = "da";
1114    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1115
1116    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1117    private static final String TAG_ALL_GRANTS = "rt-grants";
1118    private static final String TAG_GRANT = "grant";
1119    private static final String ATTR_PACKAGE_NAME = "pkg";
1120
1121    private static final String TAG_PERMISSION = "perm";
1122    private static final String ATTR_PERMISSION_NAME = "name";
1123    private static final String ATTR_IS_GRANTED = "g";
1124    private static final String ATTR_USER_SET = "set";
1125    private static final String ATTR_USER_FIXED = "fixed";
1126    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1127
1128    // System/policy permission grants are not backed up
1129    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1130            FLAG_PERMISSION_POLICY_FIXED
1131            | FLAG_PERMISSION_SYSTEM_FIXED
1132            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1133
1134    // And we back up these user-adjusted states
1135    private static final int USER_RUNTIME_GRANT_MASK =
1136            FLAG_PERMISSION_USER_SET
1137            | FLAG_PERMISSION_USER_FIXED
1138            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1139
1140    final @Nullable String mRequiredVerifierPackage;
1141    final @NonNull String mRequiredInstallerPackage;
1142    final @NonNull String mRequiredUninstallerPackage;
1143    final @Nullable String mSetupWizardPackage;
1144    final @Nullable String mStorageManagerPackage;
1145    final @NonNull String mServicesSystemSharedLibraryPackageName;
1146    final @NonNull String mSharedSystemSharedLibraryPackageName;
1147
1148    final boolean mPermissionReviewRequired;
1149
1150    private final PackageUsage mPackageUsage = new PackageUsage();
1151    private final CompilerStats mCompilerStats = new CompilerStats();
1152
1153    class PackageHandler extends Handler {
1154        private boolean mBound = false;
1155        final ArrayList<HandlerParams> mPendingInstalls =
1156            new ArrayList<HandlerParams>();
1157
1158        private boolean connectToService() {
1159            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1160                    " DefaultContainerService");
1161            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1162            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1163            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1164                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1165                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1166                mBound = true;
1167                return true;
1168            }
1169            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1170            return false;
1171        }
1172
1173        private void disconnectService() {
1174            mContainerService = null;
1175            mBound = false;
1176            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1177            mContext.unbindService(mDefContainerConn);
1178            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1179        }
1180
1181        PackageHandler(Looper looper) {
1182            super(looper);
1183        }
1184
1185        public void handleMessage(Message msg) {
1186            try {
1187                doHandleMessage(msg);
1188            } finally {
1189                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1190            }
1191        }
1192
1193        void doHandleMessage(Message msg) {
1194            switch (msg.what) {
1195                case INIT_COPY: {
1196                    HandlerParams params = (HandlerParams) msg.obj;
1197                    int idx = mPendingInstalls.size();
1198                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1199                    // If a bind was already initiated we dont really
1200                    // need to do anything. The pending install
1201                    // will be processed later on.
1202                    if (!mBound) {
1203                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1204                                System.identityHashCode(mHandler));
1205                        // If this is the only one pending we might
1206                        // have to bind to the service again.
1207                        if (!connectToService()) {
1208                            Slog.e(TAG, "Failed to bind to media container service");
1209                            params.serviceError();
1210                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1211                                    System.identityHashCode(mHandler));
1212                            if (params.traceMethod != null) {
1213                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1214                                        params.traceCookie);
1215                            }
1216                            return;
1217                        } else {
1218                            // Once we bind to the service, the first
1219                            // pending request will be processed.
1220                            mPendingInstalls.add(idx, params);
1221                        }
1222                    } else {
1223                        mPendingInstalls.add(idx, params);
1224                        // Already bound to the service. Just make
1225                        // sure we trigger off processing the first request.
1226                        if (idx == 0) {
1227                            mHandler.sendEmptyMessage(MCS_BOUND);
1228                        }
1229                    }
1230                    break;
1231                }
1232                case MCS_BOUND: {
1233                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1234                    if (msg.obj != null) {
1235                        mContainerService = (IMediaContainerService) msg.obj;
1236                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1237                                System.identityHashCode(mHandler));
1238                    }
1239                    if (mContainerService == null) {
1240                        if (!mBound) {
1241                            // Something seriously wrong since we are not bound and we are not
1242                            // waiting for connection. Bail out.
1243                            Slog.e(TAG, "Cannot bind to media container service");
1244                            for (HandlerParams params : mPendingInstalls) {
1245                                // Indicate service bind error
1246                                params.serviceError();
1247                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1248                                        System.identityHashCode(params));
1249                                if (params.traceMethod != null) {
1250                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1251                                            params.traceMethod, params.traceCookie);
1252                                }
1253                                return;
1254                            }
1255                            mPendingInstalls.clear();
1256                        } else {
1257                            Slog.w(TAG, "Waiting to connect to media container service");
1258                        }
1259                    } else if (mPendingInstalls.size() > 0) {
1260                        HandlerParams params = mPendingInstalls.get(0);
1261                        if (params != null) {
1262                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1263                                    System.identityHashCode(params));
1264                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1265                            if (params.startCopy()) {
1266                                // We are done...  look for more work or to
1267                                // go idle.
1268                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1269                                        "Checking for more work or unbind...");
1270                                // Delete pending install
1271                                if (mPendingInstalls.size() > 0) {
1272                                    mPendingInstalls.remove(0);
1273                                }
1274                                if (mPendingInstalls.size() == 0) {
1275                                    if (mBound) {
1276                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1277                                                "Posting delayed MCS_UNBIND");
1278                                        removeMessages(MCS_UNBIND);
1279                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1280                                        // Unbind after a little delay, to avoid
1281                                        // continual thrashing.
1282                                        sendMessageDelayed(ubmsg, 10000);
1283                                    }
1284                                } else {
1285                                    // There are more pending requests in queue.
1286                                    // Just post MCS_BOUND message to trigger processing
1287                                    // of next pending install.
1288                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1289                                            "Posting MCS_BOUND for next work");
1290                                    mHandler.sendEmptyMessage(MCS_BOUND);
1291                                }
1292                            }
1293                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1294                        }
1295                    } else {
1296                        // Should never happen ideally.
1297                        Slog.w(TAG, "Empty queue");
1298                    }
1299                    break;
1300                }
1301                case MCS_RECONNECT: {
1302                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1303                    if (mPendingInstalls.size() > 0) {
1304                        if (mBound) {
1305                            disconnectService();
1306                        }
1307                        if (!connectToService()) {
1308                            Slog.e(TAG, "Failed to bind to media container service");
1309                            for (HandlerParams params : mPendingInstalls) {
1310                                // Indicate service bind error
1311                                params.serviceError();
1312                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1313                                        System.identityHashCode(params));
1314                            }
1315                            mPendingInstalls.clear();
1316                        }
1317                    }
1318                    break;
1319                }
1320                case MCS_UNBIND: {
1321                    // If there is no actual work left, then time to unbind.
1322                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1323
1324                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1325                        if (mBound) {
1326                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1327
1328                            disconnectService();
1329                        }
1330                    } else if (mPendingInstalls.size() > 0) {
1331                        // There are more pending requests in queue.
1332                        // Just post MCS_BOUND message to trigger processing
1333                        // of next pending install.
1334                        mHandler.sendEmptyMessage(MCS_BOUND);
1335                    }
1336
1337                    break;
1338                }
1339                case MCS_GIVE_UP: {
1340                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1341                    HandlerParams params = mPendingInstalls.remove(0);
1342                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1343                            System.identityHashCode(params));
1344                    break;
1345                }
1346                case SEND_PENDING_BROADCAST: {
1347                    String packages[];
1348                    ArrayList<String> components[];
1349                    int size = 0;
1350                    int uids[];
1351                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1352                    synchronized (mPackages) {
1353                        if (mPendingBroadcasts == null) {
1354                            return;
1355                        }
1356                        size = mPendingBroadcasts.size();
1357                        if (size <= 0) {
1358                            // Nothing to be done. Just return
1359                            return;
1360                        }
1361                        packages = new String[size];
1362                        components = new ArrayList[size];
1363                        uids = new int[size];
1364                        int i = 0;  // filling out the above arrays
1365
1366                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1367                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1368                            Iterator<Map.Entry<String, ArrayList<String>>> it
1369                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1370                                            .entrySet().iterator();
1371                            while (it.hasNext() && i < size) {
1372                                Map.Entry<String, ArrayList<String>> ent = it.next();
1373                                packages[i] = ent.getKey();
1374                                components[i] = ent.getValue();
1375                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1376                                uids[i] = (ps != null)
1377                                        ? UserHandle.getUid(packageUserId, ps.appId)
1378                                        : -1;
1379                                i++;
1380                            }
1381                        }
1382                        size = i;
1383                        mPendingBroadcasts.clear();
1384                    }
1385                    // Send broadcasts
1386                    for (int i = 0; i < size; i++) {
1387                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1388                    }
1389                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1390                    break;
1391                }
1392                case START_CLEANING_PACKAGE: {
1393                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1394                    final String packageName = (String)msg.obj;
1395                    final int userId = msg.arg1;
1396                    final boolean andCode = msg.arg2 != 0;
1397                    synchronized (mPackages) {
1398                        if (userId == UserHandle.USER_ALL) {
1399                            int[] users = sUserManager.getUserIds();
1400                            for (int user : users) {
1401                                mSettings.addPackageToCleanLPw(
1402                                        new PackageCleanItem(user, packageName, andCode));
1403                            }
1404                        } else {
1405                            mSettings.addPackageToCleanLPw(
1406                                    new PackageCleanItem(userId, packageName, andCode));
1407                        }
1408                    }
1409                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1410                    startCleaningPackages();
1411                } break;
1412                case POST_INSTALL: {
1413                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1414
1415                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1416                    final boolean didRestore = (msg.arg2 != 0);
1417                    mRunningInstalls.delete(msg.arg1);
1418
1419                    if (data != null) {
1420                        InstallArgs args = data.args;
1421                        PackageInstalledInfo parentRes = data.res;
1422
1423                        final boolean grantPermissions = (args.installFlags
1424                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1425                        final boolean killApp = (args.installFlags
1426                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1427                        final String[] grantedPermissions = args.installGrantPermissions;
1428
1429                        // Handle the parent package
1430                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1431                                grantedPermissions, didRestore, args.installerPackageName,
1432                                args.observer);
1433
1434                        // Handle the child packages
1435                        final int childCount = (parentRes.addedChildPackages != null)
1436                                ? parentRes.addedChildPackages.size() : 0;
1437                        for (int i = 0; i < childCount; i++) {
1438                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1439                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1440                                    grantedPermissions, false, args.installerPackageName,
1441                                    args.observer);
1442                        }
1443
1444                        // Log tracing if needed
1445                        if (args.traceMethod != null) {
1446                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1447                                    args.traceCookie);
1448                        }
1449                    } else {
1450                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1451                    }
1452
1453                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1454                } break;
1455                case UPDATED_MEDIA_STATUS: {
1456                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1457                    boolean reportStatus = msg.arg1 == 1;
1458                    boolean doGc = msg.arg2 == 1;
1459                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1460                    if (doGc) {
1461                        // Force a gc to clear up stale containers.
1462                        Runtime.getRuntime().gc();
1463                    }
1464                    if (msg.obj != null) {
1465                        @SuppressWarnings("unchecked")
1466                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1467                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1468                        // Unload containers
1469                        unloadAllContainers(args);
1470                    }
1471                    if (reportStatus) {
1472                        try {
1473                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1474                            PackageHelper.getMountService().finishMediaUpdate();
1475                        } catch (RemoteException e) {
1476                            Log.e(TAG, "MountService not running?");
1477                        }
1478                    }
1479                } break;
1480                case WRITE_SETTINGS: {
1481                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1482                    synchronized (mPackages) {
1483                        removeMessages(WRITE_SETTINGS);
1484                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1485                        mSettings.writeLPr();
1486                        mDirtyUsers.clear();
1487                    }
1488                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1489                } break;
1490                case WRITE_PACKAGE_RESTRICTIONS: {
1491                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1492                    synchronized (mPackages) {
1493                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1494                        for (int userId : mDirtyUsers) {
1495                            mSettings.writePackageRestrictionsLPr(userId);
1496                        }
1497                        mDirtyUsers.clear();
1498                    }
1499                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1500                } break;
1501                case WRITE_PACKAGE_LIST: {
1502                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1503                    synchronized (mPackages) {
1504                        removeMessages(WRITE_PACKAGE_LIST);
1505                        mSettings.writePackageListLPr(msg.arg1);
1506                    }
1507                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1508                } break;
1509                case CHECK_PENDING_VERIFICATION: {
1510                    final int verificationId = msg.arg1;
1511                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1512
1513                    if ((state != null) && !state.timeoutExtended()) {
1514                        final InstallArgs args = state.getInstallArgs();
1515                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1516
1517                        Slog.i(TAG, "Verification timed out for " + originUri);
1518                        mPendingVerification.remove(verificationId);
1519
1520                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1521
1522                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1523                            Slog.i(TAG, "Continuing with installation of " + originUri);
1524                            state.setVerifierResponse(Binder.getCallingUid(),
1525                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1526                            broadcastPackageVerified(verificationId, originUri,
1527                                    PackageManager.VERIFICATION_ALLOW,
1528                                    state.getInstallArgs().getUser());
1529                            try {
1530                                ret = args.copyApk(mContainerService, true);
1531                            } catch (RemoteException e) {
1532                                Slog.e(TAG, "Could not contact the ContainerService");
1533                            }
1534                        } else {
1535                            broadcastPackageVerified(verificationId, originUri,
1536                                    PackageManager.VERIFICATION_REJECT,
1537                                    state.getInstallArgs().getUser());
1538                        }
1539
1540                        Trace.asyncTraceEnd(
1541                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1542
1543                        processPendingInstall(args, ret);
1544                        mHandler.sendEmptyMessage(MCS_UNBIND);
1545                    }
1546                    break;
1547                }
1548                case PACKAGE_VERIFIED: {
1549                    final int verificationId = msg.arg1;
1550
1551                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1552                    if (state == null) {
1553                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1554                        break;
1555                    }
1556
1557                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1558
1559                    state.setVerifierResponse(response.callerUid, response.code);
1560
1561                    if (state.isVerificationComplete()) {
1562                        mPendingVerification.remove(verificationId);
1563
1564                        final InstallArgs args = state.getInstallArgs();
1565                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1566
1567                        int ret;
1568                        if (state.isInstallAllowed()) {
1569                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1570                            broadcastPackageVerified(verificationId, originUri,
1571                                    response.code, state.getInstallArgs().getUser());
1572                            try {
1573                                ret = args.copyApk(mContainerService, true);
1574                            } catch (RemoteException e) {
1575                                Slog.e(TAG, "Could not contact the ContainerService");
1576                            }
1577                        } else {
1578                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1579                        }
1580
1581                        Trace.asyncTraceEnd(
1582                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1583
1584                        processPendingInstall(args, ret);
1585                        mHandler.sendEmptyMessage(MCS_UNBIND);
1586                    }
1587
1588                    break;
1589                }
1590                case START_INTENT_FILTER_VERIFICATIONS: {
1591                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1592                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1593                            params.replacing, params.pkg);
1594                    break;
1595                }
1596                case INTENT_FILTER_VERIFIED: {
1597                    final int verificationId = msg.arg1;
1598
1599                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1600                            verificationId);
1601                    if (state == null) {
1602                        Slog.w(TAG, "Invalid IntentFilter verification token "
1603                                + verificationId + " received");
1604                        break;
1605                    }
1606
1607                    final int userId = state.getUserId();
1608
1609                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1610                            "Processing IntentFilter verification with token:"
1611                            + verificationId + " and userId:" + userId);
1612
1613                    final IntentFilterVerificationResponse response =
1614                            (IntentFilterVerificationResponse) msg.obj;
1615
1616                    state.setVerifierResponse(response.callerUid, response.code);
1617
1618                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1619                            "IntentFilter verification with token:" + verificationId
1620                            + " and userId:" + userId
1621                            + " is settings verifier response with response code:"
1622                            + response.code);
1623
1624                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1625                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1626                                + response.getFailedDomainsString());
1627                    }
1628
1629                    if (state.isVerificationComplete()) {
1630                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1631                    } else {
1632                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1633                                "IntentFilter verification with token:" + verificationId
1634                                + " was not said to be complete");
1635                    }
1636
1637                    break;
1638                }
1639            }
1640        }
1641    }
1642
1643    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1644            boolean killApp, String[] grantedPermissions,
1645            boolean launchedForRestore, String installerPackage,
1646            IPackageInstallObserver2 installObserver) {
1647        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1648            // Send the removed broadcasts
1649            if (res.removedInfo != null) {
1650                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1651            }
1652
1653            // Now that we successfully installed the package, grant runtime
1654            // permissions if requested before broadcasting the install.
1655            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1656                    >= Build.VERSION_CODES.M) {
1657                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1658            }
1659
1660            final boolean update = res.removedInfo != null
1661                    && res.removedInfo.removedPackage != null;
1662
1663            // If this is the first time we have child packages for a disabled privileged
1664            // app that had no children, we grant requested runtime permissions to the new
1665            // children if the parent on the system image had them already granted.
1666            if (res.pkg.parentPackage != null) {
1667                synchronized (mPackages) {
1668                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1669                }
1670            }
1671
1672            synchronized (mPackages) {
1673                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1674            }
1675
1676            final String packageName = res.pkg.applicationInfo.packageName;
1677            Bundle extras = new Bundle(1);
1678            extras.putInt(Intent.EXTRA_UID, res.uid);
1679
1680            // Determine the set of users who are adding this package for
1681            // the first time vs. those who are seeing an update.
1682            int[] firstUsers = EMPTY_INT_ARRAY;
1683            int[] updateUsers = EMPTY_INT_ARRAY;
1684            if (res.origUsers == null || res.origUsers.length == 0) {
1685                firstUsers = res.newUsers;
1686            } else {
1687                for (int newUser : res.newUsers) {
1688                    boolean isNew = true;
1689                    for (int origUser : res.origUsers) {
1690                        if (origUser == newUser) {
1691                            isNew = false;
1692                            break;
1693                        }
1694                    }
1695                    if (isNew) {
1696                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1697                    } else {
1698                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1699                    }
1700                }
1701            }
1702
1703            // Send installed broadcasts if the install/update is not ephemeral
1704            if (!isEphemeral(res.pkg)) {
1705                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1706
1707                // Send added for users that see the package for the first time
1708                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1709                        extras, 0 /*flags*/, null /*targetPackage*/,
1710                        null /*finishedReceiver*/, firstUsers);
1711
1712                // Send added for users that don't see the package for the first time
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            if (!isEphemeral(res.pkg)) {
1789                // Notify DexManager that the package was installed for new users.
1790                // The updated users should already be indexed and the package code paths
1791                // should not change.
1792                // Don't notify the manager for ephemeral apps as they are not expected to
1793                // survive long enough to benefit of background optimizations.
1794                for (int userId : firstUsers) {
1795                    PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1796                    mDexManager.notifyPackageInstalled(info, userId);
1797                }
1798            }
1799        }
1800
1801        // If someone is watching installs - notify them
1802        if (installObserver != null) {
1803            try {
1804                Bundle extras = extrasForInstallResult(res);
1805                installObserver.onPackageInstalled(res.name, res.returnCode,
1806                        res.returnMsg, extras);
1807            } catch (RemoteException e) {
1808                Slog.i(TAG, "Observer no longer exists.");
1809            }
1810        }
1811    }
1812
1813    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1814            PackageParser.Package pkg) {
1815        if (pkg.parentPackage == null) {
1816            return;
1817        }
1818        if (pkg.requestedPermissions == null) {
1819            return;
1820        }
1821        final PackageSetting disabledSysParentPs = mSettings
1822                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1823        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1824                || !disabledSysParentPs.isPrivileged()
1825                || (disabledSysParentPs.childPackageNames != null
1826                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1827            return;
1828        }
1829        final int[] allUserIds = sUserManager.getUserIds();
1830        final int permCount = pkg.requestedPermissions.size();
1831        for (int i = 0; i < permCount; i++) {
1832            String permission = pkg.requestedPermissions.get(i);
1833            BasePermission bp = mSettings.mPermissions.get(permission);
1834            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1835                continue;
1836            }
1837            for (int userId : allUserIds) {
1838                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1839                        permission, userId)) {
1840                    grantRuntimePermission(pkg.packageName, permission, userId);
1841                }
1842            }
1843        }
1844    }
1845
1846    private StorageEventListener mStorageListener = new StorageEventListener() {
1847        @Override
1848        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1849            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1850                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1851                    final String volumeUuid = vol.getFsUuid();
1852
1853                    // Clean up any users or apps that were removed or recreated
1854                    // while this volume was missing
1855                    reconcileUsers(volumeUuid);
1856                    reconcileApps(volumeUuid);
1857
1858                    // Clean up any install sessions that expired or were
1859                    // cancelled while this volume was missing
1860                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1861
1862                    loadPrivatePackages(vol);
1863
1864                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1865                    unloadPrivatePackages(vol);
1866                }
1867            }
1868
1869            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1870                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1871                    updateExternalMediaStatus(true, false);
1872                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1873                    updateExternalMediaStatus(false, false);
1874                }
1875            }
1876        }
1877
1878        @Override
1879        public void onVolumeForgotten(String fsUuid) {
1880            if (TextUtils.isEmpty(fsUuid)) {
1881                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1882                return;
1883            }
1884
1885            // Remove any apps installed on the forgotten volume
1886            synchronized (mPackages) {
1887                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1888                for (PackageSetting ps : packages) {
1889                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1890                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1891                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1892                }
1893
1894                mSettings.onVolumeForgotten(fsUuid);
1895                mSettings.writeLPr();
1896            }
1897        }
1898    };
1899
1900    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1901            String[] grantedPermissions) {
1902        for (int userId : userIds) {
1903            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1904        }
1905
1906        // We could have touched GID membership, so flush out packages.list
1907        synchronized (mPackages) {
1908            mSettings.writePackageListLPr();
1909        }
1910    }
1911
1912    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1913            String[] grantedPermissions) {
1914        SettingBase sb = (SettingBase) pkg.mExtras;
1915        if (sb == null) {
1916            return;
1917        }
1918
1919        PermissionsState permissionsState = sb.getPermissionsState();
1920
1921        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1922                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1923
1924        for (String permission : pkg.requestedPermissions) {
1925            final BasePermission bp;
1926            synchronized (mPackages) {
1927                bp = mSettings.mPermissions.get(permission);
1928            }
1929            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1930                    && (grantedPermissions == null
1931                           || ArrayUtils.contains(grantedPermissions, permission))) {
1932                final int flags = permissionsState.getPermissionFlags(permission, userId);
1933                // Installer cannot change immutable permissions.
1934                if ((flags & immutableFlags) == 0) {
1935                    grantRuntimePermission(pkg.packageName, permission, userId);
1936                }
1937            }
1938        }
1939    }
1940
1941    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1942        Bundle extras = null;
1943        switch (res.returnCode) {
1944            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1945                extras = new Bundle();
1946                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1947                        res.origPermission);
1948                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1949                        res.origPackage);
1950                break;
1951            }
1952            case PackageManager.INSTALL_SUCCEEDED: {
1953                extras = new Bundle();
1954                extras.putBoolean(Intent.EXTRA_REPLACING,
1955                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1956                break;
1957            }
1958        }
1959        return extras;
1960    }
1961
1962    void scheduleWriteSettingsLocked() {
1963        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1964            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1965        }
1966    }
1967
1968    void scheduleWritePackageListLocked(int userId) {
1969        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1970            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1971            msg.arg1 = userId;
1972            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1973        }
1974    }
1975
1976    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1977        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1978        scheduleWritePackageRestrictionsLocked(userId);
1979    }
1980
1981    void scheduleWritePackageRestrictionsLocked(int userId) {
1982        final int[] userIds = (userId == UserHandle.USER_ALL)
1983                ? sUserManager.getUserIds() : new int[]{userId};
1984        for (int nextUserId : userIds) {
1985            if (!sUserManager.exists(nextUserId)) return;
1986            mDirtyUsers.add(nextUserId);
1987            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1988                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1989            }
1990        }
1991    }
1992
1993    public static PackageManagerService main(Context context, Installer installer,
1994            boolean factoryTest, boolean onlyCore) {
1995        // Self-check for initial settings.
1996        PackageManagerServiceCompilerMapping.checkProperties();
1997
1998        PackageManagerService m = new PackageManagerService(context, installer,
1999                factoryTest, onlyCore);
2000        m.enableSystemUserPackages();
2001        ServiceManager.addService("package", m);
2002        return m;
2003    }
2004
2005    private void enableSystemUserPackages() {
2006        if (!UserManager.isSplitSystemUser()) {
2007            return;
2008        }
2009        // For system user, enable apps based on the following conditions:
2010        // - app is whitelisted or belong to one of these groups:
2011        //   -- system app which has no launcher icons
2012        //   -- system app which has INTERACT_ACROSS_USERS permission
2013        //   -- system IME app
2014        // - app is not in the blacklist
2015        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2016        Set<String> enableApps = new ArraySet<>();
2017        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2018                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2019                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2020        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2021        enableApps.addAll(wlApps);
2022        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2023                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2024        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2025        enableApps.removeAll(blApps);
2026        Log.i(TAG, "Applications installed for system user: " + enableApps);
2027        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2028                UserHandle.SYSTEM);
2029        final int allAppsSize = allAps.size();
2030        synchronized (mPackages) {
2031            for (int i = 0; i < allAppsSize; i++) {
2032                String pName = allAps.get(i);
2033                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2034                // Should not happen, but we shouldn't be failing if it does
2035                if (pkgSetting == null) {
2036                    continue;
2037                }
2038                boolean install = enableApps.contains(pName);
2039                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2040                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2041                            + " for system user");
2042                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2043                }
2044            }
2045        }
2046    }
2047
2048    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2049        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2050                Context.DISPLAY_SERVICE);
2051        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2052    }
2053
2054    /**
2055     * Requests that files preopted on a secondary system partition be copied to the data partition
2056     * if possible.  Note that the actual copying of the files is accomplished by init for security
2057     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2058     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2059     */
2060    private static void requestCopyPreoptedFiles() {
2061        final int WAIT_TIME_MS = 100;
2062        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2063        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2064            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2065            // We will wait for up to 100 seconds.
2066            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2067            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2068                try {
2069                    Thread.sleep(WAIT_TIME_MS);
2070                } catch (InterruptedException e) {
2071                    // Do nothing
2072                }
2073                if (SystemClock.uptimeMillis() > timeEnd) {
2074                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2075                    Slog.wtf(TAG, "cppreopt did not finish!");
2076                    break;
2077                }
2078            }
2079        }
2080    }
2081
2082    public PackageManagerService(Context context, Installer installer,
2083            boolean factoryTest, boolean onlyCore) {
2084        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2085                SystemClock.uptimeMillis());
2086
2087        if (mSdkVersion <= 0) {
2088            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2089        }
2090
2091        mContext = context;
2092
2093        mPermissionReviewRequired = context.getResources().getBoolean(
2094                R.bool.config_permissionReviewRequired);
2095
2096        mFactoryTest = factoryTest;
2097        mOnlyCore = onlyCore;
2098        mMetrics = new DisplayMetrics();
2099        mSettings = new Settings(mPackages);
2100        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2101                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2102        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2103                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2104        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2105                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2106        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2107                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2108        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2109                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2110        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2111                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2112
2113        String separateProcesses = SystemProperties.get("debug.separate_processes");
2114        if (separateProcesses != null && separateProcesses.length() > 0) {
2115            if ("*".equals(separateProcesses)) {
2116                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2117                mSeparateProcesses = null;
2118                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2119            } else {
2120                mDefParseFlags = 0;
2121                mSeparateProcesses = separateProcesses.split(",");
2122                Slog.w(TAG, "Running with debug.separate_processes: "
2123                        + separateProcesses);
2124            }
2125        } else {
2126            mDefParseFlags = 0;
2127            mSeparateProcesses = null;
2128        }
2129
2130        mInstaller = installer;
2131        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2132                "*dexopt*");
2133        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2134        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2135
2136        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2137                FgThread.get().getLooper());
2138
2139        getDefaultDisplayMetrics(context, mMetrics);
2140
2141        SystemConfig systemConfig = SystemConfig.getInstance();
2142        mGlobalGids = systemConfig.getGlobalGids();
2143        mSystemPermissions = systemConfig.getSystemPermissions();
2144        mAvailableFeatures = systemConfig.getAvailableFeatures();
2145
2146        mProtectedPackages = new ProtectedPackages(mContext);
2147
2148        synchronized (mInstallLock) {
2149        // writer
2150        synchronized (mPackages) {
2151            mHandlerThread = new ServiceThread(TAG,
2152                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2153            mHandlerThread.start();
2154            mHandler = new PackageHandler(mHandlerThread.getLooper());
2155            mProcessLoggingHandler = new ProcessLoggingHandler();
2156            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2157
2158            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2159
2160            File dataDir = Environment.getDataDirectory();
2161            mAppInstallDir = new File(dataDir, "app");
2162            mAppLib32InstallDir = new File(dataDir, "app-lib");
2163            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2164            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2165            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2166
2167            sUserManager = new UserManagerService(context, this, mPackages);
2168
2169            // Propagate permission configuration in to package manager.
2170            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2171                    = systemConfig.getPermissions();
2172            for (int i=0; i<permConfig.size(); i++) {
2173                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2174                BasePermission bp = mSettings.mPermissions.get(perm.name);
2175                if (bp == null) {
2176                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2177                    mSettings.mPermissions.put(perm.name, bp);
2178                }
2179                if (perm.gids != null) {
2180                    bp.setGids(perm.gids, perm.perUser);
2181                }
2182            }
2183
2184            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2185            for (int i=0; i<libConfig.size(); i++) {
2186                mSharedLibraries.put(libConfig.keyAt(i),
2187                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2188            }
2189
2190            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2191
2192            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2193
2194            // Clean up orphaned packages for which the code path doesn't exist
2195            // and they are an update to a system app - caused by bug/32321269
2196            final int packageSettingCount = mSettings.mPackages.size();
2197            for (int i = packageSettingCount - 1; i >= 0; i--) {
2198                PackageSetting ps = mSettings.mPackages.valueAt(i);
2199                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2200                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2201                    mSettings.mPackages.removeAt(i);
2202                    mSettings.enableSystemPackageLPw(ps.name);
2203                }
2204            }
2205
2206            if (mFirstBoot) {
2207                requestCopyPreoptedFiles();
2208            }
2209
2210            String customResolverActivity = Resources.getSystem().getString(
2211                    R.string.config_customResolverActivity);
2212            if (TextUtils.isEmpty(customResolverActivity)) {
2213                customResolverActivity = null;
2214            } else {
2215                mCustomResolverComponentName = ComponentName.unflattenFromString(
2216                        customResolverActivity);
2217            }
2218
2219            long startTime = SystemClock.uptimeMillis();
2220
2221            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2222                    startTime);
2223
2224            // Set flag to monitor and not change apk file paths when
2225            // scanning install directories.
2226            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2227
2228            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2229            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2230
2231            if (bootClassPath == null) {
2232                Slog.w(TAG, "No BOOTCLASSPATH found!");
2233            }
2234
2235            if (systemServerClassPath == null) {
2236                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2237            }
2238
2239            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2240            final String[] dexCodeInstructionSets =
2241                    getDexCodeInstructionSets(
2242                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2243
2244            /**
2245             * Ensure all external libraries have had dexopt run on them.
2246             */
2247            if (mSharedLibraries.size() > 0) {
2248                // NOTE: For now, we're compiling these system "shared libraries"
2249                // (and framework jars) into all available architectures. It's possible
2250                // to compile them only when we come across an app that uses them (there's
2251                // already logic for that in scanPackageLI) but that adds some complexity.
2252                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2253                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2254                        final String lib = libEntry.path;
2255                        if (lib == null) {
2256                            continue;
2257                        }
2258
2259                        try {
2260                            // Shared libraries do not have profiles so we perform a full
2261                            // AOT compilation (if needed).
2262                            int dexoptNeeded = DexFile.getDexOptNeeded(
2263                                    lib, dexCodeInstructionSet,
2264                                    getCompilerFilterForReason(REASON_SHARED_APK),
2265                                    false /* newProfile */);
2266                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2267                                mInstaller.dexopt(lib, Process.SYSTEM_UID, "*",
2268                                        dexCodeInstructionSet, dexoptNeeded, null,
2269                                        DEXOPT_PUBLIC,
2270                                        getCompilerFilterForReason(REASON_SHARED_APK),
2271                                        StorageManager.UUID_PRIVATE_INTERNAL,
2272                                        PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK);
2273                            }
2274                        } catch (FileNotFoundException e) {
2275                            Slog.w(TAG, "Library not found: " + lib);
2276                        } catch (IOException | InstallerException e) {
2277                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2278                                    + e.getMessage());
2279                        }
2280                    }
2281                }
2282            }
2283
2284            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2285
2286            final VersionInfo ver = mSettings.getInternalVersion();
2287            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2288
2289            // when upgrading from pre-M, promote system app permissions from install to runtime
2290            mPromoteSystemApps =
2291                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2292
2293            // When upgrading from pre-N, we need to handle package extraction like first boot,
2294            // as there is no profiling data available.
2295            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2296
2297            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2298
2299            // save off the names of pre-existing system packages prior to scanning; we don't
2300            // want to automatically grant runtime permissions for new system apps
2301            if (mPromoteSystemApps) {
2302                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2303                while (pkgSettingIter.hasNext()) {
2304                    PackageSetting ps = pkgSettingIter.next();
2305                    if (isSystemApp(ps)) {
2306                        mExistingSystemPackages.add(ps.name);
2307                    }
2308                }
2309            }
2310
2311            // Collect vendor overlay packages. (Do this before scanning any apps.)
2312            // For security and version matching reason, only consider
2313            // overlay packages if they reside in the right directory.
2314            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2315            if (!overlayThemeDir.isEmpty()) {
2316                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2317                        | PackageParser.PARSE_IS_SYSTEM
2318                        | PackageParser.PARSE_IS_SYSTEM_DIR
2319                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2320            }
2321            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2322                    | PackageParser.PARSE_IS_SYSTEM
2323                    | PackageParser.PARSE_IS_SYSTEM_DIR
2324                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2325
2326            // Find base frameworks (resource packages without code).
2327            scanDirTracedLI(frameworkDir, mDefParseFlags
2328                    | PackageParser.PARSE_IS_SYSTEM
2329                    | PackageParser.PARSE_IS_SYSTEM_DIR
2330                    | PackageParser.PARSE_IS_PRIVILEGED,
2331                    scanFlags | SCAN_NO_DEX, 0);
2332
2333            // Collected privileged system packages.
2334            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2335            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2336                    | PackageParser.PARSE_IS_SYSTEM
2337                    | PackageParser.PARSE_IS_SYSTEM_DIR
2338                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2339
2340            // Collect ordinary system packages.
2341            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2342            scanDirTracedLI(systemAppDir, mDefParseFlags
2343                    | PackageParser.PARSE_IS_SYSTEM
2344                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2345
2346            // Collect all vendor packages.
2347            File vendorAppDir = new File("/vendor/app");
2348            try {
2349                vendorAppDir = vendorAppDir.getCanonicalFile();
2350            } catch (IOException e) {
2351                // failed to look up canonical path, continue with original one
2352            }
2353            scanDirTracedLI(vendorAppDir, mDefParseFlags
2354                    | PackageParser.PARSE_IS_SYSTEM
2355                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2356
2357            // Collect all OEM packages.
2358            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2359            scanDirTracedLI(oemAppDir, mDefParseFlags
2360                    | PackageParser.PARSE_IS_SYSTEM
2361                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2362
2363            // Prune any system packages that no longer exist.
2364            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2365            if (!mOnlyCore) {
2366                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2367                while (psit.hasNext()) {
2368                    PackageSetting ps = psit.next();
2369
2370                    /*
2371                     * If this is not a system app, it can't be a
2372                     * disable system app.
2373                     */
2374                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2375                        continue;
2376                    }
2377
2378                    /*
2379                     * If the package is scanned, it's not erased.
2380                     */
2381                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2382                    if (scannedPkg != null) {
2383                        /*
2384                         * If the system app is both scanned and in the
2385                         * disabled packages list, then it must have been
2386                         * added via OTA. Remove it from the currently
2387                         * scanned package so the previously user-installed
2388                         * application can be scanned.
2389                         */
2390                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2391                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2392                                    + ps.name + "; removing system app.  Last known codePath="
2393                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2394                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2395                                    + scannedPkg.mVersionCode);
2396                            removePackageLI(scannedPkg, true);
2397                            mExpectingBetter.put(ps.name, ps.codePath);
2398                        }
2399
2400                        continue;
2401                    }
2402
2403                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2404                        psit.remove();
2405                        logCriticalInfo(Log.WARN, "System package " + ps.name
2406                                + " no longer exists; it's data will be wiped");
2407                        // Actual deletion of code and data will be handled by later
2408                        // reconciliation step
2409                    } else {
2410                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2411                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2412                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2413                        }
2414                    }
2415                }
2416            }
2417
2418            //look for any incomplete package installations
2419            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2420            for (int i = 0; i < deletePkgsList.size(); i++) {
2421                // Actual deletion of code and data will be handled by later
2422                // reconciliation step
2423                final String packageName = deletePkgsList.get(i).name;
2424                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2425                synchronized (mPackages) {
2426                    mSettings.removePackageLPw(packageName);
2427                }
2428            }
2429
2430            //delete tmp files
2431            deleteTempPackageFiles();
2432
2433            // Remove any shared userIDs that have no associated packages
2434            mSettings.pruneSharedUsersLPw();
2435
2436            if (!mOnlyCore) {
2437                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2438                        SystemClock.uptimeMillis());
2439                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2440
2441                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2442                        | PackageParser.PARSE_FORWARD_LOCK,
2443                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2444
2445                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2446                        | PackageParser.PARSE_IS_EPHEMERAL,
2447                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2448
2449                /**
2450                 * Remove disable package settings for any updated system
2451                 * apps that were removed via an OTA. If they're not a
2452                 * previously-updated app, remove them completely.
2453                 * Otherwise, just revoke their system-level permissions.
2454                 */
2455                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2456                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2457                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2458
2459                    String msg;
2460                    if (deletedPkg == null) {
2461                        msg = "Updated system package " + deletedAppName
2462                                + " no longer exists; it's data will be wiped";
2463                        // Actual deletion of code and data will be handled by later
2464                        // reconciliation step
2465                    } else {
2466                        msg = "Updated system app + " + deletedAppName
2467                                + " no longer present; removing system privileges for "
2468                                + deletedAppName;
2469
2470                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2471
2472                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2473                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2474                    }
2475                    logCriticalInfo(Log.WARN, msg);
2476                }
2477
2478                /**
2479                 * Make sure all system apps that we expected to appear on
2480                 * the userdata partition actually showed up. If they never
2481                 * appeared, crawl back and revive the system version.
2482                 */
2483                for (int i = 0; i < mExpectingBetter.size(); i++) {
2484                    final String packageName = mExpectingBetter.keyAt(i);
2485                    if (!mPackages.containsKey(packageName)) {
2486                        final File scanFile = mExpectingBetter.valueAt(i);
2487
2488                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2489                                + " but never showed up; reverting to system");
2490
2491                        int reparseFlags = mDefParseFlags;
2492                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2493                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2494                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2495                                    | PackageParser.PARSE_IS_PRIVILEGED;
2496                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2497                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2498                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2499                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2500                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2501                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2502                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2503                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2504                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2505                        } else {
2506                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2507                            continue;
2508                        }
2509
2510                        mSettings.enableSystemPackageLPw(packageName);
2511
2512                        try {
2513                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2514                        } catch (PackageManagerException e) {
2515                            Slog.e(TAG, "Failed to parse original system package: "
2516                                    + e.getMessage());
2517                        }
2518                    }
2519                }
2520            }
2521            mExpectingBetter.clear();
2522
2523            // Resolve the storage manager.
2524            mStorageManagerPackage = getStorageManagerPackageName();
2525
2526            // Resolve protected action filters. Only the setup wizard is allowed to
2527            // have a high priority filter for these actions.
2528            mSetupWizardPackage = getSetupWizardPackageName();
2529            if (mProtectedFilters.size() > 0) {
2530                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2531                    Slog.i(TAG, "No setup wizard;"
2532                        + " All protected intents capped to priority 0");
2533                }
2534                for (ActivityIntentInfo filter : mProtectedFilters) {
2535                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2536                        if (DEBUG_FILTERS) {
2537                            Slog.i(TAG, "Found setup wizard;"
2538                                + " allow priority " + filter.getPriority() + ";"
2539                                + " package: " + filter.activity.info.packageName
2540                                + " activity: " + filter.activity.className
2541                                + " priority: " + filter.getPriority());
2542                        }
2543                        // skip setup wizard; allow it to keep the high priority filter
2544                        continue;
2545                    }
2546                    Slog.w(TAG, "Protected action; cap priority to 0;"
2547                            + " package: " + filter.activity.info.packageName
2548                            + " activity: " + filter.activity.className
2549                            + " origPrio: " + filter.getPriority());
2550                    filter.setPriority(0);
2551                }
2552            }
2553            mDeferProtectedFilters = false;
2554            mProtectedFilters.clear();
2555
2556            // Now that we know all of the shared libraries, update all clients to have
2557            // the correct library paths.
2558            updateAllSharedLibrariesLPw();
2559
2560            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2561                // NOTE: We ignore potential failures here during a system scan (like
2562                // the rest of the commands above) because there's precious little we
2563                // can do about it. A settings error is reported, though.
2564                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2565                        false /* boot complete */);
2566            }
2567
2568            // Now that we know all the packages we are keeping,
2569            // read and update their last usage times.
2570            mPackageUsage.read(mPackages);
2571            mCompilerStats.read();
2572
2573            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2574                    SystemClock.uptimeMillis());
2575            Slog.i(TAG, "Time to scan packages: "
2576                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2577                    + " seconds");
2578
2579            // If the platform SDK has changed since the last time we booted,
2580            // we need to re-grant app permission to catch any new ones that
2581            // appear.  This is really a hack, and means that apps can in some
2582            // cases get permissions that the user didn't initially explicitly
2583            // allow...  it would be nice to have some better way to handle
2584            // this situation.
2585            int updateFlags = UPDATE_PERMISSIONS_ALL;
2586            if (ver.sdkVersion != mSdkVersion) {
2587                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2588                        + mSdkVersion + "; regranting permissions for internal storage");
2589                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2590            }
2591            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2592            ver.sdkVersion = mSdkVersion;
2593
2594            // If this is the first boot or an update from pre-M, and it is a normal
2595            // boot, then we need to initialize the default preferred apps across
2596            // all defined users.
2597            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2598                for (UserInfo user : sUserManager.getUsers(true)) {
2599                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2600                    applyFactoryDefaultBrowserLPw(user.id);
2601                    primeDomainVerificationsLPw(user.id);
2602                }
2603            }
2604
2605            // Prepare storage for system user really early during boot,
2606            // since core system apps like SettingsProvider and SystemUI
2607            // can't wait for user to start
2608            final int storageFlags;
2609            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2610                storageFlags = StorageManager.FLAG_STORAGE_DE;
2611            } else {
2612                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2613            }
2614            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2615                    storageFlags);
2616
2617            // If this is first boot after an OTA, and a normal boot, then
2618            // we need to clear code cache directories.
2619            // Note that we do *not* clear the application profiles. These remain valid
2620            // across OTAs and are used to drive profile verification (post OTA) and
2621            // profile compilation (without waiting to collect a fresh set of profiles).
2622            if (mIsUpgrade && !onlyCore) {
2623                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2624                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2625                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2626                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2627                        // No apps are running this early, so no need to freeze
2628                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2629                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2630                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2631                    }
2632                }
2633                ver.fingerprint = Build.FINGERPRINT;
2634            }
2635
2636            checkDefaultBrowser();
2637
2638            // clear only after permissions and other defaults have been updated
2639            mExistingSystemPackages.clear();
2640            mPromoteSystemApps = false;
2641
2642            // All the changes are done during package scanning.
2643            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2644
2645            // can downgrade to reader
2646            mSettings.writeLPr();
2647
2648            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2649            // early on (before the package manager declares itself as early) because other
2650            // components in the system server might ask for package contexts for these apps.
2651            //
2652            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2653            // (i.e, that the data partition is unavailable).
2654            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2655                long start = System.nanoTime();
2656                List<PackageParser.Package> coreApps = new ArrayList<>();
2657                for (PackageParser.Package pkg : mPackages.values()) {
2658                    if (pkg.coreApp) {
2659                        coreApps.add(pkg);
2660                    }
2661                }
2662
2663                int[] stats = performDexOptUpgrade(coreApps, false,
2664                        getCompilerFilterForReason(REASON_CORE_APP));
2665
2666                final int elapsedTimeSeconds =
2667                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2668                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2669
2670                if (DEBUG_DEXOPT) {
2671                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2672                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2673                }
2674
2675
2676                // TODO: Should we log these stats to tron too ?
2677                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2678                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2679                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2680                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2681            }
2682
2683            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2684                    SystemClock.uptimeMillis());
2685
2686            if (!mOnlyCore) {
2687                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2688                mRequiredInstallerPackage = getRequiredInstallerLPr();
2689                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2690                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2691                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2692                        mIntentFilterVerifierComponent);
2693                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2694                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2695                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2696                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2697            } else {
2698                mRequiredVerifierPackage = null;
2699                mRequiredInstallerPackage = null;
2700                mRequiredUninstallerPackage = null;
2701                mIntentFilterVerifierComponent = null;
2702                mIntentFilterVerifier = null;
2703                mServicesSystemSharedLibraryPackageName = null;
2704                mSharedSystemSharedLibraryPackageName = null;
2705            }
2706
2707            mInstallerService = new PackageInstallerService(context, this);
2708
2709            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2710            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2711            // both the installer and resolver must be present to enable ephemeral
2712            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2713                if (DEBUG_EPHEMERAL) {
2714                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2715                            + " installer:" + ephemeralInstallerComponent);
2716                }
2717                mEphemeralResolverComponent = ephemeralResolverComponent;
2718                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2719                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2720                mEphemeralResolverConnection =
2721                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2722            } else {
2723                if (DEBUG_EPHEMERAL) {
2724                    final String missingComponent =
2725                            (ephemeralResolverComponent == null)
2726                            ? (ephemeralInstallerComponent == null)
2727                                    ? "resolver and installer"
2728                                    : "resolver"
2729                            : "installer";
2730                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2731                }
2732                mEphemeralResolverComponent = null;
2733                mEphemeralInstallerComponent = null;
2734                mEphemeralResolverConnection = null;
2735            }
2736
2737            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2738
2739            // Read and update the usage of dex files.
2740            // Do this at the end of PM init so that all the packages have their
2741            // data directory reconciled.
2742            // At this point we know the code paths of the packages, so we can validate
2743            // the disk file and build the internal cache.
2744            // The usage file is expected to be small so loading and verifying it
2745            // should take a fairly small time compare to the other activities (e.g. package
2746            // scanning).
2747            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2748            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2749            for (int userId : currentUserIds) {
2750                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2751            }
2752            mDexManager.load(userPackages);
2753        } // synchronized (mPackages)
2754        } // synchronized (mInstallLock)
2755
2756        // Now after opening every single application zip, make sure they
2757        // are all flushed.  Not really needed, but keeps things nice and
2758        // tidy.
2759        Runtime.getRuntime().gc();
2760
2761        // The initial scanning above does many calls into installd while
2762        // holding the mPackages lock, but we're mostly interested in yelling
2763        // once we have a booted system.
2764        mInstaller.setWarnIfHeld(mPackages);
2765
2766        // Expose private service for system components to use.
2767        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2768    }
2769
2770    @Override
2771    public boolean isFirstBoot() {
2772        return mFirstBoot;
2773    }
2774
2775    @Override
2776    public boolean isOnlyCoreApps() {
2777        return mOnlyCore;
2778    }
2779
2780    @Override
2781    public boolean isUpgrade() {
2782        return mIsUpgrade;
2783    }
2784
2785    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2786        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2787
2788        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2789                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2790                UserHandle.USER_SYSTEM);
2791        if (matches.size() == 1) {
2792            return matches.get(0).getComponentInfo().packageName;
2793        } else if (matches.size() == 0) {
2794            Log.e(TAG, "There should probably be a verifier, but, none were found");
2795            return null;
2796        }
2797        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2798    }
2799
2800    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2801        synchronized (mPackages) {
2802            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2803            if (libraryEntry == null) {
2804                throw new IllegalStateException("Missing required shared library:" + libraryName);
2805            }
2806            return libraryEntry.apk;
2807        }
2808    }
2809
2810    private @NonNull String getRequiredInstallerLPr() {
2811        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2812        intent.addCategory(Intent.CATEGORY_DEFAULT);
2813        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2814
2815        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2816                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2817                UserHandle.USER_SYSTEM);
2818        if (matches.size() == 1) {
2819            ResolveInfo resolveInfo = matches.get(0);
2820            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2821                throw new RuntimeException("The installer must be a privileged app");
2822            }
2823            return matches.get(0).getComponentInfo().packageName;
2824        } else {
2825            throw new RuntimeException("There must be exactly one installer; found " + matches);
2826        }
2827    }
2828
2829    private @NonNull String getRequiredUninstallerLPr() {
2830        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2831        intent.addCategory(Intent.CATEGORY_DEFAULT);
2832        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2833
2834        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2835                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2836                UserHandle.USER_SYSTEM);
2837        if (resolveInfo == null ||
2838                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2839            throw new RuntimeException("There must be exactly one uninstaller; found "
2840                    + resolveInfo);
2841        }
2842        return resolveInfo.getComponentInfo().packageName;
2843    }
2844
2845    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2846        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2847
2848        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2849                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2850                UserHandle.USER_SYSTEM);
2851        ResolveInfo best = null;
2852        final int N = matches.size();
2853        for (int i = 0; i < N; i++) {
2854            final ResolveInfo cur = matches.get(i);
2855            final String packageName = cur.getComponentInfo().packageName;
2856            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2857                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2858                continue;
2859            }
2860
2861            if (best == null || cur.priority > best.priority) {
2862                best = cur;
2863            }
2864        }
2865
2866        if (best != null) {
2867            return best.getComponentInfo().getComponentName();
2868        } else {
2869            throw new RuntimeException("There must be at least one intent filter verifier");
2870        }
2871    }
2872
2873    private @Nullable ComponentName getEphemeralResolverLPr() {
2874        final String[] packageArray =
2875                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2876        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2877            if (DEBUG_EPHEMERAL) {
2878                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2879            }
2880            return null;
2881        }
2882
2883        final int resolveFlags =
2884                MATCH_DIRECT_BOOT_AWARE
2885                | MATCH_DIRECT_BOOT_UNAWARE
2886                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2887        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2888        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2889                resolveFlags, UserHandle.USER_SYSTEM);
2890
2891        final int N = resolvers.size();
2892        if (N == 0) {
2893            if (DEBUG_EPHEMERAL) {
2894                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2895            }
2896            return null;
2897        }
2898
2899        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2900        for (int i = 0; i < N; i++) {
2901            final ResolveInfo info = resolvers.get(i);
2902
2903            if (info.serviceInfo == null) {
2904                continue;
2905            }
2906
2907            final String packageName = info.serviceInfo.packageName;
2908            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2909                if (DEBUG_EPHEMERAL) {
2910                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2911                            + " pkg: " + packageName + ", info:" + info);
2912                }
2913                continue;
2914            }
2915
2916            if (DEBUG_EPHEMERAL) {
2917                Slog.v(TAG, "Ephemeral resolver found;"
2918                        + " pkg: " + packageName + ", info:" + info);
2919            }
2920            return new ComponentName(packageName, info.serviceInfo.name);
2921        }
2922        if (DEBUG_EPHEMERAL) {
2923            Slog.v(TAG, "Ephemeral resolver NOT found");
2924        }
2925        return null;
2926    }
2927
2928    private @Nullable ComponentName getEphemeralInstallerLPr() {
2929        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2930        intent.addCategory(Intent.CATEGORY_DEFAULT);
2931        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2932
2933        final int resolveFlags =
2934                MATCH_DIRECT_BOOT_AWARE
2935                | MATCH_DIRECT_BOOT_UNAWARE
2936                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2937        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2938                resolveFlags, UserHandle.USER_SYSTEM);
2939        if (matches.size() == 0) {
2940            return null;
2941        } else if (matches.size() == 1) {
2942            return matches.get(0).getComponentInfo().getComponentName();
2943        } else {
2944            throw new RuntimeException(
2945                    "There must be at most one ephemeral installer; found " + matches);
2946        }
2947    }
2948
2949    private void primeDomainVerificationsLPw(int userId) {
2950        if (DEBUG_DOMAIN_VERIFICATION) {
2951            Slog.d(TAG, "Priming domain verifications in user " + userId);
2952        }
2953
2954        SystemConfig systemConfig = SystemConfig.getInstance();
2955        ArraySet<String> packages = systemConfig.getLinkedApps();
2956        ArraySet<String> domains = new ArraySet<String>();
2957
2958        for (String packageName : packages) {
2959            PackageParser.Package pkg = mPackages.get(packageName);
2960            if (pkg != null) {
2961                if (!pkg.isSystemApp()) {
2962                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2963                    continue;
2964                }
2965
2966                domains.clear();
2967                for (PackageParser.Activity a : pkg.activities) {
2968                    for (ActivityIntentInfo filter : a.intents) {
2969                        if (hasValidDomains(filter)) {
2970                            domains.addAll(filter.getHostsList());
2971                        }
2972                    }
2973                }
2974
2975                if (domains.size() > 0) {
2976                    if (DEBUG_DOMAIN_VERIFICATION) {
2977                        Slog.v(TAG, "      + " + packageName);
2978                    }
2979                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2980                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2981                    // and then 'always' in the per-user state actually used for intent resolution.
2982                    final IntentFilterVerificationInfo ivi;
2983                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2984                            new ArrayList<String>(domains));
2985                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2986                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2987                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2988                } else {
2989                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2990                            + "' does not handle web links");
2991                }
2992            } else {
2993                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2994            }
2995        }
2996
2997        scheduleWritePackageRestrictionsLocked(userId);
2998        scheduleWriteSettingsLocked();
2999    }
3000
3001    private void applyFactoryDefaultBrowserLPw(int userId) {
3002        // The default browser app's package name is stored in a string resource,
3003        // with a product-specific overlay used for vendor customization.
3004        String browserPkg = mContext.getResources().getString(
3005                com.android.internal.R.string.default_browser);
3006        if (!TextUtils.isEmpty(browserPkg)) {
3007            // non-empty string => required to be a known package
3008            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3009            if (ps == null) {
3010                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3011                browserPkg = null;
3012            } else {
3013                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3014            }
3015        }
3016
3017        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3018        // default.  If there's more than one, just leave everything alone.
3019        if (browserPkg == null) {
3020            calculateDefaultBrowserLPw(userId);
3021        }
3022    }
3023
3024    private void calculateDefaultBrowserLPw(int userId) {
3025        List<String> allBrowsers = resolveAllBrowserApps(userId);
3026        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3027        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3028    }
3029
3030    private List<String> resolveAllBrowserApps(int userId) {
3031        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3032        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3033                PackageManager.MATCH_ALL, userId);
3034
3035        final int count = list.size();
3036        List<String> result = new ArrayList<String>(count);
3037        for (int i=0; i<count; i++) {
3038            ResolveInfo info = list.get(i);
3039            if (info.activityInfo == null
3040                    || !info.handleAllWebDataURI
3041                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3042                    || result.contains(info.activityInfo.packageName)) {
3043                continue;
3044            }
3045            result.add(info.activityInfo.packageName);
3046        }
3047
3048        return result;
3049    }
3050
3051    private boolean packageIsBrowser(String packageName, int userId) {
3052        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3053                PackageManager.MATCH_ALL, userId);
3054        final int N = list.size();
3055        for (int i = 0; i < N; i++) {
3056            ResolveInfo info = list.get(i);
3057            if (packageName.equals(info.activityInfo.packageName)) {
3058                return true;
3059            }
3060        }
3061        return false;
3062    }
3063
3064    private void checkDefaultBrowser() {
3065        final int myUserId = UserHandle.myUserId();
3066        final String packageName = getDefaultBrowserPackageName(myUserId);
3067        if (packageName != null) {
3068            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3069            if (info == null) {
3070                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3071                synchronized (mPackages) {
3072                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3073                }
3074            }
3075        }
3076    }
3077
3078    @Override
3079    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3080            throws RemoteException {
3081        try {
3082            return super.onTransact(code, data, reply, flags);
3083        } catch (RuntimeException e) {
3084            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3085                Slog.wtf(TAG, "Package Manager Crash", e);
3086            }
3087            throw e;
3088        }
3089    }
3090
3091    static int[] appendInts(int[] cur, int[] add) {
3092        if (add == null) return cur;
3093        if (cur == null) return add;
3094        final int N = add.length;
3095        for (int i=0; i<N; i++) {
3096            cur = appendInt(cur, add[i]);
3097        }
3098        return cur;
3099    }
3100
3101    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3102        if (!sUserManager.exists(userId)) return null;
3103        if (ps == null) {
3104            return null;
3105        }
3106        final PackageParser.Package p = ps.pkg;
3107        if (p == null) {
3108            return null;
3109        }
3110
3111        final PermissionsState permissionsState = ps.getPermissionsState();
3112
3113        // Compute GIDs only if requested
3114        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3115                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3116        // Compute granted permissions only if package has requested permissions
3117        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3118                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3119        final PackageUserState state = ps.readUserState(userId);
3120
3121        return PackageParser.generatePackageInfo(p, gids, flags,
3122                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3123    }
3124
3125    @Override
3126    public void checkPackageStartable(String packageName, int userId) {
3127        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3128
3129        synchronized (mPackages) {
3130            final PackageSetting ps = mSettings.mPackages.get(packageName);
3131            if (ps == null) {
3132                throw new SecurityException("Package " + packageName + " was not found!");
3133            }
3134
3135            if (!ps.getInstalled(userId)) {
3136                throw new SecurityException(
3137                        "Package " + packageName + " was not installed for user " + userId + "!");
3138            }
3139
3140            if (mSafeMode && !ps.isSystem()) {
3141                throw new SecurityException("Package " + packageName + " not a system app!");
3142            }
3143
3144            if (mFrozenPackages.contains(packageName)) {
3145                throw new SecurityException("Package " + packageName + " is currently frozen!");
3146            }
3147
3148            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3149                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3150                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3151            }
3152        }
3153    }
3154
3155    @Override
3156    public boolean isPackageAvailable(String packageName, int userId) {
3157        if (!sUserManager.exists(userId)) return false;
3158        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3159                false /* requireFullPermission */, false /* checkShell */, "is package available");
3160        synchronized (mPackages) {
3161            PackageParser.Package p = mPackages.get(packageName);
3162            if (p != null) {
3163                final PackageSetting ps = (PackageSetting) p.mExtras;
3164                if (ps != null) {
3165                    final PackageUserState state = ps.readUserState(userId);
3166                    if (state != null) {
3167                        return PackageParser.isAvailable(state);
3168                    }
3169                }
3170            }
3171        }
3172        return false;
3173    }
3174
3175    @Override
3176    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3177        if (!sUserManager.exists(userId)) return null;
3178        flags = updateFlagsForPackage(flags, userId, packageName);
3179        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3180                false /* requireFullPermission */, false /* checkShell */, "get package info");
3181
3182        // reader
3183        synchronized (mPackages) {
3184            // Normalize package name to hanlde renamed packages
3185            packageName = normalizePackageNameLPr(packageName);
3186
3187            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3188            PackageParser.Package p = null;
3189            if (matchFactoryOnly) {
3190                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3191                if (ps != null) {
3192                    return generatePackageInfo(ps, flags, userId);
3193                }
3194            }
3195            if (p == null) {
3196                p = mPackages.get(packageName);
3197                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3198                    return null;
3199                }
3200            }
3201            if (DEBUG_PACKAGE_INFO)
3202                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3203            if (p != null) {
3204                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3205            }
3206            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3207                final PackageSetting ps = mSettings.mPackages.get(packageName);
3208                return generatePackageInfo(ps, flags, userId);
3209            }
3210        }
3211        return null;
3212    }
3213
3214    @Override
3215    public String[] currentToCanonicalPackageNames(String[] names) {
3216        String[] out = new String[names.length];
3217        // reader
3218        synchronized (mPackages) {
3219            for (int i=names.length-1; i>=0; i--) {
3220                PackageSetting ps = mSettings.mPackages.get(names[i]);
3221                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3222            }
3223        }
3224        return out;
3225    }
3226
3227    @Override
3228    public String[] canonicalToCurrentPackageNames(String[] names) {
3229        String[] out = new String[names.length];
3230        // reader
3231        synchronized (mPackages) {
3232            for (int i=names.length-1; i>=0; i--) {
3233                String cur = mSettings.mRenamedPackages.get(names[i]);
3234                out[i] = cur != null ? cur : names[i];
3235            }
3236        }
3237        return out;
3238    }
3239
3240    @Override
3241    public int getPackageUid(String packageName, int flags, int userId) {
3242        if (!sUserManager.exists(userId)) return -1;
3243        flags = updateFlagsForPackage(flags, userId, packageName);
3244        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3245                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3246
3247        // reader
3248        synchronized (mPackages) {
3249            final PackageParser.Package p = mPackages.get(packageName);
3250            if (p != null && p.isMatch(flags)) {
3251                return UserHandle.getUid(userId, p.applicationInfo.uid);
3252            }
3253            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3254                final PackageSetting ps = mSettings.mPackages.get(packageName);
3255                if (ps != null && ps.isMatch(flags)) {
3256                    return UserHandle.getUid(userId, ps.appId);
3257                }
3258            }
3259        }
3260
3261        return -1;
3262    }
3263
3264    @Override
3265    public int[] getPackageGids(String packageName, int flags, int userId) {
3266        if (!sUserManager.exists(userId)) return null;
3267        flags = updateFlagsForPackage(flags, userId, packageName);
3268        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3269                false /* requireFullPermission */, false /* checkShell */,
3270                "getPackageGids");
3271
3272        // reader
3273        synchronized (mPackages) {
3274            final PackageParser.Package p = mPackages.get(packageName);
3275            if (p != null && p.isMatch(flags)) {
3276                PackageSetting ps = (PackageSetting) p.mExtras;
3277                return ps.getPermissionsState().computeGids(userId);
3278            }
3279            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3280                final PackageSetting ps = mSettings.mPackages.get(packageName);
3281                if (ps != null && ps.isMatch(flags)) {
3282                    return ps.getPermissionsState().computeGids(userId);
3283                }
3284            }
3285        }
3286
3287        return null;
3288    }
3289
3290    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3291        if (bp.perm != null) {
3292            return PackageParser.generatePermissionInfo(bp.perm, flags);
3293        }
3294        PermissionInfo pi = new PermissionInfo();
3295        pi.name = bp.name;
3296        pi.packageName = bp.sourcePackage;
3297        pi.nonLocalizedLabel = bp.name;
3298        pi.protectionLevel = bp.protectionLevel;
3299        return pi;
3300    }
3301
3302    @Override
3303    public PermissionInfo getPermissionInfo(String name, int flags) {
3304        // reader
3305        synchronized (mPackages) {
3306            final BasePermission p = mSettings.mPermissions.get(name);
3307            if (p != null) {
3308                return generatePermissionInfo(p, flags);
3309            }
3310            return null;
3311        }
3312    }
3313
3314    @Override
3315    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3316            int flags) {
3317        // reader
3318        synchronized (mPackages) {
3319            if (group != null && !mPermissionGroups.containsKey(group)) {
3320                // This is thrown as NameNotFoundException
3321                return null;
3322            }
3323
3324            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3325            for (BasePermission p : mSettings.mPermissions.values()) {
3326                if (group == null) {
3327                    if (p.perm == null || p.perm.info.group == null) {
3328                        out.add(generatePermissionInfo(p, flags));
3329                    }
3330                } else {
3331                    if (p.perm != null && group.equals(p.perm.info.group)) {
3332                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3333                    }
3334                }
3335            }
3336            return new ParceledListSlice<>(out);
3337        }
3338    }
3339
3340    @Override
3341    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3342        // reader
3343        synchronized (mPackages) {
3344            return PackageParser.generatePermissionGroupInfo(
3345                    mPermissionGroups.get(name), flags);
3346        }
3347    }
3348
3349    @Override
3350    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3351        // reader
3352        synchronized (mPackages) {
3353            final int N = mPermissionGroups.size();
3354            ArrayList<PermissionGroupInfo> out
3355                    = new ArrayList<PermissionGroupInfo>(N);
3356            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3357                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3358            }
3359            return new ParceledListSlice<>(out);
3360        }
3361    }
3362
3363    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3364            int userId) {
3365        if (!sUserManager.exists(userId)) return null;
3366        PackageSetting ps = mSettings.mPackages.get(packageName);
3367        if (ps != null) {
3368            if (ps.pkg == null) {
3369                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3370                if (pInfo != null) {
3371                    return pInfo.applicationInfo;
3372                }
3373                return null;
3374            }
3375            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3376                    ps.readUserState(userId), userId);
3377        }
3378        return null;
3379    }
3380
3381    @Override
3382    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3383        if (!sUserManager.exists(userId)) return null;
3384        flags = updateFlagsForApplication(flags, userId, packageName);
3385        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3386                false /* requireFullPermission */, false /* checkShell */, "get application info");
3387
3388        // writer
3389        synchronized (mPackages) {
3390            // Normalize package name to hanlde renamed packages
3391            packageName = normalizePackageNameLPr(packageName);
3392
3393            PackageParser.Package p = mPackages.get(packageName);
3394            if (DEBUG_PACKAGE_INFO) Log.v(
3395                    TAG, "getApplicationInfo " + packageName
3396                    + ": " + p);
3397            if (p != null) {
3398                PackageSetting ps = mSettings.mPackages.get(packageName);
3399                if (ps == null) return null;
3400                // Note: isEnabledLP() does not apply here - always return info
3401                return PackageParser.generateApplicationInfo(
3402                        p, flags, ps.readUserState(userId), userId);
3403            }
3404            if ("android".equals(packageName)||"system".equals(packageName)) {
3405                return mAndroidApplication;
3406            }
3407            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3408                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3409            }
3410        }
3411        return null;
3412    }
3413
3414    private String normalizePackageNameLPr(String packageName) {
3415        String normalizedPackageName = mSettings.mRenamedPackages.get(packageName);
3416        return normalizedPackageName != null ? normalizedPackageName : packageName;
3417    }
3418
3419    @Override
3420    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3421            final IPackageDataObserver observer) {
3422        mContext.enforceCallingOrSelfPermission(
3423                android.Manifest.permission.CLEAR_APP_CACHE, null);
3424        // Queue up an async operation since clearing cache may take a little while.
3425        mHandler.post(new Runnable() {
3426            public void run() {
3427                mHandler.removeCallbacks(this);
3428                boolean success = true;
3429                synchronized (mInstallLock) {
3430                    try {
3431                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3432                    } catch (InstallerException e) {
3433                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3434                        success = false;
3435                    }
3436                }
3437                if (observer != null) {
3438                    try {
3439                        observer.onRemoveCompleted(null, success);
3440                    } catch (RemoteException e) {
3441                        Slog.w(TAG, "RemoveException when invoking call back");
3442                    }
3443                }
3444            }
3445        });
3446    }
3447
3448    @Override
3449    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3450            final IntentSender pi) {
3451        mContext.enforceCallingOrSelfPermission(
3452                android.Manifest.permission.CLEAR_APP_CACHE, null);
3453        // Queue up an async operation since clearing cache may take a little while.
3454        mHandler.post(new Runnable() {
3455            public void run() {
3456                mHandler.removeCallbacks(this);
3457                boolean success = true;
3458                synchronized (mInstallLock) {
3459                    try {
3460                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3461                    } catch (InstallerException e) {
3462                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3463                        success = false;
3464                    }
3465                }
3466                if(pi != null) {
3467                    try {
3468                        // Callback via pending intent
3469                        int code = success ? 1 : 0;
3470                        pi.sendIntent(null, code, null,
3471                                null, null);
3472                    } catch (SendIntentException e1) {
3473                        Slog.i(TAG, "Failed to send pending intent");
3474                    }
3475                }
3476            }
3477        });
3478    }
3479
3480    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3481        synchronized (mInstallLock) {
3482            try {
3483                mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3484            } catch (InstallerException e) {
3485                throw new IOException("Failed to free enough space", e);
3486            }
3487        }
3488    }
3489
3490    /**
3491     * Update given flags based on encryption status of current user.
3492     */
3493    private int updateFlags(int flags, int userId) {
3494        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3495                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3496            // Caller expressed an explicit opinion about what encryption
3497            // aware/unaware components they want to see, so fall through and
3498            // give them what they want
3499        } else {
3500            // Caller expressed no opinion, so match based on user state
3501            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3502                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3503            } else {
3504                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3505            }
3506        }
3507        return flags;
3508    }
3509
3510    private UserManagerInternal getUserManagerInternal() {
3511        if (mUserManagerInternal == null) {
3512            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3513        }
3514        return mUserManagerInternal;
3515    }
3516
3517    /**
3518     * Update given flags when being used to request {@link PackageInfo}.
3519     */
3520    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3521        boolean triaged = true;
3522        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3523                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3524            // Caller is asking for component details, so they'd better be
3525            // asking for specific encryption matching behavior, or be triaged
3526            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3527                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3528                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3529                triaged = false;
3530            }
3531        }
3532        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3533                | PackageManager.MATCH_SYSTEM_ONLY
3534                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3535            triaged = false;
3536        }
3537        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3538            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3539                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3540        }
3541        return updateFlags(flags, userId);
3542    }
3543
3544    /**
3545     * Update given flags when being used to request {@link ApplicationInfo}.
3546     */
3547    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3548        return updateFlagsForPackage(flags, userId, cookie);
3549    }
3550
3551    /**
3552     * Update given flags when being used to request {@link ComponentInfo}.
3553     */
3554    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3555        if (cookie instanceof Intent) {
3556            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3557                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3558            }
3559        }
3560
3561        boolean triaged = true;
3562        // Caller is asking for component details, so they'd better be
3563        // asking for specific encryption matching behavior, or be triaged
3564        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3565                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3566                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3567            triaged = false;
3568        }
3569        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3570            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3571                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3572        }
3573
3574        return updateFlags(flags, userId);
3575    }
3576
3577    /**
3578     * Update given flags when being used to request {@link ResolveInfo}.
3579     */
3580    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3581        // Safe mode means we shouldn't match any third-party components
3582        if (mSafeMode) {
3583            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3584        }
3585
3586        return updateFlagsForComponent(flags, userId, cookie);
3587    }
3588
3589    @Override
3590    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3591        if (!sUserManager.exists(userId)) return null;
3592        flags = updateFlagsForComponent(flags, userId, component);
3593        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3594                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3595        synchronized (mPackages) {
3596            PackageParser.Activity a = mActivities.mActivities.get(component);
3597
3598            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3599            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3600                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3601                if (ps == null) return null;
3602                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3603                        userId);
3604            }
3605            if (mResolveComponentName.equals(component)) {
3606                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3607                        new PackageUserState(), userId);
3608            }
3609        }
3610        return null;
3611    }
3612
3613    @Override
3614    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3615            String resolvedType) {
3616        synchronized (mPackages) {
3617            if (component.equals(mResolveComponentName)) {
3618                // The resolver supports EVERYTHING!
3619                return true;
3620            }
3621            PackageParser.Activity a = mActivities.mActivities.get(component);
3622            if (a == null) {
3623                return false;
3624            }
3625            for (int i=0; i<a.intents.size(); i++) {
3626                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3627                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3628                    return true;
3629                }
3630            }
3631            return false;
3632        }
3633    }
3634
3635    @Override
3636    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3637        if (!sUserManager.exists(userId)) return null;
3638        flags = updateFlagsForComponent(flags, userId, component);
3639        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3640                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3641        synchronized (mPackages) {
3642            PackageParser.Activity a = mReceivers.mActivities.get(component);
3643            if (DEBUG_PACKAGE_INFO) Log.v(
3644                TAG, "getReceiverInfo " + component + ": " + a);
3645            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3646                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3647                if (ps == null) return null;
3648                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3649                        userId);
3650            }
3651        }
3652        return null;
3653    }
3654
3655    @Override
3656    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3657        if (!sUserManager.exists(userId)) return null;
3658        flags = updateFlagsForComponent(flags, userId, component);
3659        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3660                false /* requireFullPermission */, false /* checkShell */, "get service info");
3661        synchronized (mPackages) {
3662            PackageParser.Service s = mServices.mServices.get(component);
3663            if (DEBUG_PACKAGE_INFO) Log.v(
3664                TAG, "getServiceInfo " + component + ": " + s);
3665            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3666                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3667                if (ps == null) return null;
3668                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3669                        userId);
3670            }
3671        }
3672        return null;
3673    }
3674
3675    @Override
3676    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3677        if (!sUserManager.exists(userId)) return null;
3678        flags = updateFlagsForComponent(flags, userId, component);
3679        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3680                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3681        synchronized (mPackages) {
3682            PackageParser.Provider p = mProviders.mProviders.get(component);
3683            if (DEBUG_PACKAGE_INFO) Log.v(
3684                TAG, "getProviderInfo " + component + ": " + p);
3685            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3686                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3687                if (ps == null) return null;
3688                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3689                        userId);
3690            }
3691        }
3692        return null;
3693    }
3694
3695    @Override
3696    public String[] getSystemSharedLibraryNames() {
3697        Set<String> libSet;
3698        synchronized (mPackages) {
3699            libSet = mSharedLibraries.keySet();
3700            int size = libSet.size();
3701            if (size > 0) {
3702                String[] libs = new String[size];
3703                libSet.toArray(libs);
3704                return libs;
3705            }
3706        }
3707        return null;
3708    }
3709
3710    @Override
3711    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3712        synchronized (mPackages) {
3713            return mServicesSystemSharedLibraryPackageName;
3714        }
3715    }
3716
3717    @Override
3718    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3719        synchronized (mPackages) {
3720            return mSharedSystemSharedLibraryPackageName;
3721        }
3722    }
3723
3724    @Override
3725    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3726        synchronized (mPackages) {
3727            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3728
3729            final FeatureInfo fi = new FeatureInfo();
3730            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3731                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3732            res.add(fi);
3733
3734            return new ParceledListSlice<>(res);
3735        }
3736    }
3737
3738    @Override
3739    public boolean hasSystemFeature(String name, int version) {
3740        synchronized (mPackages) {
3741            final FeatureInfo feat = mAvailableFeatures.get(name);
3742            if (feat == null) {
3743                return false;
3744            } else {
3745                return feat.version >= version;
3746            }
3747        }
3748    }
3749
3750    @Override
3751    public int checkPermission(String permName, String pkgName, int userId) {
3752        if (!sUserManager.exists(userId)) {
3753            return PackageManager.PERMISSION_DENIED;
3754        }
3755
3756        synchronized (mPackages) {
3757            final PackageParser.Package p = mPackages.get(pkgName);
3758            if (p != null && p.mExtras != null) {
3759                final PackageSetting ps = (PackageSetting) p.mExtras;
3760                final PermissionsState permissionsState = ps.getPermissionsState();
3761                if (permissionsState.hasPermission(permName, userId)) {
3762                    return PackageManager.PERMISSION_GRANTED;
3763                }
3764                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3765                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3766                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3767                    return PackageManager.PERMISSION_GRANTED;
3768                }
3769            }
3770        }
3771
3772        return PackageManager.PERMISSION_DENIED;
3773    }
3774
3775    @Override
3776    public int checkUidPermission(String permName, int uid) {
3777        final int userId = UserHandle.getUserId(uid);
3778
3779        if (!sUserManager.exists(userId)) {
3780            return PackageManager.PERMISSION_DENIED;
3781        }
3782
3783        synchronized (mPackages) {
3784            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3785            if (obj != null) {
3786                final SettingBase ps = (SettingBase) obj;
3787                final PermissionsState permissionsState = ps.getPermissionsState();
3788                if (permissionsState.hasPermission(permName, userId)) {
3789                    return PackageManager.PERMISSION_GRANTED;
3790                }
3791                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3792                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3793                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3794                    return PackageManager.PERMISSION_GRANTED;
3795                }
3796            } else {
3797                ArraySet<String> perms = mSystemPermissions.get(uid);
3798                if (perms != null) {
3799                    if (perms.contains(permName)) {
3800                        return PackageManager.PERMISSION_GRANTED;
3801                    }
3802                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3803                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3804                        return PackageManager.PERMISSION_GRANTED;
3805                    }
3806                }
3807            }
3808        }
3809
3810        return PackageManager.PERMISSION_DENIED;
3811    }
3812
3813    @Override
3814    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3815        if (UserHandle.getCallingUserId() != userId) {
3816            mContext.enforceCallingPermission(
3817                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3818                    "isPermissionRevokedByPolicy for user " + userId);
3819        }
3820
3821        if (checkPermission(permission, packageName, userId)
3822                == PackageManager.PERMISSION_GRANTED) {
3823            return false;
3824        }
3825
3826        final long identity = Binder.clearCallingIdentity();
3827        try {
3828            final int flags = getPermissionFlags(permission, packageName, userId);
3829            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3830        } finally {
3831            Binder.restoreCallingIdentity(identity);
3832        }
3833    }
3834
3835    @Override
3836    public String getPermissionControllerPackageName() {
3837        synchronized (mPackages) {
3838            return mRequiredInstallerPackage;
3839        }
3840    }
3841
3842    /**
3843     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3844     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3845     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3846     * @param message the message to log on security exception
3847     */
3848    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3849            boolean checkShell, String message) {
3850        if (userId < 0) {
3851            throw new IllegalArgumentException("Invalid userId " + userId);
3852        }
3853        if (checkShell) {
3854            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3855        }
3856        if (userId == UserHandle.getUserId(callingUid)) return;
3857        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3858            if (requireFullPermission) {
3859                mContext.enforceCallingOrSelfPermission(
3860                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3861            } else {
3862                try {
3863                    mContext.enforceCallingOrSelfPermission(
3864                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3865                } catch (SecurityException se) {
3866                    mContext.enforceCallingOrSelfPermission(
3867                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3868                }
3869            }
3870        }
3871    }
3872
3873    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3874        if (callingUid == Process.SHELL_UID) {
3875            if (userHandle >= 0
3876                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3877                throw new SecurityException("Shell does not have permission to access user "
3878                        + userHandle);
3879            } else if (userHandle < 0) {
3880                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3881                        + Debug.getCallers(3));
3882            }
3883        }
3884    }
3885
3886    private BasePermission findPermissionTreeLP(String permName) {
3887        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3888            if (permName.startsWith(bp.name) &&
3889                    permName.length() > bp.name.length() &&
3890                    permName.charAt(bp.name.length()) == '.') {
3891                return bp;
3892            }
3893        }
3894        return null;
3895    }
3896
3897    private BasePermission checkPermissionTreeLP(String permName) {
3898        if (permName != null) {
3899            BasePermission bp = findPermissionTreeLP(permName);
3900            if (bp != null) {
3901                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3902                    return bp;
3903                }
3904                throw new SecurityException("Calling uid "
3905                        + Binder.getCallingUid()
3906                        + " is not allowed to add to permission tree "
3907                        + bp.name + " owned by uid " + bp.uid);
3908            }
3909        }
3910        throw new SecurityException("No permission tree found for " + permName);
3911    }
3912
3913    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3914        if (s1 == null) {
3915            return s2 == null;
3916        }
3917        if (s2 == null) {
3918            return false;
3919        }
3920        if (s1.getClass() != s2.getClass()) {
3921            return false;
3922        }
3923        return s1.equals(s2);
3924    }
3925
3926    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3927        if (pi1.icon != pi2.icon) return false;
3928        if (pi1.logo != pi2.logo) return false;
3929        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3930        if (!compareStrings(pi1.name, pi2.name)) return false;
3931        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3932        // We'll take care of setting this one.
3933        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3934        // These are not currently stored in settings.
3935        //if (!compareStrings(pi1.group, pi2.group)) return false;
3936        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3937        //if (pi1.labelRes != pi2.labelRes) return false;
3938        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3939        return true;
3940    }
3941
3942    int permissionInfoFootprint(PermissionInfo info) {
3943        int size = info.name.length();
3944        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3945        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3946        return size;
3947    }
3948
3949    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3950        int size = 0;
3951        for (BasePermission perm : mSettings.mPermissions.values()) {
3952            if (perm.uid == tree.uid) {
3953                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3954            }
3955        }
3956        return size;
3957    }
3958
3959    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3960        // We calculate the max size of permissions defined by this uid and throw
3961        // if that plus the size of 'info' would exceed our stated maximum.
3962        if (tree.uid != Process.SYSTEM_UID) {
3963            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3964            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3965                throw new SecurityException("Permission tree size cap exceeded");
3966            }
3967        }
3968    }
3969
3970    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3971        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3972            throw new SecurityException("Label must be specified in permission");
3973        }
3974        BasePermission tree = checkPermissionTreeLP(info.name);
3975        BasePermission bp = mSettings.mPermissions.get(info.name);
3976        boolean added = bp == null;
3977        boolean changed = true;
3978        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3979        if (added) {
3980            enforcePermissionCapLocked(info, tree);
3981            bp = new BasePermission(info.name, tree.sourcePackage,
3982                    BasePermission.TYPE_DYNAMIC);
3983        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3984            throw new SecurityException(
3985                    "Not allowed to modify non-dynamic permission "
3986                    + info.name);
3987        } else {
3988            if (bp.protectionLevel == fixedLevel
3989                    && bp.perm.owner.equals(tree.perm.owner)
3990                    && bp.uid == tree.uid
3991                    && comparePermissionInfos(bp.perm.info, info)) {
3992                changed = false;
3993            }
3994        }
3995        bp.protectionLevel = fixedLevel;
3996        info = new PermissionInfo(info);
3997        info.protectionLevel = fixedLevel;
3998        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3999        bp.perm.info.packageName = tree.perm.info.packageName;
4000        bp.uid = tree.uid;
4001        if (added) {
4002            mSettings.mPermissions.put(info.name, bp);
4003        }
4004        if (changed) {
4005            if (!async) {
4006                mSettings.writeLPr();
4007            } else {
4008                scheduleWriteSettingsLocked();
4009            }
4010        }
4011        return added;
4012    }
4013
4014    @Override
4015    public boolean addPermission(PermissionInfo info) {
4016        synchronized (mPackages) {
4017            return addPermissionLocked(info, false);
4018        }
4019    }
4020
4021    @Override
4022    public boolean addPermissionAsync(PermissionInfo info) {
4023        synchronized (mPackages) {
4024            return addPermissionLocked(info, true);
4025        }
4026    }
4027
4028    @Override
4029    public void removePermission(String name) {
4030        synchronized (mPackages) {
4031            checkPermissionTreeLP(name);
4032            BasePermission bp = mSettings.mPermissions.get(name);
4033            if (bp != null) {
4034                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4035                    throw new SecurityException(
4036                            "Not allowed to modify non-dynamic permission "
4037                            + name);
4038                }
4039                mSettings.mPermissions.remove(name);
4040                mSettings.writeLPr();
4041            }
4042        }
4043    }
4044
4045    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4046            BasePermission bp) {
4047        int index = pkg.requestedPermissions.indexOf(bp.name);
4048        if (index == -1) {
4049            throw new SecurityException("Package " + pkg.packageName
4050                    + " has not requested permission " + bp.name);
4051        }
4052        if (!bp.isRuntime() && !bp.isDevelopment()) {
4053            throw new SecurityException("Permission " + bp.name
4054                    + " is not a changeable permission type");
4055        }
4056    }
4057
4058    @Override
4059    public void grantRuntimePermission(String packageName, String name, final int userId) {
4060        if (!sUserManager.exists(userId)) {
4061            Log.e(TAG, "No such user:" + userId);
4062            return;
4063        }
4064
4065        mContext.enforceCallingOrSelfPermission(
4066                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4067                "grantRuntimePermission");
4068
4069        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4070                true /* requireFullPermission */, true /* checkShell */,
4071                "grantRuntimePermission");
4072
4073        final int uid;
4074        final SettingBase sb;
4075
4076        synchronized (mPackages) {
4077            final PackageParser.Package pkg = mPackages.get(packageName);
4078            if (pkg == null) {
4079                throw new IllegalArgumentException("Unknown package: " + packageName);
4080            }
4081
4082            final BasePermission bp = mSettings.mPermissions.get(name);
4083            if (bp == null) {
4084                throw new IllegalArgumentException("Unknown permission: " + name);
4085            }
4086
4087            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4088
4089            // If a permission review is required for legacy apps we represent
4090            // their permissions as always granted runtime ones since we need
4091            // to keep the review required permission flag per user while an
4092            // install permission's state is shared across all users.
4093            if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
4094                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4095                    && bp.isRuntime()) {
4096                return;
4097            }
4098
4099            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4100            sb = (SettingBase) pkg.mExtras;
4101            if (sb == null) {
4102                throw new IllegalArgumentException("Unknown package: " + packageName);
4103            }
4104
4105            final PermissionsState permissionsState = sb.getPermissionsState();
4106
4107            final int flags = permissionsState.getPermissionFlags(name, userId);
4108            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4109                throw new SecurityException("Cannot grant system fixed permission "
4110                        + name + " for package " + packageName);
4111            }
4112
4113            if (bp.isDevelopment()) {
4114                // Development permissions must be handled specially, since they are not
4115                // normal runtime permissions.  For now they apply to all users.
4116                if (permissionsState.grantInstallPermission(bp) !=
4117                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4118                    scheduleWriteSettingsLocked();
4119                }
4120                return;
4121            }
4122
4123            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4124                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4125                return;
4126            }
4127
4128            final int result = permissionsState.grantRuntimePermission(bp, userId);
4129            switch (result) {
4130                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4131                    return;
4132                }
4133
4134                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4135                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4136                    mHandler.post(new Runnable() {
4137                        @Override
4138                        public void run() {
4139                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4140                        }
4141                    });
4142                }
4143                break;
4144            }
4145
4146            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4147
4148            // Not critical if that is lost - app has to request again.
4149            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4150        }
4151
4152        // Only need to do this if user is initialized. Otherwise it's a new user
4153        // and there are no processes running as the user yet and there's no need
4154        // to make an expensive call to remount processes for the changed permissions.
4155        if (READ_EXTERNAL_STORAGE.equals(name)
4156                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4157            final long token = Binder.clearCallingIdentity();
4158            try {
4159                if (sUserManager.isInitialized(userId)) {
4160                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4161                            MountServiceInternal.class);
4162                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4163                }
4164            } finally {
4165                Binder.restoreCallingIdentity(token);
4166            }
4167        }
4168    }
4169
4170    @Override
4171    public void revokeRuntimePermission(String packageName, String name, int userId) {
4172        if (!sUserManager.exists(userId)) {
4173            Log.e(TAG, "No such user:" + userId);
4174            return;
4175        }
4176
4177        mContext.enforceCallingOrSelfPermission(
4178                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4179                "revokeRuntimePermission");
4180
4181        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4182                true /* requireFullPermission */, true /* checkShell */,
4183                "revokeRuntimePermission");
4184
4185        final int appId;
4186
4187        synchronized (mPackages) {
4188            final PackageParser.Package pkg = mPackages.get(packageName);
4189            if (pkg == null) {
4190                throw new IllegalArgumentException("Unknown package: " + packageName);
4191            }
4192
4193            final BasePermission bp = mSettings.mPermissions.get(name);
4194            if (bp == null) {
4195                throw new IllegalArgumentException("Unknown permission: " + name);
4196            }
4197
4198            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4199
4200            // If a permission review is required for legacy apps we represent
4201            // their permissions as always granted runtime ones since we need
4202            // to keep the review required permission flag per user while an
4203            // install permission's state is shared across all users.
4204            if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
4205                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4206                    && bp.isRuntime()) {
4207                return;
4208            }
4209
4210            SettingBase sb = (SettingBase) pkg.mExtras;
4211            if (sb == null) {
4212                throw new IllegalArgumentException("Unknown package: " + packageName);
4213            }
4214
4215            final PermissionsState permissionsState = sb.getPermissionsState();
4216
4217            final int flags = permissionsState.getPermissionFlags(name, userId);
4218            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4219                throw new SecurityException("Cannot revoke system fixed permission "
4220                        + name + " for package " + packageName);
4221            }
4222
4223            if (bp.isDevelopment()) {
4224                // Development permissions must be handled specially, since they are not
4225                // normal runtime permissions.  For now they apply to all users.
4226                if (permissionsState.revokeInstallPermission(bp) !=
4227                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4228                    scheduleWriteSettingsLocked();
4229                }
4230                return;
4231            }
4232
4233            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4234                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4235                return;
4236            }
4237
4238            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4239
4240            // Critical, after this call app should never have the permission.
4241            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4242
4243            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4244        }
4245
4246        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4247    }
4248
4249    @Override
4250    public void resetRuntimePermissions() {
4251        mContext.enforceCallingOrSelfPermission(
4252                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4253                "revokeRuntimePermission");
4254
4255        int callingUid = Binder.getCallingUid();
4256        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4257            mContext.enforceCallingOrSelfPermission(
4258                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4259                    "resetRuntimePermissions");
4260        }
4261
4262        synchronized (mPackages) {
4263            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4264            for (int userId : UserManagerService.getInstance().getUserIds()) {
4265                final int packageCount = mPackages.size();
4266                for (int i = 0; i < packageCount; i++) {
4267                    PackageParser.Package pkg = mPackages.valueAt(i);
4268                    if (!(pkg.mExtras instanceof PackageSetting)) {
4269                        continue;
4270                    }
4271                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4272                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4273                }
4274            }
4275        }
4276    }
4277
4278    @Override
4279    public int getPermissionFlags(String name, String packageName, int userId) {
4280        if (!sUserManager.exists(userId)) {
4281            return 0;
4282        }
4283
4284        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4285
4286        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4287                true /* requireFullPermission */, false /* checkShell */,
4288                "getPermissionFlags");
4289
4290        synchronized (mPackages) {
4291            final PackageParser.Package pkg = mPackages.get(packageName);
4292            if (pkg == null) {
4293                return 0;
4294            }
4295
4296            final BasePermission bp = mSettings.mPermissions.get(name);
4297            if (bp == null) {
4298                return 0;
4299            }
4300
4301            SettingBase sb = (SettingBase) pkg.mExtras;
4302            if (sb == null) {
4303                return 0;
4304            }
4305
4306            PermissionsState permissionsState = sb.getPermissionsState();
4307            return permissionsState.getPermissionFlags(name, userId);
4308        }
4309    }
4310
4311    @Override
4312    public void updatePermissionFlags(String name, String packageName, int flagMask,
4313            int flagValues, int userId) {
4314        if (!sUserManager.exists(userId)) {
4315            return;
4316        }
4317
4318        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4319
4320        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4321                true /* requireFullPermission */, true /* checkShell */,
4322                "updatePermissionFlags");
4323
4324        // Only the system can change these flags and nothing else.
4325        if (getCallingUid() != Process.SYSTEM_UID) {
4326            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4327            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4328            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4329            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4330            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4331        }
4332
4333        synchronized (mPackages) {
4334            final PackageParser.Package pkg = mPackages.get(packageName);
4335            if (pkg == null) {
4336                throw new IllegalArgumentException("Unknown package: " + packageName);
4337            }
4338
4339            final BasePermission bp = mSettings.mPermissions.get(name);
4340            if (bp == null) {
4341                throw new IllegalArgumentException("Unknown permission: " + name);
4342            }
4343
4344            SettingBase sb = (SettingBase) pkg.mExtras;
4345            if (sb == null) {
4346                throw new IllegalArgumentException("Unknown package: " + packageName);
4347            }
4348
4349            PermissionsState permissionsState = sb.getPermissionsState();
4350
4351            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4352
4353            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4354                // Install and runtime permissions are stored in different places,
4355                // so figure out what permission changed and persist the change.
4356                if (permissionsState.getInstallPermissionState(name) != null) {
4357                    scheduleWriteSettingsLocked();
4358                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4359                        || hadState) {
4360                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4361                }
4362            }
4363        }
4364    }
4365
4366    /**
4367     * Update the permission flags for all packages and runtime permissions of a user in order
4368     * to allow device or profile owner to remove POLICY_FIXED.
4369     */
4370    @Override
4371    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4372        if (!sUserManager.exists(userId)) {
4373            return;
4374        }
4375
4376        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4377
4378        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4379                true /* requireFullPermission */, true /* checkShell */,
4380                "updatePermissionFlagsForAllApps");
4381
4382        // Only the system can change system fixed flags.
4383        if (getCallingUid() != Process.SYSTEM_UID) {
4384            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4385            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4386        }
4387
4388        synchronized (mPackages) {
4389            boolean changed = false;
4390            final int packageCount = mPackages.size();
4391            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4392                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4393                SettingBase sb = (SettingBase) pkg.mExtras;
4394                if (sb == null) {
4395                    continue;
4396                }
4397                PermissionsState permissionsState = sb.getPermissionsState();
4398                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4399                        userId, flagMask, flagValues);
4400            }
4401            if (changed) {
4402                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4403            }
4404        }
4405    }
4406
4407    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4408        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4409                != PackageManager.PERMISSION_GRANTED
4410            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4411                != PackageManager.PERMISSION_GRANTED) {
4412            throw new SecurityException(message + " requires "
4413                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4414                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4415        }
4416    }
4417
4418    @Override
4419    public boolean shouldShowRequestPermissionRationale(String permissionName,
4420            String packageName, int userId) {
4421        if (UserHandle.getCallingUserId() != userId) {
4422            mContext.enforceCallingPermission(
4423                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4424                    "canShowRequestPermissionRationale for user " + userId);
4425        }
4426
4427        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4428        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4429            return false;
4430        }
4431
4432        if (checkPermission(permissionName, packageName, userId)
4433                == PackageManager.PERMISSION_GRANTED) {
4434            return false;
4435        }
4436
4437        final int flags;
4438
4439        final long identity = Binder.clearCallingIdentity();
4440        try {
4441            flags = getPermissionFlags(permissionName,
4442                    packageName, userId);
4443        } finally {
4444            Binder.restoreCallingIdentity(identity);
4445        }
4446
4447        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4448                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4449                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4450
4451        if ((flags & fixedFlags) != 0) {
4452            return false;
4453        }
4454
4455        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4456    }
4457
4458    @Override
4459    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4460        mContext.enforceCallingOrSelfPermission(
4461                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4462                "addOnPermissionsChangeListener");
4463
4464        synchronized (mPackages) {
4465            mOnPermissionChangeListeners.addListenerLocked(listener);
4466        }
4467    }
4468
4469    @Override
4470    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4471        synchronized (mPackages) {
4472            mOnPermissionChangeListeners.removeListenerLocked(listener);
4473        }
4474    }
4475
4476    @Override
4477    public boolean isProtectedBroadcast(String actionName) {
4478        synchronized (mPackages) {
4479            if (mProtectedBroadcasts.contains(actionName)) {
4480                return true;
4481            } else if (actionName != null) {
4482                // TODO: remove these terrible hacks
4483                if (actionName.startsWith("android.net.netmon.lingerExpired")
4484                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4485                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4486                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4487                    return true;
4488                }
4489            }
4490        }
4491        return false;
4492    }
4493
4494    @Override
4495    public int checkSignatures(String pkg1, String pkg2) {
4496        synchronized (mPackages) {
4497            final PackageParser.Package p1 = mPackages.get(pkg1);
4498            final PackageParser.Package p2 = mPackages.get(pkg2);
4499            if (p1 == null || p1.mExtras == null
4500                    || p2 == null || p2.mExtras == null) {
4501                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4502            }
4503            return compareSignatures(p1.mSignatures, p2.mSignatures);
4504        }
4505    }
4506
4507    @Override
4508    public int checkUidSignatures(int uid1, int uid2) {
4509        // Map to base uids.
4510        uid1 = UserHandle.getAppId(uid1);
4511        uid2 = UserHandle.getAppId(uid2);
4512        // reader
4513        synchronized (mPackages) {
4514            Signature[] s1;
4515            Signature[] s2;
4516            Object obj = mSettings.getUserIdLPr(uid1);
4517            if (obj != null) {
4518                if (obj instanceof SharedUserSetting) {
4519                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4520                } else if (obj instanceof PackageSetting) {
4521                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4522                } else {
4523                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4524                }
4525            } else {
4526                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4527            }
4528            obj = mSettings.getUserIdLPr(uid2);
4529            if (obj != null) {
4530                if (obj instanceof SharedUserSetting) {
4531                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4532                } else if (obj instanceof PackageSetting) {
4533                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4534                } else {
4535                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4536                }
4537            } else {
4538                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4539            }
4540            return compareSignatures(s1, s2);
4541        }
4542    }
4543
4544    /**
4545     * This method should typically only be used when granting or revoking
4546     * permissions, since the app may immediately restart after this call.
4547     * <p>
4548     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4549     * guard your work against the app being relaunched.
4550     */
4551    private void killUid(int appId, int userId, String reason) {
4552        final long identity = Binder.clearCallingIdentity();
4553        try {
4554            IActivityManager am = ActivityManagerNative.getDefault();
4555            if (am != null) {
4556                try {
4557                    am.killUid(appId, userId, reason);
4558                } catch (RemoteException e) {
4559                    /* ignore - same process */
4560                }
4561            }
4562        } finally {
4563            Binder.restoreCallingIdentity(identity);
4564        }
4565    }
4566
4567    /**
4568     * Compares two sets of signatures. Returns:
4569     * <br />
4570     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4571     * <br />
4572     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4573     * <br />
4574     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4575     * <br />
4576     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4577     * <br />
4578     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4579     */
4580    static int compareSignatures(Signature[] s1, Signature[] s2) {
4581        if (s1 == null) {
4582            return s2 == null
4583                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4584                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4585        }
4586
4587        if (s2 == null) {
4588            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4589        }
4590
4591        if (s1.length != s2.length) {
4592            return PackageManager.SIGNATURE_NO_MATCH;
4593        }
4594
4595        // Since both signature sets are of size 1, we can compare without HashSets.
4596        if (s1.length == 1) {
4597            return s1[0].equals(s2[0]) ?
4598                    PackageManager.SIGNATURE_MATCH :
4599                    PackageManager.SIGNATURE_NO_MATCH;
4600        }
4601
4602        ArraySet<Signature> set1 = new ArraySet<Signature>();
4603        for (Signature sig : s1) {
4604            set1.add(sig);
4605        }
4606        ArraySet<Signature> set2 = new ArraySet<Signature>();
4607        for (Signature sig : s2) {
4608            set2.add(sig);
4609        }
4610        // Make sure s2 contains all signatures in s1.
4611        if (set1.equals(set2)) {
4612            return PackageManager.SIGNATURE_MATCH;
4613        }
4614        return PackageManager.SIGNATURE_NO_MATCH;
4615    }
4616
4617    /**
4618     * If the database version for this type of package (internal storage or
4619     * external storage) is less than the version where package signatures
4620     * were updated, return true.
4621     */
4622    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4623        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4624        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4625    }
4626
4627    /**
4628     * Used for backward compatibility to make sure any packages with
4629     * certificate chains get upgraded to the new style. {@code existingSigs}
4630     * will be in the old format (since they were stored on disk from before the
4631     * system upgrade) and {@code scannedSigs} will be in the newer format.
4632     */
4633    private int compareSignaturesCompat(PackageSignatures existingSigs,
4634            PackageParser.Package scannedPkg) {
4635        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4636            return PackageManager.SIGNATURE_NO_MATCH;
4637        }
4638
4639        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4640        for (Signature sig : existingSigs.mSignatures) {
4641            existingSet.add(sig);
4642        }
4643        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4644        for (Signature sig : scannedPkg.mSignatures) {
4645            try {
4646                Signature[] chainSignatures = sig.getChainSignatures();
4647                for (Signature chainSig : chainSignatures) {
4648                    scannedCompatSet.add(chainSig);
4649                }
4650            } catch (CertificateEncodingException e) {
4651                scannedCompatSet.add(sig);
4652            }
4653        }
4654        /*
4655         * Make sure the expanded scanned set contains all signatures in the
4656         * existing one.
4657         */
4658        if (scannedCompatSet.equals(existingSet)) {
4659            // Migrate the old signatures to the new scheme.
4660            existingSigs.assignSignatures(scannedPkg.mSignatures);
4661            // The new KeySets will be re-added later in the scanning process.
4662            synchronized (mPackages) {
4663                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4664            }
4665            return PackageManager.SIGNATURE_MATCH;
4666        }
4667        return PackageManager.SIGNATURE_NO_MATCH;
4668    }
4669
4670    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4671        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4672        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4673    }
4674
4675    private int compareSignaturesRecover(PackageSignatures existingSigs,
4676            PackageParser.Package scannedPkg) {
4677        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4678            return PackageManager.SIGNATURE_NO_MATCH;
4679        }
4680
4681        String msg = null;
4682        try {
4683            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4684                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4685                        + scannedPkg.packageName);
4686                return PackageManager.SIGNATURE_MATCH;
4687            }
4688        } catch (CertificateException e) {
4689            msg = e.getMessage();
4690        }
4691
4692        logCriticalInfo(Log.INFO,
4693                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4694        return PackageManager.SIGNATURE_NO_MATCH;
4695    }
4696
4697    @Override
4698    public List<String> getAllPackages() {
4699        synchronized (mPackages) {
4700            return new ArrayList<String>(mPackages.keySet());
4701        }
4702    }
4703
4704    @Override
4705    public String[] getPackagesForUid(int uid) {
4706        final int userId = UserHandle.getUserId(uid);
4707        uid = UserHandle.getAppId(uid);
4708        // reader
4709        synchronized (mPackages) {
4710            Object obj = mSettings.getUserIdLPr(uid);
4711            if (obj instanceof SharedUserSetting) {
4712                final SharedUserSetting sus = (SharedUserSetting) obj;
4713                final int N = sus.packages.size();
4714                String[] res = new String[N];
4715                final Iterator<PackageSetting> it = sus.packages.iterator();
4716                int i = 0;
4717                while (it.hasNext()) {
4718                    PackageSetting ps = it.next();
4719                    if (ps.getInstalled(userId)) {
4720                        res[i++] = ps.name;
4721                    } else {
4722                        res = ArrayUtils.removeElement(String.class, res, res[i]);
4723                    }
4724                }
4725                return res;
4726            } else if (obj instanceof PackageSetting) {
4727                final PackageSetting ps = (PackageSetting) obj;
4728                return new String[] { ps.name };
4729            }
4730        }
4731        return null;
4732    }
4733
4734    @Override
4735    public String getNameForUid(int uid) {
4736        // reader
4737        synchronized (mPackages) {
4738            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4739            if (obj instanceof SharedUserSetting) {
4740                final SharedUserSetting sus = (SharedUserSetting) obj;
4741                return sus.name + ":" + sus.userId;
4742            } else if (obj instanceof PackageSetting) {
4743                final PackageSetting ps = (PackageSetting) obj;
4744                return ps.name;
4745            }
4746        }
4747        return null;
4748    }
4749
4750    @Override
4751    public int getUidForSharedUser(String sharedUserName) {
4752        if(sharedUserName == null) {
4753            return -1;
4754        }
4755        // reader
4756        synchronized (mPackages) {
4757            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4758            if (suid == null) {
4759                return -1;
4760            }
4761            return suid.userId;
4762        }
4763    }
4764
4765    @Override
4766    public int getFlagsForUid(int uid) {
4767        synchronized (mPackages) {
4768            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4769            if (obj instanceof SharedUserSetting) {
4770                final SharedUserSetting sus = (SharedUserSetting) obj;
4771                return sus.pkgFlags;
4772            } else if (obj instanceof PackageSetting) {
4773                final PackageSetting ps = (PackageSetting) obj;
4774                return ps.pkgFlags;
4775            }
4776        }
4777        return 0;
4778    }
4779
4780    @Override
4781    public int getPrivateFlagsForUid(int uid) {
4782        synchronized (mPackages) {
4783            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4784            if (obj instanceof SharedUserSetting) {
4785                final SharedUserSetting sus = (SharedUserSetting) obj;
4786                return sus.pkgPrivateFlags;
4787            } else if (obj instanceof PackageSetting) {
4788                final PackageSetting ps = (PackageSetting) obj;
4789                return ps.pkgPrivateFlags;
4790            }
4791        }
4792        return 0;
4793    }
4794
4795    @Override
4796    public boolean isUidPrivileged(int uid) {
4797        uid = UserHandle.getAppId(uid);
4798        // reader
4799        synchronized (mPackages) {
4800            Object obj = mSettings.getUserIdLPr(uid);
4801            if (obj instanceof SharedUserSetting) {
4802                final SharedUserSetting sus = (SharedUserSetting) obj;
4803                final Iterator<PackageSetting> it = sus.packages.iterator();
4804                while (it.hasNext()) {
4805                    if (it.next().isPrivileged()) {
4806                        return true;
4807                    }
4808                }
4809            } else if (obj instanceof PackageSetting) {
4810                final PackageSetting ps = (PackageSetting) obj;
4811                return ps.isPrivileged();
4812            }
4813        }
4814        return false;
4815    }
4816
4817    @Override
4818    public String[] getAppOpPermissionPackages(String permissionName) {
4819        synchronized (mPackages) {
4820            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4821            if (pkgs == null) {
4822                return null;
4823            }
4824            return pkgs.toArray(new String[pkgs.size()]);
4825        }
4826    }
4827
4828    @Override
4829    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4830            int flags, int userId) {
4831        try {
4832            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4833
4834            if (!sUserManager.exists(userId)) return null;
4835            flags = updateFlagsForResolve(flags, userId, intent);
4836            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4837                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4838
4839            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4840            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4841                    flags, userId);
4842            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4843
4844            final ResolveInfo bestChoice =
4845                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4846            return bestChoice;
4847        } finally {
4848            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4849        }
4850    }
4851
4852    @Override
4853    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4854            IntentFilter filter, int match, ComponentName activity) {
4855        final int userId = UserHandle.getCallingUserId();
4856        if (DEBUG_PREFERRED) {
4857            Log.v(TAG, "setLastChosenActivity intent=" + intent
4858                + " resolvedType=" + resolvedType
4859                + " flags=" + flags
4860                + " filter=" + filter
4861                + " match=" + match
4862                + " activity=" + activity);
4863            filter.dump(new PrintStreamPrinter(System.out), "    ");
4864        }
4865        intent.setComponent(null);
4866        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4867                userId);
4868        // Find any earlier preferred or last chosen entries and nuke them
4869        findPreferredActivity(intent, resolvedType,
4870                flags, query, 0, false, true, false, userId);
4871        // Add the new activity as the last chosen for this filter
4872        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4873                "Setting last chosen");
4874    }
4875
4876    @Override
4877    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4878        final int userId = UserHandle.getCallingUserId();
4879        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4880        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4881                userId);
4882        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4883                false, false, false, userId);
4884    }
4885
4886    private boolean isEphemeralDisabled() {
4887        // ephemeral apps have been disabled across the board
4888        if (DISABLE_EPHEMERAL_APPS) {
4889            return true;
4890        }
4891        // system isn't up yet; can't read settings, so, assume no ephemeral apps
4892        if (!mSystemReady) {
4893            return true;
4894        }
4895        // we can't get a content resolver until the system is ready; these checks must happen last
4896        final ContentResolver resolver = mContext.getContentResolver();
4897        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
4898            return true;
4899        }
4900        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
4901    }
4902
4903    private boolean isEphemeralAllowed(
4904            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4905            boolean skipPackageCheck) {
4906        // Short circuit and return early if possible.
4907        if (isEphemeralDisabled()) {
4908            return false;
4909        }
4910        final int callingUser = UserHandle.getCallingUserId();
4911        if (callingUser != UserHandle.USER_SYSTEM) {
4912            return false;
4913        }
4914        if (mEphemeralResolverConnection == null) {
4915            return false;
4916        }
4917        if (intent.getComponent() != null) {
4918            return false;
4919        }
4920        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4921            return false;
4922        }
4923        if (!skipPackageCheck && intent.getPackage() != null) {
4924            return false;
4925        }
4926        final boolean isWebUri = hasWebURI(intent);
4927        if (!isWebUri || intent.getData().getHost() == null) {
4928            return false;
4929        }
4930        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4931        synchronized (mPackages) {
4932            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4933            for (int n = 0; n < count; n++) {
4934                ResolveInfo info = resolvedActivities.get(n);
4935                String packageName = info.activityInfo.packageName;
4936                PackageSetting ps = mSettings.mPackages.get(packageName);
4937                if (ps != null) {
4938                    // Try to get the status from User settings first
4939                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4940                    int status = (int) (packedStatus >> 32);
4941                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4942                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4943                        if (DEBUG_EPHEMERAL) {
4944                            Slog.v(TAG, "DENY ephemeral apps;"
4945                                + " pkg: " + packageName + ", status: " + status);
4946                        }
4947                        return false;
4948                    }
4949                }
4950            }
4951        }
4952        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4953        return true;
4954    }
4955
4956    private static EphemeralResolveInfo getEphemeralResolveInfo(
4957            Context context, EphemeralResolverConnection resolverConnection, Intent intent,
4958            String resolvedType, int userId, String packageName) {
4959        final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(),
4960                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4961        final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(),
4962                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4963        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4964                ephemeralPrefixCount);
4965        final int[] shaPrefix = digest.getDigestPrefix();
4966        final byte[][] digestBytes = digest.getDigestBytes();
4967        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4968                resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask);
4969        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4970            // No hash prefix match; there are no ephemeral apps for this domain.
4971            return null;
4972        }
4973
4974        // Go in reverse order so we match the narrowest scope first.
4975        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4976            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4977                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4978                    continue;
4979                }
4980                final List<IntentFilter> filters = ephemeralApplication.getFilters();
4981                // No filters; this should never happen.
4982                if (filters.isEmpty()) {
4983                    continue;
4984                }
4985                if (packageName != null
4986                        && !packageName.equals(ephemeralApplication.getPackageName())) {
4987                    continue;
4988                }
4989                // We have a domain match; resolve the filters to see if anything matches.
4990                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4991                for (int j = filters.size() - 1; j >= 0; --j) {
4992                    final EphemeralResolveIntentInfo intentInfo =
4993                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4994                    ephemeralResolver.addFilter(intentInfo);
4995                }
4996                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4997                        intent, resolvedType, false /*defaultOnly*/, userId);
4998                if (!matchedResolveInfoList.isEmpty()) {
4999                    return matchedResolveInfoList.get(0);
5000                }
5001            }
5002        }
5003        // Hash or filter mis-match; no ephemeral apps for this domain.
5004        return null;
5005    }
5006
5007    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5008            int flags, List<ResolveInfo> query, int userId) {
5009        if (query != null) {
5010            final int N = query.size();
5011            if (N == 1) {
5012                return query.get(0);
5013            } else if (N > 1) {
5014                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5015                // If there is more than one activity with the same priority,
5016                // then let the user decide between them.
5017                ResolveInfo r0 = query.get(0);
5018                ResolveInfo r1 = query.get(1);
5019                if (DEBUG_INTENT_MATCHING || debug) {
5020                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5021                            + r1.activityInfo.name + "=" + r1.priority);
5022                }
5023                // If the first activity has a higher priority, or a different
5024                // default, then it is always desirable to pick it.
5025                if (r0.priority != r1.priority
5026                        || r0.preferredOrder != r1.preferredOrder
5027                        || r0.isDefault != r1.isDefault) {
5028                    return query.get(0);
5029                }
5030                // If we have saved a preference for a preferred activity for
5031                // this Intent, use that.
5032                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5033                        flags, query, r0.priority, true, false, debug, userId);
5034                if (ri != null) {
5035                    return ri;
5036                }
5037                ri = new ResolveInfo(mResolveInfo);
5038                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5039                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5040                // If all of the options come from the same package, show the application's
5041                // label and icon instead of the generic resolver's.
5042                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5043                // and then throw away the ResolveInfo itself, meaning that the caller loses
5044                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5045                // a fallback for this case; we only set the target package's resources on
5046                // the ResolveInfo, not the ActivityInfo.
5047                final String intentPackage = intent.getPackage();
5048                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5049                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5050                    ri.resolvePackageName = intentPackage;
5051                    if (userNeedsBadging(userId)) {
5052                        ri.noResourceId = true;
5053                    } else {
5054                        ri.icon = appi.icon;
5055                    }
5056                    ri.iconResourceId = appi.icon;
5057                    ri.labelRes = appi.labelRes;
5058                }
5059                ri.activityInfo.applicationInfo = new ApplicationInfo(
5060                        ri.activityInfo.applicationInfo);
5061                if (userId != 0) {
5062                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5063                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5064                }
5065                // Make sure that the resolver is displayable in car mode
5066                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5067                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5068                return ri;
5069            }
5070        }
5071        return null;
5072    }
5073
5074    /**
5075     * Return true if the given list is not empty and all of its contents have
5076     * an activityInfo with the given package name.
5077     */
5078    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5079        if (ArrayUtils.isEmpty(list)) {
5080            return false;
5081        }
5082        for (int i = 0, N = list.size(); i < N; i++) {
5083            final ResolveInfo ri = list.get(i);
5084            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5085            if (ai == null || !packageName.equals(ai.packageName)) {
5086                return false;
5087            }
5088        }
5089        return true;
5090    }
5091
5092    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5093            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5094        final int N = query.size();
5095        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5096                .get(userId);
5097        // Get the list of persistent preferred activities that handle the intent
5098        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5099        List<PersistentPreferredActivity> pprefs = ppir != null
5100                ? ppir.queryIntent(intent, resolvedType,
5101                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5102                : null;
5103        if (pprefs != null && pprefs.size() > 0) {
5104            final int M = pprefs.size();
5105            for (int i=0; i<M; i++) {
5106                final PersistentPreferredActivity ppa = pprefs.get(i);
5107                if (DEBUG_PREFERRED || debug) {
5108                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5109                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5110                            + "\n  component=" + ppa.mComponent);
5111                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5112                }
5113                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5114                        flags | MATCH_DISABLED_COMPONENTS, userId);
5115                if (DEBUG_PREFERRED || debug) {
5116                    Slog.v(TAG, "Found persistent preferred activity:");
5117                    if (ai != null) {
5118                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5119                    } else {
5120                        Slog.v(TAG, "  null");
5121                    }
5122                }
5123                if (ai == null) {
5124                    // This previously registered persistent preferred activity
5125                    // component is no longer known. Ignore it and do NOT remove it.
5126                    continue;
5127                }
5128                for (int j=0; j<N; j++) {
5129                    final ResolveInfo ri = query.get(j);
5130                    if (!ri.activityInfo.applicationInfo.packageName
5131                            .equals(ai.applicationInfo.packageName)) {
5132                        continue;
5133                    }
5134                    if (!ri.activityInfo.name.equals(ai.name)) {
5135                        continue;
5136                    }
5137                    //  Found a persistent preference that can handle the intent.
5138                    if (DEBUG_PREFERRED || debug) {
5139                        Slog.v(TAG, "Returning persistent preferred activity: " +
5140                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5141                    }
5142                    return ri;
5143                }
5144            }
5145        }
5146        return null;
5147    }
5148
5149    // TODO: handle preferred activities missing while user has amnesia
5150    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5151            List<ResolveInfo> query, int priority, boolean always,
5152            boolean removeMatches, boolean debug, int userId) {
5153        if (!sUserManager.exists(userId)) return null;
5154        flags = updateFlagsForResolve(flags, userId, intent);
5155        // writer
5156        synchronized (mPackages) {
5157            if (intent.getSelector() != null) {
5158                intent = intent.getSelector();
5159            }
5160            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5161
5162            // Try to find a matching persistent preferred activity.
5163            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5164                    debug, userId);
5165
5166            // If a persistent preferred activity matched, use it.
5167            if (pri != null) {
5168                return pri;
5169            }
5170
5171            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5172            // Get the list of preferred activities that handle the intent
5173            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5174            List<PreferredActivity> prefs = pir != null
5175                    ? pir.queryIntent(intent, resolvedType,
5176                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5177                    : null;
5178            if (prefs != null && prefs.size() > 0) {
5179                boolean changed = false;
5180                try {
5181                    // First figure out how good the original match set is.
5182                    // We will only allow preferred activities that came
5183                    // from the same match quality.
5184                    int match = 0;
5185
5186                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5187
5188                    final int N = query.size();
5189                    for (int j=0; j<N; j++) {
5190                        final ResolveInfo ri = query.get(j);
5191                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5192                                + ": 0x" + Integer.toHexString(match));
5193                        if (ri.match > match) {
5194                            match = ri.match;
5195                        }
5196                    }
5197
5198                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5199                            + Integer.toHexString(match));
5200
5201                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5202                    final int M = prefs.size();
5203                    for (int i=0; i<M; i++) {
5204                        final PreferredActivity pa = prefs.get(i);
5205                        if (DEBUG_PREFERRED || debug) {
5206                            Slog.v(TAG, "Checking PreferredActivity ds="
5207                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5208                                    + "\n  component=" + pa.mPref.mComponent);
5209                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5210                        }
5211                        if (pa.mPref.mMatch != match) {
5212                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5213                                    + Integer.toHexString(pa.mPref.mMatch));
5214                            continue;
5215                        }
5216                        // If it's not an "always" type preferred activity and that's what we're
5217                        // looking for, skip it.
5218                        if (always && !pa.mPref.mAlways) {
5219                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5220                            continue;
5221                        }
5222                        final ActivityInfo ai = getActivityInfo(
5223                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5224                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5225                                userId);
5226                        if (DEBUG_PREFERRED || debug) {
5227                            Slog.v(TAG, "Found preferred activity:");
5228                            if (ai != null) {
5229                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5230                            } else {
5231                                Slog.v(TAG, "  null");
5232                            }
5233                        }
5234                        if (ai == null) {
5235                            // This previously registered preferred activity
5236                            // component is no longer known.  Most likely an update
5237                            // to the app was installed and in the new version this
5238                            // component no longer exists.  Clean it up by removing
5239                            // it from the preferred activities list, and skip it.
5240                            Slog.w(TAG, "Removing dangling preferred activity: "
5241                                    + pa.mPref.mComponent);
5242                            pir.removeFilter(pa);
5243                            changed = true;
5244                            continue;
5245                        }
5246                        for (int j=0; j<N; j++) {
5247                            final ResolveInfo ri = query.get(j);
5248                            if (!ri.activityInfo.applicationInfo.packageName
5249                                    .equals(ai.applicationInfo.packageName)) {
5250                                continue;
5251                            }
5252                            if (!ri.activityInfo.name.equals(ai.name)) {
5253                                continue;
5254                            }
5255
5256                            if (removeMatches) {
5257                                pir.removeFilter(pa);
5258                                changed = true;
5259                                if (DEBUG_PREFERRED) {
5260                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5261                                }
5262                                break;
5263                            }
5264
5265                            // Okay we found a previously set preferred or last chosen app.
5266                            // If the result set is different from when this
5267                            // was created, we need to clear it and re-ask the
5268                            // user their preference, if we're looking for an "always" type entry.
5269                            if (always && !pa.mPref.sameSet(query)) {
5270                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5271                                        + intent + " type " + resolvedType);
5272                                if (DEBUG_PREFERRED) {
5273                                    Slog.v(TAG, "Removing preferred activity since set changed "
5274                                            + pa.mPref.mComponent);
5275                                }
5276                                pir.removeFilter(pa);
5277                                // Re-add the filter as a "last chosen" entry (!always)
5278                                PreferredActivity lastChosen = new PreferredActivity(
5279                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5280                                pir.addFilter(lastChosen);
5281                                changed = true;
5282                                return null;
5283                            }
5284
5285                            // Yay! Either the set matched or we're looking for the last chosen
5286                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5287                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5288                            return ri;
5289                        }
5290                    }
5291                } finally {
5292                    if (changed) {
5293                        if (DEBUG_PREFERRED) {
5294                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5295                        }
5296                        scheduleWritePackageRestrictionsLocked(userId);
5297                    }
5298                }
5299            }
5300        }
5301        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5302        return null;
5303    }
5304
5305    /*
5306     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5307     */
5308    @Override
5309    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5310            int targetUserId) {
5311        mContext.enforceCallingOrSelfPermission(
5312                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5313        List<CrossProfileIntentFilter> matches =
5314                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5315        if (matches != null) {
5316            int size = matches.size();
5317            for (int i = 0; i < size; i++) {
5318                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5319            }
5320        }
5321        if (hasWebURI(intent)) {
5322            // cross-profile app linking works only towards the parent.
5323            final UserInfo parent = getProfileParent(sourceUserId);
5324            synchronized(mPackages) {
5325                int flags = updateFlagsForResolve(0, parent.id, intent);
5326                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5327                        intent, resolvedType, flags, sourceUserId, parent.id);
5328                return xpDomainInfo != null;
5329            }
5330        }
5331        return false;
5332    }
5333
5334    private UserInfo getProfileParent(int userId) {
5335        final long identity = Binder.clearCallingIdentity();
5336        try {
5337            return sUserManager.getProfileParent(userId);
5338        } finally {
5339            Binder.restoreCallingIdentity(identity);
5340        }
5341    }
5342
5343    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5344            String resolvedType, int userId) {
5345        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5346        if (resolver != null) {
5347            return resolver.queryIntent(intent, resolvedType, false, userId);
5348        }
5349        return null;
5350    }
5351
5352    @Override
5353    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5354            String resolvedType, int flags, int userId) {
5355        try {
5356            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5357
5358            return new ParceledListSlice<>(
5359                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5360        } finally {
5361            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5362        }
5363    }
5364
5365    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5366            String resolvedType, int flags, int userId) {
5367        if (!sUserManager.exists(userId)) return Collections.emptyList();
5368        flags = updateFlagsForResolve(flags, userId, intent);
5369        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5370                false /* requireFullPermission */, false /* checkShell */,
5371                "query intent activities");
5372        ComponentName comp = intent.getComponent();
5373        if (comp == null) {
5374            if (intent.getSelector() != null) {
5375                intent = intent.getSelector();
5376                comp = intent.getComponent();
5377            }
5378        }
5379
5380        if (comp != null) {
5381            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5382            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5383            if (ai != null) {
5384                final ResolveInfo ri = new ResolveInfo();
5385                ri.activityInfo = ai;
5386                list.add(ri);
5387            }
5388            return list;
5389        }
5390
5391        // reader
5392        boolean sortResult = false;
5393        boolean addEphemeral = false;
5394        boolean matchEphemeralPackage = false;
5395        List<ResolveInfo> result;
5396        final String pkgName = intent.getPackage();
5397        synchronized (mPackages) {
5398            if (pkgName == null) {
5399                List<CrossProfileIntentFilter> matchingFilters =
5400                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5401                // Check for results that need to skip the current profile.
5402                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5403                        resolvedType, flags, userId);
5404                if (xpResolveInfo != null) {
5405                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5406                    xpResult.add(xpResolveInfo);
5407                    return filterIfNotSystemUser(xpResult, userId);
5408                }
5409
5410                // Check for results in the current profile.
5411                result = filterIfNotSystemUser(mActivities.queryIntent(
5412                        intent, resolvedType, flags, userId), userId);
5413                addEphemeral =
5414                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5415
5416                // Check for cross profile results.
5417                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5418                xpResolveInfo = queryCrossProfileIntents(
5419                        matchingFilters, intent, resolvedType, flags, userId,
5420                        hasNonNegativePriorityResult);
5421                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5422                    boolean isVisibleToUser = filterIfNotSystemUser(
5423                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5424                    if (isVisibleToUser) {
5425                        result.add(xpResolveInfo);
5426                        sortResult = true;
5427                    }
5428                }
5429                if (hasWebURI(intent)) {
5430                    CrossProfileDomainInfo xpDomainInfo = null;
5431                    final UserInfo parent = getProfileParent(userId);
5432                    if (parent != null) {
5433                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5434                                flags, userId, parent.id);
5435                    }
5436                    if (xpDomainInfo != null) {
5437                        if (xpResolveInfo != null) {
5438                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5439                            // in the result.
5440                            result.remove(xpResolveInfo);
5441                        }
5442                        if (result.size() == 0 && !addEphemeral) {
5443                            // No result in current profile, but found candidate in parent user.
5444                            // And we are not going to add emphemeral app, so we can return the
5445                            // result straight away.
5446                            result.add(xpDomainInfo.resolveInfo);
5447                            return result;
5448                        }
5449                    } else if (result.size() <= 1 && !addEphemeral) {
5450                        // No result in parent user and <= 1 result in current profile, and we
5451                        // are not going to add emphemeral app, so we can return the result without
5452                        // further processing.
5453                        return result;
5454                    }
5455                    // We have more than one candidate (combining results from current and parent
5456                    // profile), so we need filtering and sorting.
5457                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
5458                            intent, flags, result, xpDomainInfo, userId);
5459                    sortResult = true;
5460                }
5461            } else {
5462                final PackageParser.Package pkg = mPackages.get(pkgName);
5463                if (pkg != null) {
5464                    result = filterIfNotSystemUser(
5465                            mActivities.queryIntentForPackage(
5466                                    intent, resolvedType, flags, pkg.activities, userId),
5467                            userId);
5468                } else {
5469                    // the caller wants to resolve for a particular package; however, there
5470                    // were no installed results, so, try to find an ephemeral result
5471                    addEphemeral = isEphemeralAllowed(
5472                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5473                    matchEphemeralPackage = true;
5474                    result = new ArrayList<ResolveInfo>();
5475                }
5476            }
5477        }
5478        if (addEphemeral) {
5479            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5480            final EphemeralResolveInfo ai = getEphemeralResolveInfo(
5481                    mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5482                    matchEphemeralPackage ? pkgName : null);
5483            if (ai != null) {
5484                if (DEBUG_EPHEMERAL) {
5485                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5486                }
5487                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5488                ephemeralInstaller.ephemeralResolveInfo = ai;
5489                // make sure this resolver is the default
5490                ephemeralInstaller.isDefault = true;
5491                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5492                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5493                // add a non-generic filter
5494                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5495                ephemeralInstaller.filter.addDataPath(
5496                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5497                result.add(ephemeralInstaller);
5498            }
5499            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5500        }
5501        if (sortResult) {
5502            Collections.sort(result, mResolvePrioritySorter);
5503        }
5504        return result;
5505    }
5506
5507    private static class CrossProfileDomainInfo {
5508        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5509        ResolveInfo resolveInfo;
5510        /* Best domain verification status of the activities found in the other profile */
5511        int bestDomainVerificationStatus;
5512    }
5513
5514    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5515            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5516        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5517                sourceUserId)) {
5518            return null;
5519        }
5520        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5521                resolvedType, flags, parentUserId);
5522
5523        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5524            return null;
5525        }
5526        CrossProfileDomainInfo result = null;
5527        int size = resultTargetUser.size();
5528        for (int i = 0; i < size; i++) {
5529            ResolveInfo riTargetUser = resultTargetUser.get(i);
5530            // Intent filter verification is only for filters that specify a host. So don't return
5531            // those that handle all web uris.
5532            if (riTargetUser.handleAllWebDataURI) {
5533                continue;
5534            }
5535            String packageName = riTargetUser.activityInfo.packageName;
5536            PackageSetting ps = mSettings.mPackages.get(packageName);
5537            if (ps == null) {
5538                continue;
5539            }
5540            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5541            int status = (int)(verificationState >> 32);
5542            if (result == null) {
5543                result = new CrossProfileDomainInfo();
5544                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5545                        sourceUserId, parentUserId);
5546                result.bestDomainVerificationStatus = status;
5547            } else {
5548                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5549                        result.bestDomainVerificationStatus);
5550            }
5551        }
5552        // Don't consider matches with status NEVER across profiles.
5553        if (result != null && result.bestDomainVerificationStatus
5554                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5555            return null;
5556        }
5557        return result;
5558    }
5559
5560    /**
5561     * Verification statuses are ordered from the worse to the best, except for
5562     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5563     */
5564    private int bestDomainVerificationStatus(int status1, int status2) {
5565        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5566            return status2;
5567        }
5568        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5569            return status1;
5570        }
5571        return (int) MathUtils.max(status1, status2);
5572    }
5573
5574    private boolean isUserEnabled(int userId) {
5575        long callingId = Binder.clearCallingIdentity();
5576        try {
5577            UserInfo userInfo = sUserManager.getUserInfo(userId);
5578            return userInfo != null && userInfo.isEnabled();
5579        } finally {
5580            Binder.restoreCallingIdentity(callingId);
5581        }
5582    }
5583
5584    /**
5585     * Filter out activities with systemUserOnly flag set, when current user is not System.
5586     *
5587     * @return filtered list
5588     */
5589    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5590        if (userId == UserHandle.USER_SYSTEM) {
5591            return resolveInfos;
5592        }
5593        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5594            ResolveInfo info = resolveInfos.get(i);
5595            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5596                resolveInfos.remove(i);
5597            }
5598        }
5599        return resolveInfos;
5600    }
5601
5602    /**
5603     * @param resolveInfos list of resolve infos in descending priority order
5604     * @return if the list contains a resolve info with non-negative priority
5605     */
5606    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5607        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5608    }
5609
5610    private static boolean hasWebURI(Intent intent) {
5611        if (intent.getData() == null) {
5612            return false;
5613        }
5614        final String scheme = intent.getScheme();
5615        if (TextUtils.isEmpty(scheme)) {
5616            return false;
5617        }
5618        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5619    }
5620
5621    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5622            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5623            int userId) {
5624        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5625
5626        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5627            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5628                    candidates.size());
5629        }
5630
5631        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5632        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5633        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5634        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5635        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5636        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5637
5638        synchronized (mPackages) {
5639            final int count = candidates.size();
5640            // First, try to use linked apps. Partition the candidates into four lists:
5641            // one for the final results, one for the "do not use ever", one for "undefined status"
5642            // and finally one for "browser app type".
5643            for (int n=0; n<count; n++) {
5644                ResolveInfo info = candidates.get(n);
5645                String packageName = info.activityInfo.packageName;
5646                PackageSetting ps = mSettings.mPackages.get(packageName);
5647                if (ps != null) {
5648                    // Add to the special match all list (Browser use case)
5649                    if (info.handleAllWebDataURI) {
5650                        matchAllList.add(info);
5651                        continue;
5652                    }
5653                    // Try to get the status from User settings first
5654                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5655                    int status = (int)(packedStatus >> 32);
5656                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5657                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5658                        if (DEBUG_DOMAIN_VERIFICATION) {
5659                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5660                                    + " : linkgen=" + linkGeneration);
5661                        }
5662                        // Use link-enabled generation as preferredOrder, i.e.
5663                        // prefer newly-enabled over earlier-enabled.
5664                        info.preferredOrder = linkGeneration;
5665                        alwaysList.add(info);
5666                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5667                        if (DEBUG_DOMAIN_VERIFICATION) {
5668                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5669                        }
5670                        neverList.add(info);
5671                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5672                        if (DEBUG_DOMAIN_VERIFICATION) {
5673                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5674                        }
5675                        alwaysAskList.add(info);
5676                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5677                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5678                        if (DEBUG_DOMAIN_VERIFICATION) {
5679                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5680                        }
5681                        undefinedList.add(info);
5682                    }
5683                }
5684            }
5685
5686            // We'll want to include browser possibilities in a few cases
5687            boolean includeBrowser = false;
5688
5689            // First try to add the "always" resolution(s) for the current user, if any
5690            if (alwaysList.size() > 0) {
5691                result.addAll(alwaysList);
5692            } else {
5693                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5694                result.addAll(undefinedList);
5695                // Maybe add one for the other profile.
5696                if (xpDomainInfo != null && (
5697                        xpDomainInfo.bestDomainVerificationStatus
5698                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5699                    result.add(xpDomainInfo.resolveInfo);
5700                }
5701                includeBrowser = true;
5702            }
5703
5704            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5705            // If there were 'always' entries their preferred order has been set, so we also
5706            // back that off to make the alternatives equivalent
5707            if (alwaysAskList.size() > 0) {
5708                for (ResolveInfo i : result) {
5709                    i.preferredOrder = 0;
5710                }
5711                result.addAll(alwaysAskList);
5712                includeBrowser = true;
5713            }
5714
5715            if (includeBrowser) {
5716                // Also add browsers (all of them or only the default one)
5717                if (DEBUG_DOMAIN_VERIFICATION) {
5718                    Slog.v(TAG, "   ...including browsers in candidate set");
5719                }
5720                if ((matchFlags & MATCH_ALL) != 0) {
5721                    result.addAll(matchAllList);
5722                } else {
5723                    // Browser/generic handling case.  If there's a default browser, go straight
5724                    // to that (but only if there is no other higher-priority match).
5725                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5726                    int maxMatchPrio = 0;
5727                    ResolveInfo defaultBrowserMatch = null;
5728                    final int numCandidates = matchAllList.size();
5729                    for (int n = 0; n < numCandidates; n++) {
5730                        ResolveInfo info = matchAllList.get(n);
5731                        // track the highest overall match priority...
5732                        if (info.priority > maxMatchPrio) {
5733                            maxMatchPrio = info.priority;
5734                        }
5735                        // ...and the highest-priority default browser match
5736                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5737                            if (defaultBrowserMatch == null
5738                                    || (defaultBrowserMatch.priority < info.priority)) {
5739                                if (debug) {
5740                                    Slog.v(TAG, "Considering default browser match " + info);
5741                                }
5742                                defaultBrowserMatch = info;
5743                            }
5744                        }
5745                    }
5746                    if (defaultBrowserMatch != null
5747                            && defaultBrowserMatch.priority >= maxMatchPrio
5748                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5749                    {
5750                        if (debug) {
5751                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5752                        }
5753                        result.add(defaultBrowserMatch);
5754                    } else {
5755                        result.addAll(matchAllList);
5756                    }
5757                }
5758
5759                // If there is nothing selected, add all candidates and remove the ones that the user
5760                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5761                if (result.size() == 0) {
5762                    result.addAll(candidates);
5763                    result.removeAll(neverList);
5764                }
5765            }
5766        }
5767        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5768            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5769                    result.size());
5770            for (ResolveInfo info : result) {
5771                Slog.v(TAG, "  + " + info.activityInfo);
5772            }
5773        }
5774        return result;
5775    }
5776
5777    // Returns a packed value as a long:
5778    //
5779    // high 'int'-sized word: link status: undefined/ask/never/always.
5780    // low 'int'-sized word: relative priority among 'always' results.
5781    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5782        long result = ps.getDomainVerificationStatusForUser(userId);
5783        // if none available, get the master status
5784        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5785            if (ps.getIntentFilterVerificationInfo() != null) {
5786                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5787            }
5788        }
5789        return result;
5790    }
5791
5792    private ResolveInfo querySkipCurrentProfileIntents(
5793            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5794            int flags, int sourceUserId) {
5795        if (matchingFilters != null) {
5796            int size = matchingFilters.size();
5797            for (int i = 0; i < size; i ++) {
5798                CrossProfileIntentFilter filter = matchingFilters.get(i);
5799                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5800                    // Checking if there are activities in the target user that can handle the
5801                    // intent.
5802                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5803                            resolvedType, flags, sourceUserId);
5804                    if (resolveInfo != null) {
5805                        return resolveInfo;
5806                    }
5807                }
5808            }
5809        }
5810        return null;
5811    }
5812
5813    // Return matching ResolveInfo in target user if any.
5814    private ResolveInfo queryCrossProfileIntents(
5815            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5816            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5817        if (matchingFilters != null) {
5818            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5819            // match the same intent. For performance reasons, it is better not to
5820            // run queryIntent twice for the same userId
5821            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5822            int size = matchingFilters.size();
5823            for (int i = 0; i < size; i++) {
5824                CrossProfileIntentFilter filter = matchingFilters.get(i);
5825                int targetUserId = filter.getTargetUserId();
5826                boolean skipCurrentProfile =
5827                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5828                boolean skipCurrentProfileIfNoMatchFound =
5829                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5830                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5831                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5832                    // Checking if there are activities in the target user that can handle the
5833                    // intent.
5834                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5835                            resolvedType, flags, sourceUserId);
5836                    if (resolveInfo != null) return resolveInfo;
5837                    alreadyTriedUserIds.put(targetUserId, true);
5838                }
5839            }
5840        }
5841        return null;
5842    }
5843
5844    /**
5845     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5846     * will forward the intent to the filter's target user.
5847     * Otherwise, returns null.
5848     */
5849    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5850            String resolvedType, int flags, int sourceUserId) {
5851        int targetUserId = filter.getTargetUserId();
5852        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5853                resolvedType, flags, targetUserId);
5854        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5855            // If all the matches in the target profile are suspended, return null.
5856            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5857                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5858                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5859                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5860                            targetUserId);
5861                }
5862            }
5863        }
5864        return null;
5865    }
5866
5867    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5868            int sourceUserId, int targetUserId) {
5869        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5870        long ident = Binder.clearCallingIdentity();
5871        boolean targetIsProfile;
5872        try {
5873            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5874        } finally {
5875            Binder.restoreCallingIdentity(ident);
5876        }
5877        String className;
5878        if (targetIsProfile) {
5879            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5880        } else {
5881            className = FORWARD_INTENT_TO_PARENT;
5882        }
5883        ComponentName forwardingActivityComponentName = new ComponentName(
5884                mAndroidApplication.packageName, className);
5885        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5886                sourceUserId);
5887        if (!targetIsProfile) {
5888            forwardingActivityInfo.showUserIcon = targetUserId;
5889            forwardingResolveInfo.noResourceId = true;
5890        }
5891        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5892        forwardingResolveInfo.priority = 0;
5893        forwardingResolveInfo.preferredOrder = 0;
5894        forwardingResolveInfo.match = 0;
5895        forwardingResolveInfo.isDefault = true;
5896        forwardingResolveInfo.filter = filter;
5897        forwardingResolveInfo.targetUserId = targetUserId;
5898        return forwardingResolveInfo;
5899    }
5900
5901    @Override
5902    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5903            Intent[] specifics, String[] specificTypes, Intent intent,
5904            String resolvedType, int flags, int userId) {
5905        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5906                specificTypes, intent, resolvedType, flags, userId));
5907    }
5908
5909    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5910            Intent[] specifics, String[] specificTypes, Intent intent,
5911            String resolvedType, int flags, int userId) {
5912        if (!sUserManager.exists(userId)) return Collections.emptyList();
5913        flags = updateFlagsForResolve(flags, userId, intent);
5914        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5915                false /* requireFullPermission */, false /* checkShell */,
5916                "query intent activity options");
5917        final String resultsAction = intent.getAction();
5918
5919        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5920                | PackageManager.GET_RESOLVED_FILTER, userId);
5921
5922        if (DEBUG_INTENT_MATCHING) {
5923            Log.v(TAG, "Query " + intent + ": " + results);
5924        }
5925
5926        int specificsPos = 0;
5927        int N;
5928
5929        // todo: note that the algorithm used here is O(N^2).  This
5930        // isn't a problem in our current environment, but if we start running
5931        // into situations where we have more than 5 or 10 matches then this
5932        // should probably be changed to something smarter...
5933
5934        // First we go through and resolve each of the specific items
5935        // that were supplied, taking care of removing any corresponding
5936        // duplicate items in the generic resolve list.
5937        if (specifics != null) {
5938            for (int i=0; i<specifics.length; i++) {
5939                final Intent sintent = specifics[i];
5940                if (sintent == null) {
5941                    continue;
5942                }
5943
5944                if (DEBUG_INTENT_MATCHING) {
5945                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5946                }
5947
5948                String action = sintent.getAction();
5949                if (resultsAction != null && resultsAction.equals(action)) {
5950                    // If this action was explicitly requested, then don't
5951                    // remove things that have it.
5952                    action = null;
5953                }
5954
5955                ResolveInfo ri = null;
5956                ActivityInfo ai = null;
5957
5958                ComponentName comp = sintent.getComponent();
5959                if (comp == null) {
5960                    ri = resolveIntent(
5961                        sintent,
5962                        specificTypes != null ? specificTypes[i] : null,
5963                            flags, userId);
5964                    if (ri == null) {
5965                        continue;
5966                    }
5967                    if (ri == mResolveInfo) {
5968                        // ACK!  Must do something better with this.
5969                    }
5970                    ai = ri.activityInfo;
5971                    comp = new ComponentName(ai.applicationInfo.packageName,
5972                            ai.name);
5973                } else {
5974                    ai = getActivityInfo(comp, flags, userId);
5975                    if (ai == null) {
5976                        continue;
5977                    }
5978                }
5979
5980                // Look for any generic query activities that are duplicates
5981                // of this specific one, and remove them from the results.
5982                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5983                N = results.size();
5984                int j;
5985                for (j=specificsPos; j<N; j++) {
5986                    ResolveInfo sri = results.get(j);
5987                    if ((sri.activityInfo.name.equals(comp.getClassName())
5988                            && sri.activityInfo.applicationInfo.packageName.equals(
5989                                    comp.getPackageName()))
5990                        || (action != null && sri.filter.matchAction(action))) {
5991                        results.remove(j);
5992                        if (DEBUG_INTENT_MATCHING) Log.v(
5993                            TAG, "Removing duplicate item from " + j
5994                            + " due to specific " + specificsPos);
5995                        if (ri == null) {
5996                            ri = sri;
5997                        }
5998                        j--;
5999                        N--;
6000                    }
6001                }
6002
6003                // Add this specific item to its proper place.
6004                if (ri == null) {
6005                    ri = new ResolveInfo();
6006                    ri.activityInfo = ai;
6007                }
6008                results.add(specificsPos, ri);
6009                ri.specificIndex = i;
6010                specificsPos++;
6011            }
6012        }
6013
6014        // Now we go through the remaining generic results and remove any
6015        // duplicate actions that are found here.
6016        N = results.size();
6017        for (int i=specificsPos; i<N-1; i++) {
6018            final ResolveInfo rii = results.get(i);
6019            if (rii.filter == null) {
6020                continue;
6021            }
6022
6023            // Iterate over all of the actions of this result's intent
6024            // filter...  typically this should be just one.
6025            final Iterator<String> it = rii.filter.actionsIterator();
6026            if (it == null) {
6027                continue;
6028            }
6029            while (it.hasNext()) {
6030                final String action = it.next();
6031                if (resultsAction != null && resultsAction.equals(action)) {
6032                    // If this action was explicitly requested, then don't
6033                    // remove things that have it.
6034                    continue;
6035                }
6036                for (int j=i+1; j<N; j++) {
6037                    final ResolveInfo rij = results.get(j);
6038                    if (rij.filter != null && rij.filter.hasAction(action)) {
6039                        results.remove(j);
6040                        if (DEBUG_INTENT_MATCHING) Log.v(
6041                            TAG, "Removing duplicate item from " + j
6042                            + " due to action " + action + " at " + i);
6043                        j--;
6044                        N--;
6045                    }
6046                }
6047            }
6048
6049            // If the caller didn't request filter information, drop it now
6050            // so we don't have to marshall/unmarshall it.
6051            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6052                rii.filter = null;
6053            }
6054        }
6055
6056        // Filter out the caller activity if so requested.
6057        if (caller != null) {
6058            N = results.size();
6059            for (int i=0; i<N; i++) {
6060                ActivityInfo ainfo = results.get(i).activityInfo;
6061                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6062                        && caller.getClassName().equals(ainfo.name)) {
6063                    results.remove(i);
6064                    break;
6065                }
6066            }
6067        }
6068
6069        // If the caller didn't request filter information,
6070        // drop them now so we don't have to
6071        // marshall/unmarshall it.
6072        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6073            N = results.size();
6074            for (int i=0; i<N; i++) {
6075                results.get(i).filter = null;
6076            }
6077        }
6078
6079        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6080        return results;
6081    }
6082
6083    @Override
6084    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6085            String resolvedType, int flags, int userId) {
6086        return new ParceledListSlice<>(
6087                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6088    }
6089
6090    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6091            String resolvedType, int flags, int userId) {
6092        if (!sUserManager.exists(userId)) return Collections.emptyList();
6093        flags = updateFlagsForResolve(flags, userId, intent);
6094        ComponentName comp = intent.getComponent();
6095        if (comp == null) {
6096            if (intent.getSelector() != null) {
6097                intent = intent.getSelector();
6098                comp = intent.getComponent();
6099            }
6100        }
6101        if (comp != null) {
6102            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6103            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6104            if (ai != null) {
6105                ResolveInfo ri = new ResolveInfo();
6106                ri.activityInfo = ai;
6107                list.add(ri);
6108            }
6109            return list;
6110        }
6111
6112        // reader
6113        synchronized (mPackages) {
6114            String pkgName = intent.getPackage();
6115            if (pkgName == null) {
6116                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6117            }
6118            final PackageParser.Package pkg = mPackages.get(pkgName);
6119            if (pkg != null) {
6120                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6121                        userId);
6122            }
6123            return Collections.emptyList();
6124        }
6125    }
6126
6127    @Override
6128    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6129        if (!sUserManager.exists(userId)) return null;
6130        flags = updateFlagsForResolve(flags, userId, intent);
6131        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6132        if (query != null) {
6133            if (query.size() >= 1) {
6134                // If there is more than one service with the same priority,
6135                // just arbitrarily pick the first one.
6136                return query.get(0);
6137            }
6138        }
6139        return null;
6140    }
6141
6142    @Override
6143    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6144            String resolvedType, int flags, int userId) {
6145        return new ParceledListSlice<>(
6146                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6147    }
6148
6149    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6150            String resolvedType, int flags, int userId) {
6151        if (!sUserManager.exists(userId)) return Collections.emptyList();
6152        flags = updateFlagsForResolve(flags, userId, intent);
6153        ComponentName comp = intent.getComponent();
6154        if (comp == null) {
6155            if (intent.getSelector() != null) {
6156                intent = intent.getSelector();
6157                comp = intent.getComponent();
6158            }
6159        }
6160        if (comp != null) {
6161            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6162            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6163            if (si != null) {
6164                final ResolveInfo ri = new ResolveInfo();
6165                ri.serviceInfo = si;
6166                list.add(ri);
6167            }
6168            return list;
6169        }
6170
6171        // reader
6172        synchronized (mPackages) {
6173            String pkgName = intent.getPackage();
6174            if (pkgName == null) {
6175                return mServices.queryIntent(intent, resolvedType, flags, userId);
6176            }
6177            final PackageParser.Package pkg = mPackages.get(pkgName);
6178            if (pkg != null) {
6179                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6180                        userId);
6181            }
6182            return Collections.emptyList();
6183        }
6184    }
6185
6186    @Override
6187    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6188            String resolvedType, int flags, int userId) {
6189        return new ParceledListSlice<>(
6190                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6191    }
6192
6193    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6194            Intent intent, String resolvedType, int flags, int userId) {
6195        if (!sUserManager.exists(userId)) return Collections.emptyList();
6196        flags = updateFlagsForResolve(flags, userId, intent);
6197        ComponentName comp = intent.getComponent();
6198        if (comp == null) {
6199            if (intent.getSelector() != null) {
6200                intent = intent.getSelector();
6201                comp = intent.getComponent();
6202            }
6203        }
6204        if (comp != null) {
6205            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6206            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6207            if (pi != null) {
6208                final ResolveInfo ri = new ResolveInfo();
6209                ri.providerInfo = pi;
6210                list.add(ri);
6211            }
6212            return list;
6213        }
6214
6215        // reader
6216        synchronized (mPackages) {
6217            String pkgName = intent.getPackage();
6218            if (pkgName == null) {
6219                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6220            }
6221            final PackageParser.Package pkg = mPackages.get(pkgName);
6222            if (pkg != null) {
6223                return mProviders.queryIntentForPackage(
6224                        intent, resolvedType, flags, pkg.providers, userId);
6225            }
6226            return Collections.emptyList();
6227        }
6228    }
6229
6230    @Override
6231    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6232        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6233        flags = updateFlagsForPackage(flags, userId, null);
6234        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6235        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6236                true /* requireFullPermission */, false /* checkShell */,
6237                "get installed packages");
6238
6239        // writer
6240        synchronized (mPackages) {
6241            ArrayList<PackageInfo> list;
6242            if (listUninstalled) {
6243                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6244                for (PackageSetting ps : mSettings.mPackages.values()) {
6245                    final PackageInfo pi;
6246                    if (ps.pkg != null) {
6247                        pi = generatePackageInfo(ps, flags, userId);
6248                    } else {
6249                        pi = generatePackageInfo(ps, flags, userId);
6250                    }
6251                    if (pi != null) {
6252                        list.add(pi);
6253                    }
6254                }
6255            } else {
6256                list = new ArrayList<PackageInfo>(mPackages.size());
6257                for (PackageParser.Package p : mPackages.values()) {
6258                    final PackageInfo pi =
6259                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6260                    if (pi != null) {
6261                        list.add(pi);
6262                    }
6263                }
6264            }
6265
6266            return new ParceledListSlice<PackageInfo>(list);
6267        }
6268    }
6269
6270    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6271            String[] permissions, boolean[] tmp, int flags, int userId) {
6272        int numMatch = 0;
6273        final PermissionsState permissionsState = ps.getPermissionsState();
6274        for (int i=0; i<permissions.length; i++) {
6275            final String permission = permissions[i];
6276            if (permissionsState.hasPermission(permission, userId)) {
6277                tmp[i] = true;
6278                numMatch++;
6279            } else {
6280                tmp[i] = false;
6281            }
6282        }
6283        if (numMatch == 0) {
6284            return;
6285        }
6286        final PackageInfo pi;
6287        if (ps.pkg != null) {
6288            pi = generatePackageInfo(ps, flags, userId);
6289        } else {
6290            pi = generatePackageInfo(ps, flags, userId);
6291        }
6292        // The above might return null in cases of uninstalled apps or install-state
6293        // skew across users/profiles.
6294        if (pi != null) {
6295            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6296                if (numMatch == permissions.length) {
6297                    pi.requestedPermissions = permissions;
6298                } else {
6299                    pi.requestedPermissions = new String[numMatch];
6300                    numMatch = 0;
6301                    for (int i=0; i<permissions.length; i++) {
6302                        if (tmp[i]) {
6303                            pi.requestedPermissions[numMatch] = permissions[i];
6304                            numMatch++;
6305                        }
6306                    }
6307                }
6308            }
6309            list.add(pi);
6310        }
6311    }
6312
6313    @Override
6314    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6315            String[] permissions, int flags, int userId) {
6316        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6317        flags = updateFlagsForPackage(flags, userId, permissions);
6318        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6319
6320        // writer
6321        synchronized (mPackages) {
6322            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6323            boolean[] tmpBools = new boolean[permissions.length];
6324            if (listUninstalled) {
6325                for (PackageSetting ps : mSettings.mPackages.values()) {
6326                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6327                }
6328            } else {
6329                for (PackageParser.Package pkg : mPackages.values()) {
6330                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6331                    if (ps != null) {
6332                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6333                                userId);
6334                    }
6335                }
6336            }
6337
6338            return new ParceledListSlice<PackageInfo>(list);
6339        }
6340    }
6341
6342    @Override
6343    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6344        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6345        flags = updateFlagsForApplication(flags, userId, null);
6346        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6347
6348        // writer
6349        synchronized (mPackages) {
6350            ArrayList<ApplicationInfo> list;
6351            if (listUninstalled) {
6352                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6353                for (PackageSetting ps : mSettings.mPackages.values()) {
6354                    ApplicationInfo ai;
6355                    if (ps.pkg != null) {
6356                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6357                                ps.readUserState(userId), userId);
6358                    } else {
6359                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6360                    }
6361                    if (ai != null) {
6362                        list.add(ai);
6363                    }
6364                }
6365            } else {
6366                list = new ArrayList<ApplicationInfo>(mPackages.size());
6367                for (PackageParser.Package p : mPackages.values()) {
6368                    if (p.mExtras != null) {
6369                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6370                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6371                        if (ai != null) {
6372                            list.add(ai);
6373                        }
6374                    }
6375                }
6376            }
6377
6378            return new ParceledListSlice<ApplicationInfo>(list);
6379        }
6380    }
6381
6382    @Override
6383    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6384        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6385            return null;
6386        }
6387
6388        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6389                "getEphemeralApplications");
6390        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6391                true /* requireFullPermission */, false /* checkShell */,
6392                "getEphemeralApplications");
6393        synchronized (mPackages) {
6394            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6395                    .getEphemeralApplicationsLPw(userId);
6396            if (ephemeralApps != null) {
6397                return new ParceledListSlice<>(ephemeralApps);
6398            }
6399        }
6400        return null;
6401    }
6402
6403    @Override
6404    public boolean isEphemeralApplication(String packageName, int userId) {
6405        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6406                true /* requireFullPermission */, false /* checkShell */,
6407                "isEphemeral");
6408        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6409            return false;
6410        }
6411
6412        if (!isCallerSameApp(packageName)) {
6413            return false;
6414        }
6415        synchronized (mPackages) {
6416            PackageParser.Package pkg = mPackages.get(packageName);
6417            if (pkg != null) {
6418                return pkg.applicationInfo.isEphemeralApp();
6419            }
6420        }
6421        return false;
6422    }
6423
6424    @Override
6425    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6426        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6427            return null;
6428        }
6429
6430        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6431                true /* requireFullPermission */, false /* checkShell */,
6432                "getCookie");
6433        if (!isCallerSameApp(packageName)) {
6434            return null;
6435        }
6436        synchronized (mPackages) {
6437            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6438                    packageName, userId);
6439        }
6440    }
6441
6442    @Override
6443    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6444        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6445            return true;
6446        }
6447
6448        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6449                true /* requireFullPermission */, true /* checkShell */,
6450                "setCookie");
6451        if (!isCallerSameApp(packageName)) {
6452            return false;
6453        }
6454        synchronized (mPackages) {
6455            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6456                    packageName, cookie, userId);
6457        }
6458    }
6459
6460    @Override
6461    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6462        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6463            return null;
6464        }
6465
6466        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6467                "getEphemeralApplicationIcon");
6468        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6469                true /* requireFullPermission */, false /* checkShell */,
6470                "getEphemeralApplicationIcon");
6471        synchronized (mPackages) {
6472            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6473                    packageName, userId);
6474        }
6475    }
6476
6477    private boolean isCallerSameApp(String packageName) {
6478        PackageParser.Package pkg = mPackages.get(packageName);
6479        return pkg != null
6480                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6481    }
6482
6483    @Override
6484    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6485        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6486    }
6487
6488    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6489        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6490
6491        // reader
6492        synchronized (mPackages) {
6493            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6494            final int userId = UserHandle.getCallingUserId();
6495            while (i.hasNext()) {
6496                final PackageParser.Package p = i.next();
6497                if (p.applicationInfo == null) continue;
6498
6499                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6500                        && !p.applicationInfo.isDirectBootAware();
6501                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6502                        && p.applicationInfo.isDirectBootAware();
6503
6504                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6505                        && (!mSafeMode || isSystemApp(p))
6506                        && (matchesUnaware || matchesAware)) {
6507                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6508                    if (ps != null) {
6509                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6510                                ps.readUserState(userId), userId);
6511                        if (ai != null) {
6512                            finalList.add(ai);
6513                        }
6514                    }
6515                }
6516            }
6517        }
6518
6519        return finalList;
6520    }
6521
6522    @Override
6523    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6524        if (!sUserManager.exists(userId)) return null;
6525        flags = updateFlagsForComponent(flags, userId, name);
6526        // reader
6527        synchronized (mPackages) {
6528            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6529            PackageSetting ps = provider != null
6530                    ? mSettings.mPackages.get(provider.owner.packageName)
6531                    : null;
6532            return ps != null
6533                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6534                    ? PackageParser.generateProviderInfo(provider, flags,
6535                            ps.readUserState(userId), userId)
6536                    : null;
6537        }
6538    }
6539
6540    /**
6541     * @deprecated
6542     */
6543    @Deprecated
6544    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6545        // reader
6546        synchronized (mPackages) {
6547            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6548                    .entrySet().iterator();
6549            final int userId = UserHandle.getCallingUserId();
6550            while (i.hasNext()) {
6551                Map.Entry<String, PackageParser.Provider> entry = i.next();
6552                PackageParser.Provider p = entry.getValue();
6553                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6554
6555                if (ps != null && p.syncable
6556                        && (!mSafeMode || (p.info.applicationInfo.flags
6557                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6558                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6559                            ps.readUserState(userId), userId);
6560                    if (info != null) {
6561                        outNames.add(entry.getKey());
6562                        outInfo.add(info);
6563                    }
6564                }
6565            }
6566        }
6567    }
6568
6569    @Override
6570    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6571            int uid, int flags) {
6572        final int userId = processName != null ? UserHandle.getUserId(uid)
6573                : UserHandle.getCallingUserId();
6574        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6575        flags = updateFlagsForComponent(flags, userId, processName);
6576
6577        ArrayList<ProviderInfo> finalList = null;
6578        // reader
6579        synchronized (mPackages) {
6580            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6581            while (i.hasNext()) {
6582                final PackageParser.Provider p = i.next();
6583                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6584                if (ps != null && p.info.authority != null
6585                        && (processName == null
6586                                || (p.info.processName.equals(processName)
6587                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6588                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6589                    if (finalList == null) {
6590                        finalList = new ArrayList<ProviderInfo>(3);
6591                    }
6592                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6593                            ps.readUserState(userId), userId);
6594                    if (info != null) {
6595                        finalList.add(info);
6596                    }
6597                }
6598            }
6599        }
6600
6601        if (finalList != null) {
6602            Collections.sort(finalList, mProviderInitOrderSorter);
6603            return new ParceledListSlice<ProviderInfo>(finalList);
6604        }
6605
6606        return ParceledListSlice.emptyList();
6607    }
6608
6609    @Override
6610    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6611        // reader
6612        synchronized (mPackages) {
6613            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6614            return PackageParser.generateInstrumentationInfo(i, flags);
6615        }
6616    }
6617
6618    @Override
6619    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6620            String targetPackage, int flags) {
6621        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6622    }
6623
6624    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6625            int flags) {
6626        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6627
6628        // reader
6629        synchronized (mPackages) {
6630            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6631            while (i.hasNext()) {
6632                final PackageParser.Instrumentation p = i.next();
6633                if (targetPackage == null
6634                        || targetPackage.equals(p.info.targetPackage)) {
6635                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6636                            flags);
6637                    if (ii != null) {
6638                        finalList.add(ii);
6639                    }
6640                }
6641            }
6642        }
6643
6644        return finalList;
6645    }
6646
6647    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6648        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6649        if (overlays == null) {
6650            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6651            return;
6652        }
6653        for (PackageParser.Package opkg : overlays.values()) {
6654            // Not much to do if idmap fails: we already logged the error
6655            // and we certainly don't want to abort installation of pkg simply
6656            // because an overlay didn't fit properly. For these reasons,
6657            // ignore the return value of createIdmapForPackagePairLI.
6658            createIdmapForPackagePairLI(pkg, opkg);
6659        }
6660    }
6661
6662    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6663            PackageParser.Package opkg) {
6664        if (!opkg.mTrustedOverlay) {
6665            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6666                    opkg.baseCodePath + ": overlay not trusted");
6667            return false;
6668        }
6669        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6670        if (overlaySet == null) {
6671            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6672                    opkg.baseCodePath + " but target package has no known overlays");
6673            return false;
6674        }
6675        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6676        // TODO: generate idmap for split APKs
6677        try {
6678            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6679        } catch (InstallerException e) {
6680            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6681                    + opkg.baseCodePath);
6682            return false;
6683        }
6684        PackageParser.Package[] overlayArray =
6685            overlaySet.values().toArray(new PackageParser.Package[0]);
6686        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6687            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6688                return p1.mOverlayPriority - p2.mOverlayPriority;
6689            }
6690        };
6691        Arrays.sort(overlayArray, cmp);
6692
6693        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6694        int i = 0;
6695        for (PackageParser.Package p : overlayArray) {
6696            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6697        }
6698        return true;
6699    }
6700
6701    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6702        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6703        try {
6704            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6705        } finally {
6706            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6707        }
6708    }
6709
6710    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6711        final File[] files = dir.listFiles();
6712        if (ArrayUtils.isEmpty(files)) {
6713            Log.d(TAG, "No files in app dir " + dir);
6714            return;
6715        }
6716
6717        if (DEBUG_PACKAGE_SCANNING) {
6718            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6719                    + " flags=0x" + Integer.toHexString(parseFlags));
6720        }
6721
6722        for (File file : files) {
6723            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6724                    && !PackageInstallerService.isStageName(file.getName());
6725            if (!isPackage) {
6726                // Ignore entries which are not packages
6727                continue;
6728            }
6729            try {
6730                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6731                        scanFlags, currentTime, null);
6732            } catch (PackageManagerException e) {
6733                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6734
6735                // Delete invalid userdata apps
6736                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6737                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6738                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6739                    removeCodePathLI(file);
6740                }
6741            }
6742        }
6743    }
6744
6745    private static File getSettingsProblemFile() {
6746        File dataDir = Environment.getDataDirectory();
6747        File systemDir = new File(dataDir, "system");
6748        File fname = new File(systemDir, "uiderrors.txt");
6749        return fname;
6750    }
6751
6752    static void reportSettingsProblem(int priority, String msg) {
6753        logCriticalInfo(priority, msg);
6754    }
6755
6756    static void logCriticalInfo(int priority, String msg) {
6757        Slog.println(priority, TAG, msg);
6758        EventLogTags.writePmCriticalInfo(msg);
6759        try {
6760            File fname = getSettingsProblemFile();
6761            FileOutputStream out = new FileOutputStream(fname, true);
6762            PrintWriter pw = new FastPrintWriter(out);
6763            SimpleDateFormat formatter = new SimpleDateFormat();
6764            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6765            pw.println(dateString + ": " + msg);
6766            pw.close();
6767            FileUtils.setPermissions(
6768                    fname.toString(),
6769                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6770                    -1, -1);
6771        } catch (java.io.IOException e) {
6772        }
6773    }
6774
6775    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6776        if (srcFile.isDirectory()) {
6777            final File baseFile = new File(pkg.baseCodePath);
6778            long maxModifiedTime = baseFile.lastModified();
6779            if (pkg.splitCodePaths != null) {
6780                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6781                    final File splitFile = new File(pkg.splitCodePaths[i]);
6782                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6783                }
6784            }
6785            return maxModifiedTime;
6786        }
6787        return srcFile.lastModified();
6788    }
6789
6790    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6791            final int policyFlags) throws PackageManagerException {
6792        // When upgrading from pre-N MR1, verify the package time stamp using the package
6793        // directory and not the APK file.
6794        final long lastModifiedTime = mIsPreNMR1Upgrade
6795                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6796        if (ps != null
6797                && ps.codePath.equals(srcFile)
6798                && ps.timeStamp == lastModifiedTime
6799                && !isCompatSignatureUpdateNeeded(pkg)
6800                && !isRecoverSignatureUpdateNeeded(pkg)) {
6801            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6802            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6803            ArraySet<PublicKey> signingKs;
6804            synchronized (mPackages) {
6805                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6806            }
6807            if (ps.signatures.mSignatures != null
6808                    && ps.signatures.mSignatures.length != 0
6809                    && signingKs != null) {
6810                // Optimization: reuse the existing cached certificates
6811                // if the package appears to be unchanged.
6812                pkg.mSignatures = ps.signatures.mSignatures;
6813                pkg.mSigningKeys = signingKs;
6814                return;
6815            }
6816
6817            Slog.w(TAG, "PackageSetting for " + ps.name
6818                    + " is missing signatures.  Collecting certs again to recover them.");
6819        } else {
6820            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6821        }
6822
6823        try {
6824            PackageParser.collectCertificates(pkg, policyFlags);
6825        } catch (PackageParserException e) {
6826            throw PackageManagerException.from(e);
6827        }
6828    }
6829
6830    /**
6831     *  Traces a package scan.
6832     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6833     */
6834    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6835            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6836        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6837        try {
6838            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6839        } finally {
6840            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6841        }
6842    }
6843
6844    /**
6845     *  Scans a package and returns the newly parsed package.
6846     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6847     */
6848    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6849            long currentTime, UserHandle user) throws PackageManagerException {
6850        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6851        PackageParser pp = new PackageParser();
6852        pp.setSeparateProcesses(mSeparateProcesses);
6853        pp.setOnlyCoreApps(mOnlyCore);
6854        pp.setDisplayMetrics(mMetrics);
6855
6856        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6857            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6858        }
6859
6860        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6861        final PackageParser.Package pkg;
6862        try {
6863            pkg = pp.parsePackage(scanFile, parseFlags);
6864        } catch (PackageParserException e) {
6865            throw PackageManagerException.from(e);
6866        } finally {
6867            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6868        }
6869
6870        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6871    }
6872
6873    /**
6874     *  Scans a package and returns the newly parsed package.
6875     *  @throws PackageManagerException on a parse error.
6876     */
6877    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6878            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6879            throws PackageManagerException {
6880        // If the package has children and this is the first dive in the function
6881        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6882        // packages (parent and children) would be successfully scanned before the
6883        // actual scan since scanning mutates internal state and we want to atomically
6884        // install the package and its children.
6885        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6886            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6887                scanFlags |= SCAN_CHECK_ONLY;
6888            }
6889        } else {
6890            scanFlags &= ~SCAN_CHECK_ONLY;
6891        }
6892
6893        // Scan the parent
6894        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6895                scanFlags, currentTime, user);
6896
6897        // Scan the children
6898        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6899        for (int i = 0; i < childCount; i++) {
6900            PackageParser.Package childPackage = pkg.childPackages.get(i);
6901            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6902                    currentTime, user);
6903        }
6904
6905
6906        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6907            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6908        }
6909
6910        return scannedPkg;
6911    }
6912
6913    /**
6914     *  Scans a package and returns the newly parsed package.
6915     *  @throws PackageManagerException on a parse error.
6916     */
6917    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6918            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6919            throws PackageManagerException {
6920        PackageSetting ps = null;
6921        PackageSetting updatedPkg;
6922        // reader
6923        synchronized (mPackages) {
6924            // Look to see if we already know about this package.
6925            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6926            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6927                // This package has been renamed to its original name.  Let's
6928                // use that.
6929                ps = mSettings.peekPackageLPr(oldName);
6930            }
6931            // If there was no original package, see one for the real package name.
6932            if (ps == null) {
6933                ps = mSettings.peekPackageLPr(pkg.packageName);
6934            }
6935            // Check to see if this package could be hiding/updating a system
6936            // package.  Must look for it either under the original or real
6937            // package name depending on our state.
6938            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6939            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6940
6941            // If this is a package we don't know about on the system partition, we
6942            // may need to remove disabled child packages on the system partition
6943            // or may need to not add child packages if the parent apk is updated
6944            // on the data partition and no longer defines this child package.
6945            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6946                // If this is a parent package for an updated system app and this system
6947                // app got an OTA update which no longer defines some of the child packages
6948                // we have to prune them from the disabled system packages.
6949                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6950                if (disabledPs != null) {
6951                    final int scannedChildCount = (pkg.childPackages != null)
6952                            ? pkg.childPackages.size() : 0;
6953                    final int disabledChildCount = disabledPs.childPackageNames != null
6954                            ? disabledPs.childPackageNames.size() : 0;
6955                    for (int i = 0; i < disabledChildCount; i++) {
6956                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6957                        boolean disabledPackageAvailable = false;
6958                        for (int j = 0; j < scannedChildCount; j++) {
6959                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6960                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6961                                disabledPackageAvailable = true;
6962                                break;
6963                            }
6964                         }
6965                         if (!disabledPackageAvailable) {
6966                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6967                         }
6968                    }
6969                }
6970            }
6971        }
6972
6973        boolean updatedPkgBetter = false;
6974        // First check if this is a system package that may involve an update
6975        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6976            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6977            // it needs to drop FLAG_PRIVILEGED.
6978            if (locationIsPrivileged(scanFile)) {
6979                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6980            } else {
6981                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6982            }
6983
6984            if (ps != null && !ps.codePath.equals(scanFile)) {
6985                // The path has changed from what was last scanned...  check the
6986                // version of the new path against what we have stored to determine
6987                // what to do.
6988                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6989                if (pkg.mVersionCode <= ps.versionCode) {
6990                    // The system package has been updated and the code path does not match
6991                    // Ignore entry. Skip it.
6992                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6993                            + " ignored: updated version " + ps.versionCode
6994                            + " better than this " + pkg.mVersionCode);
6995                    if (!updatedPkg.codePath.equals(scanFile)) {
6996                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6997                                + ps.name + " changing from " + updatedPkg.codePathString
6998                                + " to " + scanFile);
6999                        updatedPkg.codePath = scanFile;
7000                        updatedPkg.codePathString = scanFile.toString();
7001                        updatedPkg.resourcePath = scanFile;
7002                        updatedPkg.resourcePathString = scanFile.toString();
7003                    }
7004                    updatedPkg.pkg = pkg;
7005                    updatedPkg.versionCode = pkg.mVersionCode;
7006
7007                    // Update the disabled system child packages to point to the package too.
7008                    final int childCount = updatedPkg.childPackageNames != null
7009                            ? updatedPkg.childPackageNames.size() : 0;
7010                    for (int i = 0; i < childCount; i++) {
7011                        String childPackageName = updatedPkg.childPackageNames.get(i);
7012                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7013                                childPackageName);
7014                        if (updatedChildPkg != null) {
7015                            updatedChildPkg.pkg = pkg;
7016                            updatedChildPkg.versionCode = pkg.mVersionCode;
7017                        }
7018                    }
7019
7020                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7021                            + scanFile + " ignored: updated version " + ps.versionCode
7022                            + " better than this " + pkg.mVersionCode);
7023                } else {
7024                    // The current app on the system partition is better than
7025                    // what we have updated to on the data partition; switch
7026                    // back to the system partition version.
7027                    // At this point, its safely assumed that package installation for
7028                    // apps in system partition will go through. If not there won't be a working
7029                    // version of the app
7030                    // writer
7031                    synchronized (mPackages) {
7032                        // Just remove the loaded entries from package lists.
7033                        mPackages.remove(ps.name);
7034                    }
7035
7036                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7037                            + " reverting from " + ps.codePathString
7038                            + ": new version " + pkg.mVersionCode
7039                            + " better than installed " + ps.versionCode);
7040
7041                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7042                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7043                    synchronized (mInstallLock) {
7044                        args.cleanUpResourcesLI();
7045                    }
7046                    synchronized (mPackages) {
7047                        mSettings.enableSystemPackageLPw(ps.name);
7048                    }
7049                    updatedPkgBetter = true;
7050                }
7051            }
7052        }
7053
7054        if (updatedPkg != null) {
7055            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7056            // initially
7057            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7058
7059            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7060            // flag set initially
7061            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7062                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7063            }
7064        }
7065
7066        // Verify certificates against what was last scanned
7067        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7068
7069        /*
7070         * A new system app appeared, but we already had a non-system one of the
7071         * same name installed earlier.
7072         */
7073        boolean shouldHideSystemApp = false;
7074        if (updatedPkg == null && ps != null
7075                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7076            /*
7077             * Check to make sure the signatures match first. If they don't,
7078             * wipe the installed application and its data.
7079             */
7080            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7081                    != PackageManager.SIGNATURE_MATCH) {
7082                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7083                        + " signatures don't match existing userdata copy; removing");
7084                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7085                        "scanPackageInternalLI")) {
7086                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7087                }
7088                ps = null;
7089            } else {
7090                /*
7091                 * If the newly-added system app is an older version than the
7092                 * already installed version, hide it. It will be scanned later
7093                 * and re-added like an update.
7094                 */
7095                if (pkg.mVersionCode <= ps.versionCode) {
7096                    shouldHideSystemApp = true;
7097                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7098                            + " but new version " + pkg.mVersionCode + " better than installed "
7099                            + ps.versionCode + "; hiding system");
7100                } else {
7101                    /*
7102                     * The newly found system app is a newer version that the
7103                     * one previously installed. Simply remove the
7104                     * already-installed application and replace it with our own
7105                     * while keeping the application data.
7106                     */
7107                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7108                            + " reverting from " + ps.codePathString + ": new version "
7109                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7110                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7111                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7112                    synchronized (mInstallLock) {
7113                        args.cleanUpResourcesLI();
7114                    }
7115                }
7116            }
7117        }
7118
7119        // The apk is forward locked (not public) if its code and resources
7120        // are kept in different files. (except for app in either system or
7121        // vendor path).
7122        // TODO grab this value from PackageSettings
7123        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7124            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7125                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7126            }
7127        }
7128
7129        // TODO: extend to support forward-locked splits
7130        String resourcePath = null;
7131        String baseResourcePath = null;
7132        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7133            if (ps != null && ps.resourcePathString != null) {
7134                resourcePath = ps.resourcePathString;
7135                baseResourcePath = ps.resourcePathString;
7136            } else {
7137                // Should not happen at all. Just log an error.
7138                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7139            }
7140        } else {
7141            resourcePath = pkg.codePath;
7142            baseResourcePath = pkg.baseCodePath;
7143        }
7144
7145        // Set application objects path explicitly.
7146        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7147        pkg.setApplicationInfoCodePath(pkg.codePath);
7148        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7149        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7150        pkg.setApplicationInfoResourcePath(resourcePath);
7151        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7152        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7153
7154        // Note that we invoke the following method only if we are about to unpack an application
7155        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7156                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7157
7158        /*
7159         * If the system app should be overridden by a previously installed
7160         * data, hide the system app now and let the /data/app scan pick it up
7161         * again.
7162         */
7163        if (shouldHideSystemApp) {
7164            synchronized (mPackages) {
7165                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7166            }
7167        }
7168
7169        return scannedPkg;
7170    }
7171
7172    private static String fixProcessName(String defProcessName,
7173            String processName, int uid) {
7174        if (processName == null) {
7175            return defProcessName;
7176        }
7177        return processName;
7178    }
7179
7180    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7181            throws PackageManagerException {
7182        if (pkgSetting.signatures.mSignatures != null) {
7183            // Already existing package. Make sure signatures match
7184            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7185                    == PackageManager.SIGNATURE_MATCH;
7186            if (!match) {
7187                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7188                        == PackageManager.SIGNATURE_MATCH;
7189            }
7190            if (!match) {
7191                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7192                        == PackageManager.SIGNATURE_MATCH;
7193            }
7194            if (!match) {
7195                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7196                        + pkg.packageName + " signatures do not match the "
7197                        + "previously installed version; ignoring!");
7198            }
7199        }
7200
7201        // Check for shared user signatures
7202        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7203            // Already existing package. Make sure signatures match
7204            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7205                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7206            if (!match) {
7207                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7208                        == PackageManager.SIGNATURE_MATCH;
7209            }
7210            if (!match) {
7211                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7212                        == PackageManager.SIGNATURE_MATCH;
7213            }
7214            if (!match) {
7215                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7216                        "Package " + pkg.packageName
7217                        + " has no signatures that match those in shared user "
7218                        + pkgSetting.sharedUser.name + "; ignoring!");
7219            }
7220        }
7221    }
7222
7223    /**
7224     * Enforces that only the system UID or root's UID can call a method exposed
7225     * via Binder.
7226     *
7227     * @param message used as message if SecurityException is thrown
7228     * @throws SecurityException if the caller is not system or root
7229     */
7230    private static final void enforceSystemOrRoot(String message) {
7231        final int uid = Binder.getCallingUid();
7232        if (uid != Process.SYSTEM_UID && uid != 0) {
7233            throw new SecurityException(message);
7234        }
7235    }
7236
7237    @Override
7238    public void performFstrimIfNeeded() {
7239        enforceSystemOrRoot("Only the system can request fstrim");
7240
7241        // Before everything else, see whether we need to fstrim.
7242        try {
7243            IMountService ms = PackageHelper.getMountService();
7244            if (ms != null) {
7245                boolean doTrim = false;
7246                final long interval = android.provider.Settings.Global.getLong(
7247                        mContext.getContentResolver(),
7248                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7249                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7250                if (interval > 0) {
7251                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7252                    if (timeSinceLast > interval) {
7253                        doTrim = true;
7254                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7255                                + "; running immediately");
7256                    }
7257                }
7258                if (doTrim) {
7259                    final boolean dexOptDialogShown;
7260                    synchronized (mPackages) {
7261                        dexOptDialogShown = mDexOptDialogShown;
7262                    }
7263                    if (!isFirstBoot() && dexOptDialogShown) {
7264                        try {
7265                            ActivityManagerNative.getDefault().showBootMessage(
7266                                    mContext.getResources().getString(
7267                                            R.string.android_upgrading_fstrim), true);
7268                        } catch (RemoteException e) {
7269                        }
7270                    }
7271                    ms.runMaintenance();
7272                }
7273            } else {
7274                Slog.e(TAG, "Mount service unavailable!");
7275            }
7276        } catch (RemoteException e) {
7277            // Can't happen; MountService is local
7278        }
7279    }
7280
7281    @Override
7282    public void updatePackagesIfNeeded() {
7283        enforceSystemOrRoot("Only the system can request package update");
7284
7285        // We need to re-extract after an OTA.
7286        boolean causeUpgrade = isUpgrade();
7287
7288        // First boot or factory reset.
7289        // Note: we also handle devices that are upgrading to N right now as if it is their
7290        //       first boot, as they do not have profile data.
7291        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7292
7293        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7294        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7295
7296        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7297            return;
7298        }
7299
7300        List<PackageParser.Package> pkgs;
7301        synchronized (mPackages) {
7302            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7303        }
7304
7305        final long startTime = System.nanoTime();
7306        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7307                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7308
7309        final int elapsedTimeSeconds =
7310                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7311
7312        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7313        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7314        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7315        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7316        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7317    }
7318
7319    /**
7320     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7321     * containing statistics about the invocation. The array consists of three elements,
7322     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7323     * and {@code numberOfPackagesFailed}.
7324     */
7325    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7326            String compilerFilter) {
7327
7328        int numberOfPackagesVisited = 0;
7329        int numberOfPackagesOptimized = 0;
7330        int numberOfPackagesSkipped = 0;
7331        int numberOfPackagesFailed = 0;
7332        final int numberOfPackagesToDexopt = pkgs.size();
7333
7334        for (PackageParser.Package pkg : pkgs) {
7335            numberOfPackagesVisited++;
7336
7337            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7338                if (DEBUG_DEXOPT) {
7339                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7340                }
7341                numberOfPackagesSkipped++;
7342                continue;
7343            }
7344
7345            if (DEBUG_DEXOPT) {
7346                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7347                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7348            }
7349
7350            if (showDialog) {
7351                try {
7352                    ActivityManagerNative.getDefault().showBootMessage(
7353                            mContext.getResources().getString(R.string.android_upgrading_apk,
7354                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7355                } catch (RemoteException e) {
7356                }
7357                synchronized (mPackages) {
7358                    mDexOptDialogShown = true;
7359                }
7360            }
7361
7362            // If the OTA updates a system app which was previously preopted to a non-preopted state
7363            // the app might end up being verified at runtime. That's because by default the apps
7364            // are verify-profile but for preopted apps there's no profile.
7365            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7366            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7367            // filter (by default 'quicken').
7368            // Note that at this stage unused apps are already filtered.
7369            if (isSystemApp(pkg) &&
7370                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7371                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7372                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7373            }
7374
7375            // checkProfiles is false to avoid merging profiles during boot which
7376            // might interfere with background compilation (b/28612421).
7377            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7378            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7379            // trade-off worth doing to save boot time work.
7380            int dexOptStatus = performDexOptTraced(pkg.packageName,
7381                    false /* checkProfiles */,
7382                    compilerFilter,
7383                    false /* force */);
7384            switch (dexOptStatus) {
7385                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7386                    numberOfPackagesOptimized++;
7387                    break;
7388                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7389                    numberOfPackagesSkipped++;
7390                    break;
7391                case PackageDexOptimizer.DEX_OPT_FAILED:
7392                    numberOfPackagesFailed++;
7393                    break;
7394                default:
7395                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7396                    break;
7397            }
7398        }
7399
7400        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7401                numberOfPackagesFailed };
7402    }
7403
7404    @Override
7405    public void notifyPackageUse(String packageName, int reason) {
7406        synchronized (mPackages) {
7407            PackageParser.Package p = mPackages.get(packageName);
7408            if (p == null) {
7409                return;
7410            }
7411            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7412        }
7413    }
7414
7415    @Override
7416    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
7417        int userId = UserHandle.getCallingUserId();
7418        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
7419        if (ai == null) {
7420            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
7421                + loadingPackageName + ", user=" + userId);
7422            return;
7423        }
7424        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
7425    }
7426
7427    // TODO: this is not used nor needed. Delete it.
7428    @Override
7429    public boolean performDexOptIfNeeded(String packageName) {
7430        int dexOptStatus = performDexOptTraced(packageName,
7431                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7432        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7433    }
7434
7435    @Override
7436    public boolean performDexOpt(String packageName,
7437            boolean checkProfiles, int compileReason, boolean force) {
7438        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7439                getCompilerFilterForReason(compileReason), force);
7440        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7441    }
7442
7443    @Override
7444    public boolean performDexOptMode(String packageName,
7445            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7446        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7447                targetCompilerFilter, force);
7448        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7449    }
7450
7451    private int performDexOptTraced(String packageName,
7452                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7453        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7454        try {
7455            return performDexOptInternal(packageName, checkProfiles,
7456                    targetCompilerFilter, force);
7457        } finally {
7458            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7459        }
7460    }
7461
7462    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7463    // if the package can now be considered up to date for the given filter.
7464    private int performDexOptInternal(String packageName,
7465                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7466        PackageParser.Package p;
7467        synchronized (mPackages) {
7468            p = mPackages.get(packageName);
7469            if (p == null) {
7470                // Package could not be found. Report failure.
7471                return PackageDexOptimizer.DEX_OPT_FAILED;
7472            }
7473            mPackageUsage.maybeWriteAsync(mPackages);
7474            mCompilerStats.maybeWriteAsync();
7475        }
7476        long callingId = Binder.clearCallingIdentity();
7477        try {
7478            synchronized (mInstallLock) {
7479                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7480                        targetCompilerFilter, force);
7481            }
7482        } finally {
7483            Binder.restoreCallingIdentity(callingId);
7484        }
7485    }
7486
7487    public ArraySet<String> getOptimizablePackages() {
7488        ArraySet<String> pkgs = new ArraySet<String>();
7489        synchronized (mPackages) {
7490            for (PackageParser.Package p : mPackages.values()) {
7491                if (PackageDexOptimizer.canOptimizePackage(p)) {
7492                    pkgs.add(p.packageName);
7493                }
7494            }
7495        }
7496        return pkgs;
7497    }
7498
7499    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7500            boolean checkProfiles, String targetCompilerFilter,
7501            boolean force) {
7502        // Select the dex optimizer based on the force parameter.
7503        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7504        //       allocate an object here.
7505        PackageDexOptimizer pdo = force
7506                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7507                : mPackageDexOptimizer;
7508
7509        // Optimize all dependencies first. Note: we ignore the return value and march on
7510        // on errors.
7511        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7512        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7513        if (!deps.isEmpty()) {
7514            for (PackageParser.Package depPackage : deps) {
7515                // TODO: Analyze and investigate if we (should) profile libraries.
7516                // Currently this will do a full compilation of the library by default.
7517                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7518                        false /* checkProfiles */,
7519                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7520                        getOrCreateCompilerPackageStats(depPackage),
7521                        mDexManager.isUsedByOtherApps(p.packageName));
7522            }
7523        }
7524        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7525                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
7526                mDexManager.isUsedByOtherApps(p.packageName));
7527    }
7528
7529    // Performs dexopt on the used secondary dex files belonging to the given package.
7530    // Returns true if all dex files were process successfully (which could mean either dexopt or
7531    // skip). Returns false if any of the files caused errors.
7532    @Override
7533    public boolean performDexOptSecondary(String packageName, String compilerFilter,
7534            boolean force) {
7535        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
7536    }
7537
7538    public boolean performDexOptSecondary(String packageName, int compileReason,
7539            boolean force) {
7540        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
7541    }
7542
7543    /**
7544     * Reconcile the information we have about the secondary dex files belonging to
7545     * {@code packagName} and the actual dex files. For all dex files that were
7546     * deleted, update the internal records and delete the generated oat files.
7547     */
7548    @Override
7549    public void reconcileSecondaryDexFiles(String packageName) {
7550        mDexManager.reconcileSecondaryDexFiles(packageName);
7551    }
7552
7553    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
7554    // a reference there.
7555    /*package*/ DexManager getDexManager() {
7556        return mDexManager;
7557    }
7558
7559    /**
7560     * Execute the background dexopt job immediately.
7561     */
7562    @Override
7563    public boolean runBackgroundDexoptJob() {
7564        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
7565    }
7566
7567    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7568        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7569            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7570            Set<String> collectedNames = new HashSet<>();
7571            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7572
7573            retValue.remove(p);
7574
7575            return retValue;
7576        } else {
7577            return Collections.emptyList();
7578        }
7579    }
7580
7581    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7582            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7583        if (!collectedNames.contains(p.packageName)) {
7584            collectedNames.add(p.packageName);
7585            collected.add(p);
7586
7587            if (p.usesLibraries != null) {
7588                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7589            }
7590            if (p.usesOptionalLibraries != null) {
7591                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7592                        collectedNames);
7593            }
7594        }
7595    }
7596
7597    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7598            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7599        for (String libName : libs) {
7600            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7601            if (libPkg != null) {
7602                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7603            }
7604        }
7605    }
7606
7607    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7608        synchronized (mPackages) {
7609            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7610            if (lib != null && lib.apk != null) {
7611                return mPackages.get(lib.apk);
7612            }
7613        }
7614        return null;
7615    }
7616
7617    public void shutdown() {
7618        mPackageUsage.writeNow(mPackages);
7619        mCompilerStats.writeNow();
7620    }
7621
7622    @Override
7623    public void dumpProfiles(String packageName) {
7624        PackageParser.Package pkg;
7625        synchronized (mPackages) {
7626            pkg = mPackages.get(packageName);
7627            if (pkg == null) {
7628                throw new IllegalArgumentException("Unknown package: " + packageName);
7629            }
7630        }
7631        /* Only the shell, root, or the app user should be able to dump profiles. */
7632        int callingUid = Binder.getCallingUid();
7633        if (callingUid != Process.SHELL_UID &&
7634            callingUid != Process.ROOT_UID &&
7635            callingUid != pkg.applicationInfo.uid) {
7636            throw new SecurityException("dumpProfiles");
7637        }
7638
7639        synchronized (mInstallLock) {
7640            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7641            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7642            try {
7643                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7644                String codePaths = TextUtils.join(";", allCodePaths);
7645                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
7646            } catch (InstallerException e) {
7647                Slog.w(TAG, "Failed to dump profiles", e);
7648            }
7649            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7650        }
7651    }
7652
7653    @Override
7654    public void forceDexOpt(String packageName) {
7655        enforceSystemOrRoot("forceDexOpt");
7656
7657        PackageParser.Package pkg;
7658        synchronized (mPackages) {
7659            pkg = mPackages.get(packageName);
7660            if (pkg == null) {
7661                throw new IllegalArgumentException("Unknown package: " + packageName);
7662            }
7663        }
7664
7665        synchronized (mInstallLock) {
7666            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7667
7668            // Whoever is calling forceDexOpt wants a fully compiled package.
7669            // Don't use profiles since that may cause compilation to be skipped.
7670            final int res = performDexOptInternalWithDependenciesLI(pkg,
7671                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7672                    true /* force */);
7673
7674            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7675            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7676                throw new IllegalStateException("Failed to dexopt: " + res);
7677            }
7678        }
7679    }
7680
7681    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7682        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7683            Slog.w(TAG, "Unable to update from " + oldPkg.name
7684                    + " to " + newPkg.packageName
7685                    + ": old package not in system partition");
7686            return false;
7687        } else if (mPackages.get(oldPkg.name) != null) {
7688            Slog.w(TAG, "Unable to update from " + oldPkg.name
7689                    + " to " + newPkg.packageName
7690                    + ": old package still exists");
7691            return false;
7692        }
7693        return true;
7694    }
7695
7696    void removeCodePathLI(File codePath) {
7697        if (codePath.isDirectory()) {
7698            try {
7699                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7700            } catch (InstallerException e) {
7701                Slog.w(TAG, "Failed to remove code path", e);
7702            }
7703        } else {
7704            codePath.delete();
7705        }
7706    }
7707
7708    private int[] resolveUserIds(int userId) {
7709        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7710    }
7711
7712    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7713        if (pkg == null) {
7714            Slog.wtf(TAG, "Package was null!", new Throwable());
7715            return;
7716        }
7717        clearAppDataLeafLIF(pkg, userId, flags);
7718        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7719        for (int i = 0; i < childCount; i++) {
7720            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7721        }
7722    }
7723
7724    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7725        final PackageSetting ps;
7726        synchronized (mPackages) {
7727            ps = mSettings.mPackages.get(pkg.packageName);
7728        }
7729        for (int realUserId : resolveUserIds(userId)) {
7730            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7731            try {
7732                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7733                        ceDataInode);
7734            } catch (InstallerException e) {
7735                Slog.w(TAG, String.valueOf(e));
7736            }
7737        }
7738    }
7739
7740    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7741        if (pkg == null) {
7742            Slog.wtf(TAG, "Package was null!", new Throwable());
7743            return;
7744        }
7745        destroyAppDataLeafLIF(pkg, userId, flags);
7746        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7747        for (int i = 0; i < childCount; i++) {
7748            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7749        }
7750    }
7751
7752    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7753        final PackageSetting ps;
7754        synchronized (mPackages) {
7755            ps = mSettings.mPackages.get(pkg.packageName);
7756        }
7757        for (int realUserId : resolveUserIds(userId)) {
7758            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7759            try {
7760                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7761                        ceDataInode);
7762            } catch (InstallerException e) {
7763                Slog.w(TAG, String.valueOf(e));
7764            }
7765            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
7766        }
7767    }
7768
7769    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7770        if (pkg == null) {
7771            Slog.wtf(TAG, "Package was null!", new Throwable());
7772            return;
7773        }
7774        destroyAppProfilesLeafLIF(pkg);
7775        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7776        for (int i = 0; i < childCount; i++) {
7777            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7778        }
7779    }
7780
7781    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7782        try {
7783            mInstaller.destroyAppProfiles(pkg.packageName);
7784        } catch (InstallerException e) {
7785            Slog.w(TAG, String.valueOf(e));
7786        }
7787    }
7788
7789    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7790        if (pkg == null) {
7791            Slog.wtf(TAG, "Package was null!", new Throwable());
7792            return;
7793        }
7794        clearAppProfilesLeafLIF(pkg);
7795        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7796        for (int i = 0; i < childCount; i++) {
7797            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7798        }
7799    }
7800
7801    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7802        try {
7803            mInstaller.clearAppProfiles(pkg.packageName);
7804        } catch (InstallerException e) {
7805            Slog.w(TAG, String.valueOf(e));
7806        }
7807    }
7808
7809    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7810            long lastUpdateTime) {
7811        // Set parent install/update time
7812        PackageSetting ps = (PackageSetting) pkg.mExtras;
7813        if (ps != null) {
7814            ps.firstInstallTime = firstInstallTime;
7815            ps.lastUpdateTime = lastUpdateTime;
7816        }
7817        // Set children install/update time
7818        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7819        for (int i = 0; i < childCount; i++) {
7820            PackageParser.Package childPkg = pkg.childPackages.get(i);
7821            ps = (PackageSetting) childPkg.mExtras;
7822            if (ps != null) {
7823                ps.firstInstallTime = firstInstallTime;
7824                ps.lastUpdateTime = lastUpdateTime;
7825            }
7826        }
7827    }
7828
7829    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7830            PackageParser.Package changingLib) {
7831        if (file.path != null) {
7832            usesLibraryFiles.add(file.path);
7833            return;
7834        }
7835        PackageParser.Package p = mPackages.get(file.apk);
7836        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7837            // If we are doing this while in the middle of updating a library apk,
7838            // then we need to make sure to use that new apk for determining the
7839            // dependencies here.  (We haven't yet finished committing the new apk
7840            // to the package manager state.)
7841            if (p == null || p.packageName.equals(changingLib.packageName)) {
7842                p = changingLib;
7843            }
7844        }
7845        if (p != null) {
7846            usesLibraryFiles.addAll(p.getAllCodePaths());
7847        }
7848    }
7849
7850    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7851            PackageParser.Package changingLib) throws PackageManagerException {
7852        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7853            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7854            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7855            for (int i=0; i<N; i++) {
7856                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7857                if (file == null) {
7858                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7859                            "Package " + pkg.packageName + " requires unavailable shared library "
7860                            + pkg.usesLibraries.get(i) + "; failing!");
7861                }
7862                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7863            }
7864            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7865            for (int i=0; i<N; i++) {
7866                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7867                if (file == null) {
7868                    Slog.w(TAG, "Package " + pkg.packageName
7869                            + " desires unavailable shared library "
7870                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7871                } else {
7872                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7873                }
7874            }
7875            N = usesLibraryFiles.size();
7876            if (N > 0) {
7877                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7878            } else {
7879                pkg.usesLibraryFiles = null;
7880            }
7881        }
7882    }
7883
7884    private static boolean hasString(List<String> list, List<String> which) {
7885        if (list == null) {
7886            return false;
7887        }
7888        for (int i=list.size()-1; i>=0; i--) {
7889            for (int j=which.size()-1; j>=0; j--) {
7890                if (which.get(j).equals(list.get(i))) {
7891                    return true;
7892                }
7893            }
7894        }
7895        return false;
7896    }
7897
7898    private void updateAllSharedLibrariesLPw() {
7899        for (PackageParser.Package pkg : mPackages.values()) {
7900            try {
7901                updateSharedLibrariesLPw(pkg, null);
7902            } catch (PackageManagerException e) {
7903                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7904            }
7905        }
7906    }
7907
7908    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7909            PackageParser.Package changingPkg) {
7910        ArrayList<PackageParser.Package> res = null;
7911        for (PackageParser.Package pkg : mPackages.values()) {
7912            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7913                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7914                if (res == null) {
7915                    res = new ArrayList<PackageParser.Package>();
7916                }
7917                res.add(pkg);
7918                try {
7919                    updateSharedLibrariesLPw(pkg, changingPkg);
7920                } catch (PackageManagerException e) {
7921                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7922                }
7923            }
7924        }
7925        return res;
7926    }
7927
7928    /**
7929     * Derive the value of the {@code cpuAbiOverride} based on the provided
7930     * value and an optional stored value from the package settings.
7931     */
7932    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7933        String cpuAbiOverride = null;
7934
7935        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7936            cpuAbiOverride = null;
7937        } else if (abiOverride != null) {
7938            cpuAbiOverride = abiOverride;
7939        } else if (settings != null) {
7940            cpuAbiOverride = settings.cpuAbiOverrideString;
7941        }
7942
7943        return cpuAbiOverride;
7944    }
7945
7946    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7947            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7948                    throws PackageManagerException {
7949        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7950        // If the package has children and this is the first dive in the function
7951        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7952        // whether all packages (parent and children) would be successfully scanned
7953        // before the actual scan since scanning mutates internal state and we want
7954        // to atomically install the package and its children.
7955        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7956            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7957                scanFlags |= SCAN_CHECK_ONLY;
7958            }
7959        } else {
7960            scanFlags &= ~SCAN_CHECK_ONLY;
7961        }
7962
7963        final PackageParser.Package scannedPkg;
7964        try {
7965            // Scan the parent
7966            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7967            // Scan the children
7968            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7969            for (int i = 0; i < childCount; i++) {
7970                PackageParser.Package childPkg = pkg.childPackages.get(i);
7971                scanPackageLI(childPkg, policyFlags,
7972                        scanFlags, currentTime, user);
7973            }
7974        } finally {
7975            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7976        }
7977
7978        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7979            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7980        }
7981
7982        return scannedPkg;
7983    }
7984
7985    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7986            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7987        boolean success = false;
7988        try {
7989            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7990                    currentTime, user);
7991            success = true;
7992            return res;
7993        } finally {
7994            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7995                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7996                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7997                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7998                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7999            }
8000        }
8001    }
8002
8003    /**
8004     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8005     */
8006    private static boolean apkHasCode(String fileName) {
8007        StrictJarFile jarFile = null;
8008        try {
8009            jarFile = new StrictJarFile(fileName,
8010                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8011            return jarFile.findEntry("classes.dex") != null;
8012        } catch (IOException ignore) {
8013        } finally {
8014            try {
8015                if (jarFile != null) {
8016                    jarFile.close();
8017                }
8018            } catch (IOException ignore) {}
8019        }
8020        return false;
8021    }
8022
8023    /**
8024     * Enforces code policy for the package. This ensures that if an APK has
8025     * declared hasCode="true" in its manifest that the APK actually contains
8026     * code.
8027     *
8028     * @throws PackageManagerException If bytecode could not be found when it should exist
8029     */
8030    private static void enforceCodePolicy(PackageParser.Package pkg)
8031            throws PackageManagerException {
8032        final boolean shouldHaveCode =
8033                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8034        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8035            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8036                    "Package " + pkg.baseCodePath + " code is missing");
8037        }
8038
8039        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8040            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8041                final boolean splitShouldHaveCode =
8042                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8043                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8044                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8045                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8046                }
8047            }
8048        }
8049    }
8050
8051    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8052            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8053            throws PackageManagerException {
8054        final File scanFile = new File(pkg.codePath);
8055        if (pkg.applicationInfo.getCodePath() == null ||
8056                pkg.applicationInfo.getResourcePath() == null) {
8057            // Bail out. The resource and code paths haven't been set.
8058            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8059                    "Code and resource paths haven't been set correctly");
8060        }
8061
8062        // Apply policy
8063        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8064            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8065            if (pkg.applicationInfo.isDirectBootAware()) {
8066                // we're direct boot aware; set for all components
8067                for (PackageParser.Service s : pkg.services) {
8068                    s.info.encryptionAware = s.info.directBootAware = true;
8069                }
8070                for (PackageParser.Provider p : pkg.providers) {
8071                    p.info.encryptionAware = p.info.directBootAware = true;
8072                }
8073                for (PackageParser.Activity a : pkg.activities) {
8074                    a.info.encryptionAware = a.info.directBootAware = true;
8075                }
8076                for (PackageParser.Activity r : pkg.receivers) {
8077                    r.info.encryptionAware = r.info.directBootAware = true;
8078                }
8079            }
8080        } else {
8081            // Only allow system apps to be flagged as core apps.
8082            pkg.coreApp = false;
8083            // clear flags not applicable to regular apps
8084            pkg.applicationInfo.privateFlags &=
8085                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8086            pkg.applicationInfo.privateFlags &=
8087                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8088        }
8089        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8090
8091        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8092            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8093        }
8094
8095        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8096            enforceCodePolicy(pkg);
8097        }
8098
8099        if (mCustomResolverComponentName != null &&
8100                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8101            setUpCustomResolverActivity(pkg);
8102        }
8103
8104        if (pkg.packageName.equals("android")) {
8105            synchronized (mPackages) {
8106                if (mAndroidApplication != null) {
8107                    Slog.w(TAG, "*************************************************");
8108                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8109                    Slog.w(TAG, " file=" + scanFile);
8110                    Slog.w(TAG, "*************************************************");
8111                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8112                            "Core android package being redefined.  Skipping.");
8113                }
8114
8115                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8116                    // Set up information for our fall-back user intent resolution activity.
8117                    mPlatformPackage = pkg;
8118                    pkg.mVersionCode = mSdkVersion;
8119                    mAndroidApplication = pkg.applicationInfo;
8120
8121                    if (!mResolverReplaced) {
8122                        mResolveActivity.applicationInfo = mAndroidApplication;
8123                        mResolveActivity.name = ResolverActivity.class.getName();
8124                        mResolveActivity.packageName = mAndroidApplication.packageName;
8125                        mResolveActivity.processName = "system:ui";
8126                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8127                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8128                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8129                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8130                        mResolveActivity.exported = true;
8131                        mResolveActivity.enabled = true;
8132                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8133                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8134                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8135                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8136                                | ActivityInfo.CONFIG_ORIENTATION
8137                                | ActivityInfo.CONFIG_KEYBOARD
8138                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8139                        mResolveInfo.activityInfo = mResolveActivity;
8140                        mResolveInfo.priority = 0;
8141                        mResolveInfo.preferredOrder = 0;
8142                        mResolveInfo.match = 0;
8143                        mResolveComponentName = new ComponentName(
8144                                mAndroidApplication.packageName, mResolveActivity.name);
8145                    }
8146                }
8147            }
8148        }
8149
8150        if (DEBUG_PACKAGE_SCANNING) {
8151            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8152                Log.d(TAG, "Scanning package " + pkg.packageName);
8153        }
8154
8155        synchronized (mPackages) {
8156            if (mPackages.containsKey(pkg.packageName)
8157                    || mSharedLibraries.containsKey(pkg.packageName)) {
8158                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8159                        "Application package " + pkg.packageName
8160                                + " already installed.  Skipping duplicate.");
8161            }
8162
8163            // If we're only installing presumed-existing packages, require that the
8164            // scanned APK is both already known and at the path previously established
8165            // for it.  Previously unknown packages we pick up normally, but if we have an
8166            // a priori expectation about this package's install presence, enforce it.
8167            // With a singular exception for new system packages. When an OTA contains
8168            // a new system package, we allow the codepath to change from a system location
8169            // to the user-installed location. If we don't allow this change, any newer,
8170            // user-installed version of the application will be ignored.
8171            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8172                if (mExpectingBetter.containsKey(pkg.packageName)) {
8173                    logCriticalInfo(Log.WARN,
8174                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8175                } else {
8176                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8177                    if (known != null) {
8178                        if (DEBUG_PACKAGE_SCANNING) {
8179                            Log.d(TAG, "Examining " + pkg.codePath
8180                                    + " and requiring known paths " + known.codePathString
8181                                    + " & " + known.resourcePathString);
8182                        }
8183                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8184                                || !pkg.applicationInfo.getResourcePath().equals(
8185                                known.resourcePathString)) {
8186                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8187                                    "Application package " + pkg.packageName
8188                                            + " found at " + pkg.applicationInfo.getCodePath()
8189                                            + " but expected at " + known.codePathString
8190                                            + "; ignoring.");
8191                        }
8192                    }
8193                }
8194            }
8195        }
8196
8197        // Initialize package source and resource directories
8198        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8199        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8200
8201        SharedUserSetting suid = null;
8202        PackageSetting pkgSetting = null;
8203
8204        if (!isSystemApp(pkg)) {
8205            // Only system apps can use these features.
8206            pkg.mOriginalPackages = null;
8207            pkg.mRealPackage = null;
8208            pkg.mAdoptPermissions = null;
8209        }
8210
8211        // Getting the package setting may have a side-effect, so if we
8212        // are only checking if scan would succeed, stash a copy of the
8213        // old setting to restore at the end.
8214        PackageSetting nonMutatedPs = null;
8215
8216        // writer
8217        synchronized (mPackages) {
8218            if (pkg.mSharedUserId != null) {
8219                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8220                if (suid == null) {
8221                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8222                            "Creating application package " + pkg.packageName
8223                            + " for shared user failed");
8224                }
8225                if (DEBUG_PACKAGE_SCANNING) {
8226                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8227                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8228                                + "): packages=" + suid.packages);
8229                }
8230            }
8231
8232            // Check if we are renaming from an original package name.
8233            PackageSetting origPackage = null;
8234            String realName = null;
8235            if (pkg.mOriginalPackages != null) {
8236                // This package may need to be renamed to a previously
8237                // installed name.  Let's check on that...
8238                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8239                if (pkg.mOriginalPackages.contains(renamed)) {
8240                    // This package had originally been installed as the
8241                    // original name, and we have already taken care of
8242                    // transitioning to the new one.  Just update the new
8243                    // one to continue using the old name.
8244                    realName = pkg.mRealPackage;
8245                    if (!pkg.packageName.equals(renamed)) {
8246                        // Callers into this function may have already taken
8247                        // care of renaming the package; only do it here if
8248                        // it is not already done.
8249                        pkg.setPackageName(renamed);
8250                    }
8251
8252                } else {
8253                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8254                        if ((origPackage = mSettings.peekPackageLPr(
8255                                pkg.mOriginalPackages.get(i))) != null) {
8256                            // We do have the package already installed under its
8257                            // original name...  should we use it?
8258                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8259                                // New package is not compatible with original.
8260                                origPackage = null;
8261                                continue;
8262                            } else if (origPackage.sharedUser != null) {
8263                                // Make sure uid is compatible between packages.
8264                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8265                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8266                                            + " to " + pkg.packageName + ": old uid "
8267                                            + origPackage.sharedUser.name
8268                                            + " differs from " + pkg.mSharedUserId);
8269                                    origPackage = null;
8270                                    continue;
8271                                }
8272                                // TODO: Add case when shared user id is added [b/28144775]
8273                            } else {
8274                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8275                                        + pkg.packageName + " to old name " + origPackage.name);
8276                            }
8277                            break;
8278                        }
8279                    }
8280                }
8281            }
8282
8283            if (mTransferedPackages.contains(pkg.packageName)) {
8284                Slog.w(TAG, "Package " + pkg.packageName
8285                        + " was transferred to another, but its .apk remains");
8286            }
8287
8288            // See comments in nonMutatedPs declaration
8289            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8290                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8291                if (foundPs != null) {
8292                    nonMutatedPs = new PackageSetting(foundPs);
8293                }
8294            }
8295
8296            // Just create the setting, don't add it yet. For already existing packages
8297            // the PkgSetting exists already and doesn't have to be created.
8298            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8299                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8300                    pkg.applicationInfo.primaryCpuAbi,
8301                    pkg.applicationInfo.secondaryCpuAbi,
8302                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8303                    user, false);
8304            if (pkgSetting == null) {
8305                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8306                        "Creating application package " + pkg.packageName + " failed");
8307            }
8308
8309            if (pkgSetting.origPackage != null) {
8310                // If we are first transitioning from an original package,
8311                // fix up the new package's name now.  We need to do this after
8312                // looking up the package under its new name, so getPackageLP
8313                // can take care of fiddling things correctly.
8314                pkg.setPackageName(origPackage.name);
8315
8316                // File a report about this.
8317                String msg = "New package " + pkgSetting.realName
8318                        + " renamed to replace old package " + pkgSetting.name;
8319                reportSettingsProblem(Log.WARN, msg);
8320
8321                // Make a note of it.
8322                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8323                    mTransferedPackages.add(origPackage.name);
8324                }
8325
8326                // No longer need to retain this.
8327                pkgSetting.origPackage = null;
8328            }
8329
8330            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8331                // Make a note of it.
8332                mTransferedPackages.add(pkg.packageName);
8333            }
8334
8335            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8336                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8337            }
8338
8339            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8340                // Check all shared libraries and map to their actual file path.
8341                // We only do this here for apps not on a system dir, because those
8342                // are the only ones that can fail an install due to this.  We
8343                // will take care of the system apps by updating all of their
8344                // library paths after the scan is done.
8345                updateSharedLibrariesLPw(pkg, null);
8346            }
8347
8348            if (mFoundPolicyFile) {
8349                SELinuxMMAC.assignSeinfoValue(pkg);
8350            }
8351
8352            pkg.applicationInfo.uid = pkgSetting.appId;
8353            pkg.mExtras = pkgSetting;
8354            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8355                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8356                    // We just determined the app is signed correctly, so bring
8357                    // over the latest parsed certs.
8358                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8359                } else {
8360                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8361                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8362                                "Package " + pkg.packageName + " upgrade keys do not match the "
8363                                + "previously installed version");
8364                    } else {
8365                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8366                        String msg = "System package " + pkg.packageName
8367                            + " signature changed; retaining data.";
8368                        reportSettingsProblem(Log.WARN, msg);
8369                    }
8370                }
8371            } else {
8372                try {
8373                    verifySignaturesLP(pkgSetting, pkg);
8374                    // We just determined the app is signed correctly, so bring
8375                    // over the latest parsed certs.
8376                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8377                } catch (PackageManagerException e) {
8378                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8379                        throw e;
8380                    }
8381                    // The signature has changed, but this package is in the system
8382                    // image...  let's recover!
8383                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8384                    // However...  if this package is part of a shared user, but it
8385                    // doesn't match the signature of the shared user, let's fail.
8386                    // What this means is that you can't change the signatures
8387                    // associated with an overall shared user, which doesn't seem all
8388                    // that unreasonable.
8389                    if (pkgSetting.sharedUser != null) {
8390                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8391                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8392                            throw new PackageManagerException(
8393                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8394                                            "Signature mismatch for shared user: "
8395                                            + pkgSetting.sharedUser);
8396                        }
8397                    }
8398                    // File a report about this.
8399                    String msg = "System package " + pkg.packageName
8400                        + " signature changed; retaining data.";
8401                    reportSettingsProblem(Log.WARN, msg);
8402                }
8403            }
8404            // Verify that this new package doesn't have any content providers
8405            // that conflict with existing packages.  Only do this if the
8406            // package isn't already installed, since we don't want to break
8407            // things that are installed.
8408            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8409                final int N = pkg.providers.size();
8410                int i;
8411                for (i=0; i<N; i++) {
8412                    PackageParser.Provider p = pkg.providers.get(i);
8413                    if (p.info.authority != null) {
8414                        String names[] = p.info.authority.split(";");
8415                        for (int j = 0; j < names.length; j++) {
8416                            if (mProvidersByAuthority.containsKey(names[j])) {
8417                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8418                                final String otherPackageName =
8419                                        ((other != null && other.getComponentName() != null) ?
8420                                                other.getComponentName().getPackageName() : "?");
8421                                throw new PackageManagerException(
8422                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8423                                                "Can't install because provider name " + names[j]
8424                                                + " (in package " + pkg.applicationInfo.packageName
8425                                                + ") is already used by " + otherPackageName);
8426                            }
8427                        }
8428                    }
8429                }
8430            }
8431
8432            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8433                // This package wants to adopt ownership of permissions from
8434                // another package.
8435                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8436                    final String origName = pkg.mAdoptPermissions.get(i);
8437                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8438                    if (orig != null) {
8439                        if (verifyPackageUpdateLPr(orig, pkg)) {
8440                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8441                                    + pkg.packageName);
8442                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8443                        }
8444                    }
8445                }
8446            }
8447        }
8448
8449        final String pkgName = pkg.packageName;
8450
8451        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8452        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8453        pkg.applicationInfo.processName = fixProcessName(
8454                pkg.applicationInfo.packageName,
8455                pkg.applicationInfo.processName,
8456                pkg.applicationInfo.uid);
8457
8458        if (pkg != mPlatformPackage) {
8459            // Get all of our default paths setup
8460            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8461        }
8462
8463        final String path = scanFile.getPath();
8464        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8465
8466        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8467            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8468
8469            // Some system apps still use directory structure for native libraries
8470            // in which case we might end up not detecting abi solely based on apk
8471            // structure. Try to detect abi based on directory structure.
8472            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8473                    pkg.applicationInfo.primaryCpuAbi == null) {
8474                setBundledAppAbisAndRoots(pkg, pkgSetting);
8475                setNativeLibraryPaths(pkg);
8476            }
8477
8478        } else {
8479            if ((scanFlags & SCAN_MOVE) != 0) {
8480                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8481                // but we already have this packages package info in the PackageSetting. We just
8482                // use that and derive the native library path based on the new codepath.
8483                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8484                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8485            }
8486
8487            // Set native library paths again. For moves, the path will be updated based on the
8488            // ABIs we've determined above. For non-moves, the path will be updated based on the
8489            // ABIs we determined during compilation, but the path will depend on the final
8490            // package path (after the rename away from the stage path).
8491            setNativeLibraryPaths(pkg);
8492        }
8493
8494        // This is a special case for the "system" package, where the ABI is
8495        // dictated by the zygote configuration (and init.rc). We should keep track
8496        // of this ABI so that we can deal with "normal" applications that run under
8497        // the same UID correctly.
8498        if (mPlatformPackage == pkg) {
8499            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8500                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8501        }
8502
8503        // If there's a mismatch between the abi-override in the package setting
8504        // and the abiOverride specified for the install. Warn about this because we
8505        // would've already compiled the app without taking the package setting into
8506        // account.
8507        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8508            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8509                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8510                        " for package " + pkg.packageName);
8511            }
8512        }
8513
8514        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8515        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8516        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8517
8518        // Copy the derived override back to the parsed package, so that we can
8519        // update the package settings accordingly.
8520        pkg.cpuAbiOverride = cpuAbiOverride;
8521
8522        if (DEBUG_ABI_SELECTION) {
8523            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8524                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8525                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8526        }
8527
8528        // Push the derived path down into PackageSettings so we know what to
8529        // clean up at uninstall time.
8530        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8531
8532        if (DEBUG_ABI_SELECTION) {
8533            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8534                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8535                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8536        }
8537
8538        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8539            // We don't do this here during boot because we can do it all
8540            // at once after scanning all existing packages.
8541            //
8542            // We also do this *before* we perform dexopt on this package, so that
8543            // we can avoid redundant dexopts, and also to make sure we've got the
8544            // code and package path correct.
8545            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8546                    pkg, true /* boot complete */);
8547        }
8548
8549        if (mFactoryTest && pkg.requestedPermissions.contains(
8550                android.Manifest.permission.FACTORY_TEST)) {
8551            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8552        }
8553
8554        if (isSystemApp(pkg)) {
8555            pkgSetting.isOrphaned = true;
8556        }
8557
8558        ArrayList<PackageParser.Package> clientLibPkgs = null;
8559
8560        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8561            if (nonMutatedPs != null) {
8562                synchronized (mPackages) {
8563                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8564                }
8565            }
8566            return pkg;
8567        }
8568
8569        // Only privileged apps and updated privileged apps can add child packages.
8570        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8571            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8572                throw new PackageManagerException("Only privileged apps and updated "
8573                        + "privileged apps can add child packages. Ignoring package "
8574                        + pkg.packageName);
8575            }
8576            final int childCount = pkg.childPackages.size();
8577            for (int i = 0; i < childCount; i++) {
8578                PackageParser.Package childPkg = pkg.childPackages.get(i);
8579                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8580                        childPkg.packageName)) {
8581                    throw new PackageManagerException("Cannot override a child package of "
8582                            + "another disabled system app. Ignoring package " + pkg.packageName);
8583                }
8584            }
8585        }
8586
8587        // writer
8588        synchronized (mPackages) {
8589            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8590                // Only system apps can add new shared libraries.
8591                if (pkg.libraryNames != null) {
8592                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8593                        String name = pkg.libraryNames.get(i);
8594                        boolean allowed = false;
8595                        if (pkg.isUpdatedSystemApp()) {
8596                            // New library entries can only be added through the
8597                            // system image.  This is important to get rid of a lot
8598                            // of nasty edge cases: for example if we allowed a non-
8599                            // system update of the app to add a library, then uninstalling
8600                            // the update would make the library go away, and assumptions
8601                            // we made such as through app install filtering would now
8602                            // have allowed apps on the device which aren't compatible
8603                            // with it.  Better to just have the restriction here, be
8604                            // conservative, and create many fewer cases that can negatively
8605                            // impact the user experience.
8606                            final PackageSetting sysPs = mSettings
8607                                    .getDisabledSystemPkgLPr(pkg.packageName);
8608                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8609                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8610                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8611                                        allowed = true;
8612                                        break;
8613                                    }
8614                                }
8615                            }
8616                        } else {
8617                            allowed = true;
8618                        }
8619                        if (allowed) {
8620                            if (!mSharedLibraries.containsKey(name)) {
8621                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8622                            } else if (!name.equals(pkg.packageName)) {
8623                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8624                                        + name + " already exists; skipping");
8625                            }
8626                        } else {
8627                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8628                                    + name + " that is not declared on system image; skipping");
8629                        }
8630                    }
8631                    if ((scanFlags & SCAN_BOOTING) == 0) {
8632                        // If we are not booting, we need to update any applications
8633                        // that are clients of our shared library.  If we are booting,
8634                        // this will all be done once the scan is complete.
8635                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8636                    }
8637                }
8638            }
8639        }
8640
8641        if ((scanFlags & SCAN_BOOTING) != 0) {
8642            // No apps can run during boot scan, so they don't need to be frozen
8643        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8644            // Caller asked to not kill app, so it's probably not frozen
8645        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8646            // Caller asked us to ignore frozen check for some reason; they
8647            // probably didn't know the package name
8648        } else {
8649            // We're doing major surgery on this package, so it better be frozen
8650            // right now to keep it from launching
8651            checkPackageFrozen(pkgName);
8652        }
8653
8654        // Also need to kill any apps that are dependent on the library.
8655        if (clientLibPkgs != null) {
8656            for (int i=0; i<clientLibPkgs.size(); i++) {
8657                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8658                killApplication(clientPkg.applicationInfo.packageName,
8659                        clientPkg.applicationInfo.uid, "update lib");
8660            }
8661        }
8662
8663        // Make sure we're not adding any bogus keyset info
8664        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8665        ksms.assertScannedPackageValid(pkg);
8666
8667        // writer
8668        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8669
8670        boolean createIdmapFailed = false;
8671        synchronized (mPackages) {
8672            // We don't expect installation to fail beyond this point
8673
8674            // Add the new setting to mSettings
8675            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8676            // Add the new setting to mPackages
8677            mPackages.put(pkg.applicationInfo.packageName, pkg);
8678            // Make sure we don't accidentally delete its data.
8679            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8680            while (iter.hasNext()) {
8681                PackageCleanItem item = iter.next();
8682                if (pkgName.equals(item.packageName)) {
8683                    iter.remove();
8684                }
8685            }
8686
8687            // Take care of first install / last update times.
8688            if (currentTime != 0) {
8689                if (pkgSetting.firstInstallTime == 0) {
8690                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8691                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8692                    pkgSetting.lastUpdateTime = currentTime;
8693                }
8694            } else if (pkgSetting.firstInstallTime == 0) {
8695                // We need *something*.  Take time time stamp of the file.
8696                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8697            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8698                if (scanFileTime != pkgSetting.timeStamp) {
8699                    // A package on the system image has changed; consider this
8700                    // to be an update.
8701                    pkgSetting.lastUpdateTime = scanFileTime;
8702                }
8703            }
8704
8705            // Add the package's KeySets to the global KeySetManagerService
8706            ksms.addScannedPackageLPw(pkg);
8707
8708            int N = pkg.providers.size();
8709            StringBuilder r = null;
8710            int i;
8711            for (i=0; i<N; i++) {
8712                PackageParser.Provider p = pkg.providers.get(i);
8713                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8714                        p.info.processName, pkg.applicationInfo.uid);
8715                mProviders.addProvider(p);
8716                p.syncable = p.info.isSyncable;
8717                if (p.info.authority != null) {
8718                    String names[] = p.info.authority.split(";");
8719                    p.info.authority = null;
8720                    for (int j = 0; j < names.length; j++) {
8721                        if (j == 1 && p.syncable) {
8722                            // We only want the first authority for a provider to possibly be
8723                            // syncable, so if we already added this provider using a different
8724                            // authority clear the syncable flag. We copy the provider before
8725                            // changing it because the mProviders object contains a reference
8726                            // to a provider that we don't want to change.
8727                            // Only do this for the second authority since the resulting provider
8728                            // object can be the same for all future authorities for this provider.
8729                            p = new PackageParser.Provider(p);
8730                            p.syncable = false;
8731                        }
8732                        if (!mProvidersByAuthority.containsKey(names[j])) {
8733                            mProvidersByAuthority.put(names[j], p);
8734                            if (p.info.authority == null) {
8735                                p.info.authority = names[j];
8736                            } else {
8737                                p.info.authority = p.info.authority + ";" + names[j];
8738                            }
8739                            if (DEBUG_PACKAGE_SCANNING) {
8740                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8741                                    Log.d(TAG, "Registered content provider: " + names[j]
8742                                            + ", className = " + p.info.name + ", isSyncable = "
8743                                            + p.info.isSyncable);
8744                            }
8745                        } else {
8746                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8747                            Slog.w(TAG, "Skipping provider name " + names[j] +
8748                                    " (in package " + pkg.applicationInfo.packageName +
8749                                    "): name already used by "
8750                                    + ((other != null && other.getComponentName() != null)
8751                                            ? other.getComponentName().getPackageName() : "?"));
8752                        }
8753                    }
8754                }
8755                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8756                    if (r == null) {
8757                        r = new StringBuilder(256);
8758                    } else {
8759                        r.append(' ');
8760                    }
8761                    r.append(p.info.name);
8762                }
8763            }
8764            if (r != null) {
8765                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8766            }
8767
8768            N = pkg.services.size();
8769            r = null;
8770            for (i=0; i<N; i++) {
8771                PackageParser.Service s = pkg.services.get(i);
8772                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8773                        s.info.processName, pkg.applicationInfo.uid);
8774                mServices.addService(s);
8775                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8776                    if (r == null) {
8777                        r = new StringBuilder(256);
8778                    } else {
8779                        r.append(' ');
8780                    }
8781                    r.append(s.info.name);
8782                }
8783            }
8784            if (r != null) {
8785                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8786            }
8787
8788            N = pkg.receivers.size();
8789            r = null;
8790            for (i=0; i<N; i++) {
8791                PackageParser.Activity a = pkg.receivers.get(i);
8792                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8793                        a.info.processName, pkg.applicationInfo.uid);
8794                mReceivers.addActivity(a, "receiver");
8795                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8796                    if (r == null) {
8797                        r = new StringBuilder(256);
8798                    } else {
8799                        r.append(' ');
8800                    }
8801                    r.append(a.info.name);
8802                }
8803            }
8804            if (r != null) {
8805                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8806            }
8807
8808            N = pkg.activities.size();
8809            r = null;
8810            for (i=0; i<N; i++) {
8811                PackageParser.Activity a = pkg.activities.get(i);
8812                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8813                        a.info.processName, pkg.applicationInfo.uid);
8814                mActivities.addActivity(a, "activity");
8815                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8816                    if (r == null) {
8817                        r = new StringBuilder(256);
8818                    } else {
8819                        r.append(' ');
8820                    }
8821                    r.append(a.info.name);
8822                }
8823            }
8824            if (r != null) {
8825                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8826            }
8827
8828            N = pkg.permissionGroups.size();
8829            r = null;
8830            for (i=0; i<N; i++) {
8831                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8832                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8833                final String curPackageName = cur == null ? null : cur.info.packageName;
8834                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8835                if (cur == null || isPackageUpdate) {
8836                    mPermissionGroups.put(pg.info.name, pg);
8837                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8838                        if (r == null) {
8839                            r = new StringBuilder(256);
8840                        } else {
8841                            r.append(' ');
8842                        }
8843                        if (isPackageUpdate) {
8844                            r.append("UPD:");
8845                        }
8846                        r.append(pg.info.name);
8847                    }
8848                } else {
8849                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8850                            + pg.info.packageName + " ignored: original from "
8851                            + cur.info.packageName);
8852                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8853                        if (r == null) {
8854                            r = new StringBuilder(256);
8855                        } else {
8856                            r.append(' ');
8857                        }
8858                        r.append("DUP:");
8859                        r.append(pg.info.name);
8860                    }
8861                }
8862            }
8863            if (r != null) {
8864                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8865            }
8866
8867            N = pkg.permissions.size();
8868            r = null;
8869            for (i=0; i<N; i++) {
8870                PackageParser.Permission p = pkg.permissions.get(i);
8871
8872                // Assume by default that we did not install this permission into the system.
8873                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8874
8875                // Now that permission groups have a special meaning, we ignore permission
8876                // groups for legacy apps to prevent unexpected behavior. In particular,
8877                // permissions for one app being granted to someone just becase they happen
8878                // to be in a group defined by another app (before this had no implications).
8879                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8880                    p.group = mPermissionGroups.get(p.info.group);
8881                    // Warn for a permission in an unknown group.
8882                    if (p.info.group != null && p.group == null) {
8883                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8884                                + p.info.packageName + " in an unknown group " + p.info.group);
8885                    }
8886                }
8887
8888                ArrayMap<String, BasePermission> permissionMap =
8889                        p.tree ? mSettings.mPermissionTrees
8890                                : mSettings.mPermissions;
8891                BasePermission bp = permissionMap.get(p.info.name);
8892
8893                // Allow system apps to redefine non-system permissions
8894                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8895                    final boolean currentOwnerIsSystem = (bp.perm != null
8896                            && isSystemApp(bp.perm.owner));
8897                    if (isSystemApp(p.owner)) {
8898                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8899                            // It's a built-in permission and no owner, take ownership now
8900                            bp.packageSetting = pkgSetting;
8901                            bp.perm = p;
8902                            bp.uid = pkg.applicationInfo.uid;
8903                            bp.sourcePackage = p.info.packageName;
8904                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8905                        } else if (!currentOwnerIsSystem) {
8906                            String msg = "New decl " + p.owner + " of permission  "
8907                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8908                            reportSettingsProblem(Log.WARN, msg);
8909                            bp = null;
8910                        }
8911                    }
8912                }
8913
8914                if (bp == null) {
8915                    bp = new BasePermission(p.info.name, p.info.packageName,
8916                            BasePermission.TYPE_NORMAL);
8917                    permissionMap.put(p.info.name, bp);
8918                }
8919
8920                if (bp.perm == null) {
8921                    if (bp.sourcePackage == null
8922                            || bp.sourcePackage.equals(p.info.packageName)) {
8923                        BasePermission tree = findPermissionTreeLP(p.info.name);
8924                        if (tree == null
8925                                || tree.sourcePackage.equals(p.info.packageName)) {
8926                            bp.packageSetting = pkgSetting;
8927                            bp.perm = p;
8928                            bp.uid = pkg.applicationInfo.uid;
8929                            bp.sourcePackage = p.info.packageName;
8930                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8931                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8932                                if (r == null) {
8933                                    r = new StringBuilder(256);
8934                                } else {
8935                                    r.append(' ');
8936                                }
8937                                r.append(p.info.name);
8938                            }
8939                        } else {
8940                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8941                                    + p.info.packageName + " ignored: base tree "
8942                                    + tree.name + " is from package "
8943                                    + tree.sourcePackage);
8944                        }
8945                    } else {
8946                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8947                                + p.info.packageName + " ignored: original from "
8948                                + bp.sourcePackage);
8949                    }
8950                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8951                    if (r == null) {
8952                        r = new StringBuilder(256);
8953                    } else {
8954                        r.append(' ');
8955                    }
8956                    r.append("DUP:");
8957                    r.append(p.info.name);
8958                }
8959                if (bp.perm == p) {
8960                    bp.protectionLevel = p.info.protectionLevel;
8961                }
8962            }
8963
8964            if (r != null) {
8965                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8966            }
8967
8968            N = pkg.instrumentation.size();
8969            r = null;
8970            for (i=0; i<N; i++) {
8971                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8972                a.info.packageName = pkg.applicationInfo.packageName;
8973                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8974                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8975                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8976                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8977                a.info.dataDir = pkg.applicationInfo.dataDir;
8978                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8979                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8980
8981                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8982                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8983                mInstrumentation.put(a.getComponentName(), a);
8984                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8985                    if (r == null) {
8986                        r = new StringBuilder(256);
8987                    } else {
8988                        r.append(' ');
8989                    }
8990                    r.append(a.info.name);
8991                }
8992            }
8993            if (r != null) {
8994                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8995            }
8996
8997            if (pkg.protectedBroadcasts != null) {
8998                N = pkg.protectedBroadcasts.size();
8999                for (i=0; i<N; i++) {
9000                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
9001                }
9002            }
9003
9004            pkgSetting.setTimeStamp(scanFileTime);
9005
9006            // Create idmap files for pairs of (packages, overlay packages).
9007            // Note: "android", ie framework-res.apk, is handled by native layers.
9008            if (pkg.mOverlayTarget != null) {
9009                // This is an overlay package.
9010                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9011                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9012                        mOverlays.put(pkg.mOverlayTarget,
9013                                new ArrayMap<String, PackageParser.Package>());
9014                    }
9015                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9016                    map.put(pkg.packageName, pkg);
9017                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9018                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9019                        createIdmapFailed = true;
9020                    }
9021                }
9022            } else if (mOverlays.containsKey(pkg.packageName) &&
9023                    !pkg.packageName.equals("android")) {
9024                // This is a regular package, with one or more known overlay packages.
9025                createIdmapsForPackageLI(pkg);
9026            }
9027        }
9028
9029        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9030
9031        if (createIdmapFailed) {
9032            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9033                    "scanPackageLI failed to createIdmap");
9034        }
9035        return pkg;
9036    }
9037
9038    /**
9039     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9040     * is derived purely on the basis of the contents of {@code scanFile} and
9041     * {@code cpuAbiOverride}.
9042     *
9043     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9044     */
9045    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9046                                 String cpuAbiOverride, boolean extractLibs)
9047            throws PackageManagerException {
9048        // TODO: We can probably be smarter about this stuff. For installed apps,
9049        // we can calculate this information at install time once and for all. For
9050        // system apps, we can probably assume that this information doesn't change
9051        // after the first boot scan. As things stand, we do lots of unnecessary work.
9052
9053        // Give ourselves some initial paths; we'll come back for another
9054        // pass once we've determined ABI below.
9055        setNativeLibraryPaths(pkg);
9056
9057        // We would never need to extract libs for forward-locked and external packages,
9058        // since the container service will do it for us. We shouldn't attempt to
9059        // extract libs from system app when it was not updated.
9060        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9061                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9062            extractLibs = false;
9063        }
9064
9065        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9066        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9067
9068        NativeLibraryHelper.Handle handle = null;
9069        try {
9070            handle = NativeLibraryHelper.Handle.create(pkg);
9071            // TODO(multiArch): This can be null for apps that didn't go through the
9072            // usual installation process. We can calculate it again, like we
9073            // do during install time.
9074            //
9075            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9076            // unnecessary.
9077            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9078
9079            // Null out the abis so that they can be recalculated.
9080            pkg.applicationInfo.primaryCpuAbi = null;
9081            pkg.applicationInfo.secondaryCpuAbi = null;
9082            if (isMultiArch(pkg.applicationInfo)) {
9083                // Warn if we've set an abiOverride for multi-lib packages..
9084                // By definition, we need to copy both 32 and 64 bit libraries for
9085                // such packages.
9086                if (pkg.cpuAbiOverride != null
9087                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9088                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9089                }
9090
9091                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9092                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9093                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9094                    if (extractLibs) {
9095                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9096                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9097                                useIsaSpecificSubdirs);
9098                    } else {
9099                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9100                    }
9101                }
9102
9103                maybeThrowExceptionForMultiArchCopy(
9104                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9105
9106                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9107                    if (extractLibs) {
9108                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9109                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9110                                useIsaSpecificSubdirs);
9111                    } else {
9112                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9113                    }
9114                }
9115
9116                maybeThrowExceptionForMultiArchCopy(
9117                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9118
9119                if (abi64 >= 0) {
9120                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9121                }
9122
9123                if (abi32 >= 0) {
9124                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9125                    if (abi64 >= 0) {
9126                        if (pkg.use32bitAbi) {
9127                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9128                            pkg.applicationInfo.primaryCpuAbi = abi;
9129                        } else {
9130                            pkg.applicationInfo.secondaryCpuAbi = abi;
9131                        }
9132                    } else {
9133                        pkg.applicationInfo.primaryCpuAbi = abi;
9134                    }
9135                }
9136
9137            } else {
9138                String[] abiList = (cpuAbiOverride != null) ?
9139                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9140
9141                // Enable gross and lame hacks for apps that are built with old
9142                // SDK tools. We must scan their APKs for renderscript bitcode and
9143                // not launch them if it's present. Don't bother checking on devices
9144                // that don't have 64 bit support.
9145                boolean needsRenderScriptOverride = false;
9146                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9147                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9148                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9149                    needsRenderScriptOverride = true;
9150                }
9151
9152                final int copyRet;
9153                if (extractLibs) {
9154                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9155                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9156                } else {
9157                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9158                }
9159
9160                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9161                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9162                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9163                }
9164
9165                if (copyRet >= 0) {
9166                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9167                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9168                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9169                } else if (needsRenderScriptOverride) {
9170                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9171                }
9172            }
9173        } catch (IOException ioe) {
9174            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9175        } finally {
9176            IoUtils.closeQuietly(handle);
9177        }
9178
9179        // Now that we've calculated the ABIs and determined if it's an internal app,
9180        // we will go ahead and populate the nativeLibraryPath.
9181        setNativeLibraryPaths(pkg);
9182    }
9183
9184    /**
9185     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9186     * i.e, so that all packages can be run inside a single process if required.
9187     *
9188     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9189     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9190     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9191     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9192     * updating a package that belongs to a shared user.
9193     *
9194     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9195     * adds unnecessary complexity.
9196     */
9197    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9198            PackageParser.Package scannedPackage, boolean bootComplete) {
9199        String requiredInstructionSet = null;
9200        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9201            requiredInstructionSet = VMRuntime.getInstructionSet(
9202                     scannedPackage.applicationInfo.primaryCpuAbi);
9203        }
9204
9205        PackageSetting requirer = null;
9206        for (PackageSetting ps : packagesForUser) {
9207            // If packagesForUser contains scannedPackage, we skip it. This will happen
9208            // when scannedPackage is an update of an existing package. Without this check,
9209            // we will never be able to change the ABI of any package belonging to a shared
9210            // user, even if it's compatible with other packages.
9211            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9212                if (ps.primaryCpuAbiString == null) {
9213                    continue;
9214                }
9215
9216                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9217                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9218                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9219                    // this but there's not much we can do.
9220                    String errorMessage = "Instruction set mismatch, "
9221                            + ((requirer == null) ? "[caller]" : requirer)
9222                            + " requires " + requiredInstructionSet + " whereas " + ps
9223                            + " requires " + instructionSet;
9224                    Slog.w(TAG, errorMessage);
9225                }
9226
9227                if (requiredInstructionSet == null) {
9228                    requiredInstructionSet = instructionSet;
9229                    requirer = ps;
9230                }
9231            }
9232        }
9233
9234        if (requiredInstructionSet != null) {
9235            String adjustedAbi;
9236            if (requirer != null) {
9237                // requirer != null implies that either scannedPackage was null or that scannedPackage
9238                // did not require an ABI, in which case we have to adjust scannedPackage to match
9239                // the ABI of the set (which is the same as requirer's ABI)
9240                adjustedAbi = requirer.primaryCpuAbiString;
9241                if (scannedPackage != null) {
9242                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9243                }
9244            } else {
9245                // requirer == null implies that we're updating all ABIs in the set to
9246                // match scannedPackage.
9247                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9248            }
9249
9250            for (PackageSetting ps : packagesForUser) {
9251                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9252                    if (ps.primaryCpuAbiString != null) {
9253                        continue;
9254                    }
9255
9256                    ps.primaryCpuAbiString = adjustedAbi;
9257                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9258                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9259                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9260                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9261                                + " (requirer="
9262                                + (requirer != null ? requirer.pkg : "null")
9263                                + ", scannedPackage="
9264                                + (scannedPackage != null ? scannedPackage : "null")
9265                                + ")");
9266                        try {
9267                            mInstaller.rmdex(ps.codePathString,
9268                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9269                        } catch (InstallerException ignored) {
9270                        }
9271                    }
9272                }
9273            }
9274        }
9275    }
9276
9277    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9278        synchronized (mPackages) {
9279            mResolverReplaced = true;
9280            // Set up information for custom user intent resolution activity.
9281            mResolveActivity.applicationInfo = pkg.applicationInfo;
9282            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9283            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9284            mResolveActivity.processName = pkg.applicationInfo.packageName;
9285            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9286            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9287                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9288            mResolveActivity.theme = 0;
9289            mResolveActivity.exported = true;
9290            mResolveActivity.enabled = true;
9291            mResolveInfo.activityInfo = mResolveActivity;
9292            mResolveInfo.priority = 0;
9293            mResolveInfo.preferredOrder = 0;
9294            mResolveInfo.match = 0;
9295            mResolveComponentName = mCustomResolverComponentName;
9296            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9297                    mResolveComponentName);
9298        }
9299    }
9300
9301    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9302        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9303
9304        // Set up information for ephemeral installer activity
9305        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9306        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9307        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9308        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9309        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9310        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9311                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9312        mEphemeralInstallerActivity.theme = 0;
9313        mEphemeralInstallerActivity.exported = true;
9314        mEphemeralInstallerActivity.enabled = true;
9315        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9316        mEphemeralInstallerInfo.priority = 0;
9317        mEphemeralInstallerInfo.preferredOrder = 1;
9318        mEphemeralInstallerInfo.isDefault = true;
9319        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9320                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9321
9322        if (DEBUG_EPHEMERAL) {
9323            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9324        }
9325    }
9326
9327    private static String calculateBundledApkRoot(final String codePathString) {
9328        final File codePath = new File(codePathString);
9329        final File codeRoot;
9330        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9331            codeRoot = Environment.getRootDirectory();
9332        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9333            codeRoot = Environment.getOemDirectory();
9334        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9335            codeRoot = Environment.getVendorDirectory();
9336        } else {
9337            // Unrecognized code path; take its top real segment as the apk root:
9338            // e.g. /something/app/blah.apk => /something
9339            try {
9340                File f = codePath.getCanonicalFile();
9341                File parent = f.getParentFile();    // non-null because codePath is a file
9342                File tmp;
9343                while ((tmp = parent.getParentFile()) != null) {
9344                    f = parent;
9345                    parent = tmp;
9346                }
9347                codeRoot = f;
9348                Slog.w(TAG, "Unrecognized code path "
9349                        + codePath + " - using " + codeRoot);
9350            } catch (IOException e) {
9351                // Can't canonicalize the code path -- shenanigans?
9352                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9353                return Environment.getRootDirectory().getPath();
9354            }
9355        }
9356        return codeRoot.getPath();
9357    }
9358
9359    /**
9360     * Derive and set the location of native libraries for the given package,
9361     * which varies depending on where and how the package was installed.
9362     */
9363    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9364        final ApplicationInfo info = pkg.applicationInfo;
9365        final String codePath = pkg.codePath;
9366        final File codeFile = new File(codePath);
9367        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9368        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9369
9370        info.nativeLibraryRootDir = null;
9371        info.nativeLibraryRootRequiresIsa = false;
9372        info.nativeLibraryDir = null;
9373        info.secondaryNativeLibraryDir = null;
9374
9375        if (isApkFile(codeFile)) {
9376            // Monolithic install
9377            if (bundledApp) {
9378                // If "/system/lib64/apkname" exists, assume that is the per-package
9379                // native library directory to use; otherwise use "/system/lib/apkname".
9380                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9381                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9382                        getPrimaryInstructionSet(info));
9383
9384                // This is a bundled system app so choose the path based on the ABI.
9385                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9386                // is just the default path.
9387                final String apkName = deriveCodePathName(codePath);
9388                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9389                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9390                        apkName).getAbsolutePath();
9391
9392                if (info.secondaryCpuAbi != null) {
9393                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9394                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9395                            secondaryLibDir, apkName).getAbsolutePath();
9396                }
9397            } else if (asecApp) {
9398                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9399                        .getAbsolutePath();
9400            } else {
9401                final String apkName = deriveCodePathName(codePath);
9402                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9403                        .getAbsolutePath();
9404            }
9405
9406            info.nativeLibraryRootRequiresIsa = false;
9407            info.nativeLibraryDir = info.nativeLibraryRootDir;
9408        } else {
9409            // Cluster install
9410            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9411            info.nativeLibraryRootRequiresIsa = true;
9412
9413            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9414                    getPrimaryInstructionSet(info)).getAbsolutePath();
9415
9416            if (info.secondaryCpuAbi != null) {
9417                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9418                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9419            }
9420        }
9421    }
9422
9423    /**
9424     * Calculate the abis and roots for a bundled app. These can uniquely
9425     * be determined from the contents of the system partition, i.e whether
9426     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9427     * of this information, and instead assume that the system was built
9428     * sensibly.
9429     */
9430    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9431                                           PackageSetting pkgSetting) {
9432        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9433
9434        // If "/system/lib64/apkname" exists, assume that is the per-package
9435        // native library directory to use; otherwise use "/system/lib/apkname".
9436        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9437        setBundledAppAbi(pkg, apkRoot, apkName);
9438        // pkgSetting might be null during rescan following uninstall of updates
9439        // to a bundled app, so accommodate that possibility.  The settings in
9440        // that case will be established later from the parsed package.
9441        //
9442        // If the settings aren't null, sync them up with what we've just derived.
9443        // note that apkRoot isn't stored in the package settings.
9444        if (pkgSetting != null) {
9445            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9446            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9447        }
9448    }
9449
9450    /**
9451     * Deduces the ABI of a bundled app and sets the relevant fields on the
9452     * parsed pkg object.
9453     *
9454     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9455     *        under which system libraries are installed.
9456     * @param apkName the name of the installed package.
9457     */
9458    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9459        final File codeFile = new File(pkg.codePath);
9460
9461        final boolean has64BitLibs;
9462        final boolean has32BitLibs;
9463        if (isApkFile(codeFile)) {
9464            // Monolithic install
9465            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9466            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9467        } else {
9468            // Cluster install
9469            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9470            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9471                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9472                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9473                has64BitLibs = (new File(rootDir, isa)).exists();
9474            } else {
9475                has64BitLibs = false;
9476            }
9477            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9478                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9479                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9480                has32BitLibs = (new File(rootDir, isa)).exists();
9481            } else {
9482                has32BitLibs = false;
9483            }
9484        }
9485
9486        if (has64BitLibs && !has32BitLibs) {
9487            // The package has 64 bit libs, but not 32 bit libs. Its primary
9488            // ABI should be 64 bit. We can safely assume here that the bundled
9489            // native libraries correspond to the most preferred ABI in the list.
9490
9491            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9492            pkg.applicationInfo.secondaryCpuAbi = null;
9493        } else if (has32BitLibs && !has64BitLibs) {
9494            // The package has 32 bit libs but not 64 bit libs. Its primary
9495            // ABI should be 32 bit.
9496
9497            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9498            pkg.applicationInfo.secondaryCpuAbi = null;
9499        } else if (has32BitLibs && has64BitLibs) {
9500            // The application has both 64 and 32 bit bundled libraries. We check
9501            // here that the app declares multiArch support, and warn if it doesn't.
9502            //
9503            // We will be lenient here and record both ABIs. The primary will be the
9504            // ABI that's higher on the list, i.e, a device that's configured to prefer
9505            // 64 bit apps will see a 64 bit primary ABI,
9506
9507            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9508                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9509            }
9510
9511            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9512                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9513                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9514            } else {
9515                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9516                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9517            }
9518        } else {
9519            pkg.applicationInfo.primaryCpuAbi = null;
9520            pkg.applicationInfo.secondaryCpuAbi = null;
9521        }
9522    }
9523
9524    private void killApplication(String pkgName, int appId, String reason) {
9525        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9526    }
9527
9528    private void killApplication(String pkgName, int appId, int userId, String reason) {
9529        // Request the ActivityManager to kill the process(only for existing packages)
9530        // so that we do not end up in a confused state while the user is still using the older
9531        // version of the application while the new one gets installed.
9532        final long token = Binder.clearCallingIdentity();
9533        try {
9534            IActivityManager am = ActivityManagerNative.getDefault();
9535            if (am != null) {
9536                try {
9537                    am.killApplication(pkgName, appId, userId, reason);
9538                } catch (RemoteException e) {
9539                }
9540            }
9541        } finally {
9542            Binder.restoreCallingIdentity(token);
9543        }
9544    }
9545
9546    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9547        // Remove the parent package setting
9548        PackageSetting ps = (PackageSetting) pkg.mExtras;
9549        if (ps != null) {
9550            removePackageLI(ps, chatty);
9551        }
9552        // Remove the child package setting
9553        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9554        for (int i = 0; i < childCount; i++) {
9555            PackageParser.Package childPkg = pkg.childPackages.get(i);
9556            ps = (PackageSetting) childPkg.mExtras;
9557            if (ps != null) {
9558                removePackageLI(ps, chatty);
9559            }
9560        }
9561    }
9562
9563    void removePackageLI(PackageSetting ps, boolean chatty) {
9564        if (DEBUG_INSTALL) {
9565            if (chatty)
9566                Log.d(TAG, "Removing package " + ps.name);
9567        }
9568
9569        // writer
9570        synchronized (mPackages) {
9571            mPackages.remove(ps.name);
9572            final PackageParser.Package pkg = ps.pkg;
9573            if (pkg != null) {
9574                cleanPackageDataStructuresLILPw(pkg, chatty);
9575            }
9576        }
9577    }
9578
9579    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9580        if (DEBUG_INSTALL) {
9581            if (chatty)
9582                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9583        }
9584
9585        // writer
9586        synchronized (mPackages) {
9587            // Remove the parent package
9588            mPackages.remove(pkg.applicationInfo.packageName);
9589            cleanPackageDataStructuresLILPw(pkg, chatty);
9590
9591            // Remove the child packages
9592            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9593            for (int i = 0; i < childCount; i++) {
9594                PackageParser.Package childPkg = pkg.childPackages.get(i);
9595                mPackages.remove(childPkg.applicationInfo.packageName);
9596                cleanPackageDataStructuresLILPw(childPkg, chatty);
9597            }
9598        }
9599    }
9600
9601    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9602        int N = pkg.providers.size();
9603        StringBuilder r = null;
9604        int i;
9605        for (i=0; i<N; i++) {
9606            PackageParser.Provider p = pkg.providers.get(i);
9607            mProviders.removeProvider(p);
9608            if (p.info.authority == null) {
9609
9610                /* There was another ContentProvider with this authority when
9611                 * this app was installed so this authority is null,
9612                 * Ignore it as we don't have to unregister the provider.
9613                 */
9614                continue;
9615            }
9616            String names[] = p.info.authority.split(";");
9617            for (int j = 0; j < names.length; j++) {
9618                if (mProvidersByAuthority.get(names[j]) == p) {
9619                    mProvidersByAuthority.remove(names[j]);
9620                    if (DEBUG_REMOVE) {
9621                        if (chatty)
9622                            Log.d(TAG, "Unregistered content provider: " + names[j]
9623                                    + ", className = " + p.info.name + ", isSyncable = "
9624                                    + p.info.isSyncable);
9625                    }
9626                }
9627            }
9628            if (DEBUG_REMOVE && chatty) {
9629                if (r == null) {
9630                    r = new StringBuilder(256);
9631                } else {
9632                    r.append(' ');
9633                }
9634                r.append(p.info.name);
9635            }
9636        }
9637        if (r != null) {
9638            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9639        }
9640
9641        N = pkg.services.size();
9642        r = null;
9643        for (i=0; i<N; i++) {
9644            PackageParser.Service s = pkg.services.get(i);
9645            mServices.removeService(s);
9646            if (chatty) {
9647                if (r == null) {
9648                    r = new StringBuilder(256);
9649                } else {
9650                    r.append(' ');
9651                }
9652                r.append(s.info.name);
9653            }
9654        }
9655        if (r != null) {
9656            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9657        }
9658
9659        N = pkg.receivers.size();
9660        r = null;
9661        for (i=0; i<N; i++) {
9662            PackageParser.Activity a = pkg.receivers.get(i);
9663            mReceivers.removeActivity(a, "receiver");
9664            if (DEBUG_REMOVE && chatty) {
9665                if (r == null) {
9666                    r = new StringBuilder(256);
9667                } else {
9668                    r.append(' ');
9669                }
9670                r.append(a.info.name);
9671            }
9672        }
9673        if (r != null) {
9674            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9675        }
9676
9677        N = pkg.activities.size();
9678        r = null;
9679        for (i=0; i<N; i++) {
9680            PackageParser.Activity a = pkg.activities.get(i);
9681            mActivities.removeActivity(a, "activity");
9682            if (DEBUG_REMOVE && chatty) {
9683                if (r == null) {
9684                    r = new StringBuilder(256);
9685                } else {
9686                    r.append(' ');
9687                }
9688                r.append(a.info.name);
9689            }
9690        }
9691        if (r != null) {
9692            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9693        }
9694
9695        N = pkg.permissions.size();
9696        r = null;
9697        for (i=0; i<N; i++) {
9698            PackageParser.Permission p = pkg.permissions.get(i);
9699            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9700            if (bp == null) {
9701                bp = mSettings.mPermissionTrees.get(p.info.name);
9702            }
9703            if (bp != null && bp.perm == p) {
9704                bp.perm = null;
9705                if (DEBUG_REMOVE && chatty) {
9706                    if (r == null) {
9707                        r = new StringBuilder(256);
9708                    } else {
9709                        r.append(' ');
9710                    }
9711                    r.append(p.info.name);
9712                }
9713            }
9714            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9715                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9716                if (appOpPkgs != null) {
9717                    appOpPkgs.remove(pkg.packageName);
9718                }
9719            }
9720        }
9721        if (r != null) {
9722            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9723        }
9724
9725        N = pkg.requestedPermissions.size();
9726        r = null;
9727        for (i=0; i<N; i++) {
9728            String perm = pkg.requestedPermissions.get(i);
9729            BasePermission bp = mSettings.mPermissions.get(perm);
9730            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9731                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9732                if (appOpPkgs != null) {
9733                    appOpPkgs.remove(pkg.packageName);
9734                    if (appOpPkgs.isEmpty()) {
9735                        mAppOpPermissionPackages.remove(perm);
9736                    }
9737                }
9738            }
9739        }
9740        if (r != null) {
9741            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9742        }
9743
9744        N = pkg.instrumentation.size();
9745        r = null;
9746        for (i=0; i<N; i++) {
9747            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9748            mInstrumentation.remove(a.getComponentName());
9749            if (DEBUG_REMOVE && chatty) {
9750                if (r == null) {
9751                    r = new StringBuilder(256);
9752                } else {
9753                    r.append(' ');
9754                }
9755                r.append(a.info.name);
9756            }
9757        }
9758        if (r != null) {
9759            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9760        }
9761
9762        r = null;
9763        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9764            // Only system apps can hold shared libraries.
9765            if (pkg.libraryNames != null) {
9766                for (i=0; i<pkg.libraryNames.size(); i++) {
9767                    String name = pkg.libraryNames.get(i);
9768                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9769                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9770                        mSharedLibraries.remove(name);
9771                        if (DEBUG_REMOVE && chatty) {
9772                            if (r == null) {
9773                                r = new StringBuilder(256);
9774                            } else {
9775                                r.append(' ');
9776                            }
9777                            r.append(name);
9778                        }
9779                    }
9780                }
9781            }
9782        }
9783        if (r != null) {
9784            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9785        }
9786    }
9787
9788    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9789        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9790            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9791                return true;
9792            }
9793        }
9794        return false;
9795    }
9796
9797    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9798    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9799    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9800
9801    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9802        // Update the parent permissions
9803        updatePermissionsLPw(pkg.packageName, pkg, flags);
9804        // Update the child permissions
9805        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9806        for (int i = 0; i < childCount; i++) {
9807            PackageParser.Package childPkg = pkg.childPackages.get(i);
9808            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9809        }
9810    }
9811
9812    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9813            int flags) {
9814        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9815        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9816    }
9817
9818    private void updatePermissionsLPw(String changingPkg,
9819            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9820        // Make sure there are no dangling permission trees.
9821        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9822        while (it.hasNext()) {
9823            final BasePermission bp = it.next();
9824            if (bp.packageSetting == null) {
9825                // We may not yet have parsed the package, so just see if
9826                // we still know about its settings.
9827                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9828            }
9829            if (bp.packageSetting == null) {
9830                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9831                        + " from package " + bp.sourcePackage);
9832                it.remove();
9833            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9834                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9835                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9836                            + " from package " + bp.sourcePackage);
9837                    flags |= UPDATE_PERMISSIONS_ALL;
9838                    it.remove();
9839                }
9840            }
9841        }
9842
9843        // Make sure all dynamic permissions have been assigned to a package,
9844        // and make sure there are no dangling permissions.
9845        it = mSettings.mPermissions.values().iterator();
9846        while (it.hasNext()) {
9847            final BasePermission bp = it.next();
9848            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9849                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9850                        + bp.name + " pkg=" + bp.sourcePackage
9851                        + " info=" + bp.pendingInfo);
9852                if (bp.packageSetting == null && bp.pendingInfo != null) {
9853                    final BasePermission tree = findPermissionTreeLP(bp.name);
9854                    if (tree != null && tree.perm != null) {
9855                        bp.packageSetting = tree.packageSetting;
9856                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9857                                new PermissionInfo(bp.pendingInfo));
9858                        bp.perm.info.packageName = tree.perm.info.packageName;
9859                        bp.perm.info.name = bp.name;
9860                        bp.uid = tree.uid;
9861                    }
9862                }
9863            }
9864            if (bp.packageSetting == null) {
9865                // We may not yet have parsed the package, so just see if
9866                // we still know about its settings.
9867                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9868            }
9869            if (bp.packageSetting == null) {
9870                Slog.w(TAG, "Removing dangling permission: " + bp.name
9871                        + " from package " + bp.sourcePackage);
9872                it.remove();
9873            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9874                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9875                    Slog.i(TAG, "Removing old permission: " + bp.name
9876                            + " from package " + bp.sourcePackage);
9877                    flags |= UPDATE_PERMISSIONS_ALL;
9878                    it.remove();
9879                }
9880            }
9881        }
9882
9883        // Now update the permissions for all packages, in particular
9884        // replace the granted permissions of the system packages.
9885        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9886            for (PackageParser.Package pkg : mPackages.values()) {
9887                if (pkg != pkgInfo) {
9888                    // Only replace for packages on requested volume
9889                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9890                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9891                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9892                    grantPermissionsLPw(pkg, replace, changingPkg);
9893                }
9894            }
9895        }
9896
9897        if (pkgInfo != null) {
9898            // Only replace for packages on requested volume
9899            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9900            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9901                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9902            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9903        }
9904    }
9905
9906    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9907            String packageOfInterest) {
9908        // IMPORTANT: There are two types of permissions: install and runtime.
9909        // Install time permissions are granted when the app is installed to
9910        // all device users and users added in the future. Runtime permissions
9911        // are granted at runtime explicitly to specific users. Normal and signature
9912        // protected permissions are install time permissions. Dangerous permissions
9913        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9914        // otherwise they are runtime permissions. This function does not manage
9915        // runtime permissions except for the case an app targeting Lollipop MR1
9916        // being upgraded to target a newer SDK, in which case dangerous permissions
9917        // are transformed from install time to runtime ones.
9918
9919        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9920        if (ps == null) {
9921            return;
9922        }
9923
9924        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9925
9926        PermissionsState permissionsState = ps.getPermissionsState();
9927        PermissionsState origPermissions = permissionsState;
9928
9929        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9930
9931        boolean runtimePermissionsRevoked = false;
9932        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9933
9934        boolean changedInstallPermission = false;
9935
9936        if (replace) {
9937            ps.installPermissionsFixed = false;
9938            if (!ps.isSharedUser()) {
9939                origPermissions = new PermissionsState(permissionsState);
9940                permissionsState.reset();
9941            } else {
9942                // We need to know only about runtime permission changes since the
9943                // calling code always writes the install permissions state but
9944                // the runtime ones are written only if changed. The only cases of
9945                // changed runtime permissions here are promotion of an install to
9946                // runtime and revocation of a runtime from a shared user.
9947                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9948                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9949                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9950                    runtimePermissionsRevoked = true;
9951                }
9952            }
9953        }
9954
9955        permissionsState.setGlobalGids(mGlobalGids);
9956
9957        final int N = pkg.requestedPermissions.size();
9958        for (int i=0; i<N; i++) {
9959            final String name = pkg.requestedPermissions.get(i);
9960            final BasePermission bp = mSettings.mPermissions.get(name);
9961
9962            if (DEBUG_INSTALL) {
9963                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9964            }
9965
9966            if (bp == null || bp.packageSetting == null) {
9967                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9968                    Slog.w(TAG, "Unknown permission " + name
9969                            + " in package " + pkg.packageName);
9970                }
9971                continue;
9972            }
9973
9974            final String perm = bp.name;
9975            boolean allowedSig = false;
9976            int grant = GRANT_DENIED;
9977
9978            // Keep track of app op permissions.
9979            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9980                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9981                if (pkgs == null) {
9982                    pkgs = new ArraySet<>();
9983                    mAppOpPermissionPackages.put(bp.name, pkgs);
9984                }
9985                pkgs.add(pkg.packageName);
9986            }
9987
9988            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9989            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9990                    >= Build.VERSION_CODES.M;
9991            switch (level) {
9992                case PermissionInfo.PROTECTION_NORMAL: {
9993                    // For all apps normal permissions are install time ones.
9994                    grant = GRANT_INSTALL;
9995                } break;
9996
9997                case PermissionInfo.PROTECTION_DANGEROUS: {
9998                    // If a permission review is required for legacy apps we represent
9999                    // their permissions as always granted runtime ones since we need
10000                    // to keep the review required permission flag per user while an
10001                    // install permission's state is shared across all users.
10002                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired
10003                            && !Build.PERMISSIONS_REVIEW_REQUIRED) {
10004                        // For legacy apps dangerous permissions are install time ones.
10005                        grant = GRANT_INSTALL;
10006                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10007                        // For legacy apps that became modern, install becomes runtime.
10008                        grant = GRANT_UPGRADE;
10009                    } else if (mPromoteSystemApps
10010                            && isSystemApp(ps)
10011                            && mExistingSystemPackages.contains(ps.name)) {
10012                        // For legacy system apps, install becomes runtime.
10013                        // We cannot check hasInstallPermission() for system apps since those
10014                        // permissions were granted implicitly and not persisted pre-M.
10015                        grant = GRANT_UPGRADE;
10016                    } else {
10017                        // For modern apps keep runtime permissions unchanged.
10018                        grant = GRANT_RUNTIME;
10019                    }
10020                } break;
10021
10022                case PermissionInfo.PROTECTION_SIGNATURE: {
10023                    // For all apps signature permissions are install time ones.
10024                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10025                    if (allowedSig) {
10026                        grant = GRANT_INSTALL;
10027                    }
10028                } break;
10029            }
10030
10031            if (DEBUG_INSTALL) {
10032                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10033            }
10034
10035            if (grant != GRANT_DENIED) {
10036                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10037                    // If this is an existing, non-system package, then
10038                    // we can't add any new permissions to it.
10039                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10040                        // Except...  if this is a permission that was added
10041                        // to the platform (note: need to only do this when
10042                        // updating the platform).
10043                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10044                            grant = GRANT_DENIED;
10045                        }
10046                    }
10047                }
10048
10049                switch (grant) {
10050                    case GRANT_INSTALL: {
10051                        // Revoke this as runtime permission to handle the case of
10052                        // a runtime permission being downgraded to an install one.
10053                        // Also in permission review mode we keep dangerous permissions
10054                        // for legacy apps
10055                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10056                            if (origPermissions.getRuntimePermissionState(
10057                                    bp.name, userId) != null) {
10058                                // Revoke the runtime permission and clear the flags.
10059                                origPermissions.revokeRuntimePermission(bp, userId);
10060                                origPermissions.updatePermissionFlags(bp, userId,
10061                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10062                                // If we revoked a permission permission, we have to write.
10063                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10064                                        changedRuntimePermissionUserIds, userId);
10065                            }
10066                        }
10067                        // Grant an install permission.
10068                        if (permissionsState.grantInstallPermission(bp) !=
10069                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10070                            changedInstallPermission = true;
10071                        }
10072                    } break;
10073
10074                    case GRANT_RUNTIME: {
10075                        // Grant previously granted runtime permissions.
10076                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10077                            PermissionState permissionState = origPermissions
10078                                    .getRuntimePermissionState(bp.name, userId);
10079                            int flags = permissionState != null
10080                                    ? permissionState.getFlags() : 0;
10081                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10082                                // Don't propagate the permission in a permission review mode if
10083                                // the former was revoked, i.e. marked to not propagate on upgrade.
10084                                // Note that in a permission review mode install permissions are
10085                                // represented as constantly granted runtime ones since we need to
10086                                // keep a per user state associated with the permission. Also the
10087                                // revoke on upgrade flag is no longer applicable and is reset.
10088                                final boolean revokeOnUpgrade = (flags & PackageManager
10089                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
10090                                if (revokeOnUpgrade) {
10091                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
10092                                    // Since we changed the flags, we have to write.
10093                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10094                                            changedRuntimePermissionUserIds, userId);
10095                                }
10096                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
10097                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
10098                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
10099                                        // If we cannot put the permission as it was,
10100                                        // we have to write.
10101                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10102                                                changedRuntimePermissionUserIds, userId);
10103                                    }
10104                                }
10105
10106                                // If the app supports runtime permissions no need for a review.
10107                                if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
10108                                        && appSupportsRuntimePermissions
10109                                        && (flags & PackageManager
10110                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10111                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10112                                    // Since we changed the flags, we have to write.
10113                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10114                                            changedRuntimePermissionUserIds, userId);
10115                                }
10116                            } else if ((mPermissionReviewRequired
10117                                        || Build.PERMISSIONS_REVIEW_REQUIRED)
10118                                    && !appSupportsRuntimePermissions) {
10119                                // For legacy apps that need a permission review, every new
10120                                // runtime permission is granted but it is pending a review.
10121                                // We also need to review only platform defined runtime
10122                                // permissions as these are the only ones the platform knows
10123                                // how to disable the API to simulate revocation as legacy
10124                                // apps don't expect to run with revoked permissions.
10125                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10126                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10127                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10128                                        // We changed the flags, hence have to write.
10129                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10130                                                changedRuntimePermissionUserIds, userId);
10131                                    }
10132                                }
10133                                if (permissionsState.grantRuntimePermission(bp, userId)
10134                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10135                                    // We changed the permission, hence have to write.
10136                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10137                                            changedRuntimePermissionUserIds, userId);
10138                                }
10139                            }
10140                            // Propagate the permission flags.
10141                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10142                        }
10143                    } break;
10144
10145                    case GRANT_UPGRADE: {
10146                        // Grant runtime permissions for a previously held install permission.
10147                        PermissionState permissionState = origPermissions
10148                                .getInstallPermissionState(bp.name);
10149                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10150
10151                        if (origPermissions.revokeInstallPermission(bp)
10152                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10153                            // We will be transferring the permission flags, so clear them.
10154                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10155                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10156                            changedInstallPermission = true;
10157                        }
10158
10159                        // If the permission is not to be promoted to runtime we ignore it and
10160                        // also its other flags as they are not applicable to install permissions.
10161                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10162                            for (int userId : currentUserIds) {
10163                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10164                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10165                                    // Transfer the permission flags.
10166                                    permissionsState.updatePermissionFlags(bp, userId,
10167                                            flags, flags);
10168                                    // If we granted the permission, we have to write.
10169                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10170                                            changedRuntimePermissionUserIds, userId);
10171                                }
10172                            }
10173                        }
10174                    } break;
10175
10176                    default: {
10177                        if (packageOfInterest == null
10178                                || packageOfInterest.equals(pkg.packageName)) {
10179                            Slog.w(TAG, "Not granting permission " + perm
10180                                    + " to package " + pkg.packageName
10181                                    + " because it was previously installed without");
10182                        }
10183                    } break;
10184                }
10185            } else {
10186                if (permissionsState.revokeInstallPermission(bp) !=
10187                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10188                    // Also drop the permission flags.
10189                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10190                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10191                    changedInstallPermission = true;
10192                    Slog.i(TAG, "Un-granting permission " + perm
10193                            + " from package " + pkg.packageName
10194                            + " (protectionLevel=" + bp.protectionLevel
10195                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10196                            + ")");
10197                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10198                    // Don't print warning for app op permissions, since it is fine for them
10199                    // not to be granted, there is a UI for the user to decide.
10200                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10201                        Slog.w(TAG, "Not granting permission " + perm
10202                                + " to package " + pkg.packageName
10203                                + " (protectionLevel=" + bp.protectionLevel
10204                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10205                                + ")");
10206                    }
10207                }
10208            }
10209        }
10210
10211        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10212                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10213            // This is the first that we have heard about this package, so the
10214            // permissions we have now selected are fixed until explicitly
10215            // changed.
10216            ps.installPermissionsFixed = true;
10217        }
10218
10219        // Persist the runtime permissions state for users with changes. If permissions
10220        // were revoked because no app in the shared user declares them we have to
10221        // write synchronously to avoid losing runtime permissions state.
10222        for (int userId : changedRuntimePermissionUserIds) {
10223            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10224        }
10225
10226        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10227    }
10228
10229    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10230        boolean allowed = false;
10231        final int NP = PackageParser.NEW_PERMISSIONS.length;
10232        for (int ip=0; ip<NP; ip++) {
10233            final PackageParser.NewPermissionInfo npi
10234                    = PackageParser.NEW_PERMISSIONS[ip];
10235            if (npi.name.equals(perm)
10236                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10237                allowed = true;
10238                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10239                        + pkg.packageName);
10240                break;
10241            }
10242        }
10243        return allowed;
10244    }
10245
10246    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10247            BasePermission bp, PermissionsState origPermissions) {
10248        boolean allowed;
10249        allowed = (compareSignatures(
10250                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10251                        == PackageManager.SIGNATURE_MATCH)
10252                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10253                        == PackageManager.SIGNATURE_MATCH);
10254        if (!allowed && (bp.protectionLevel
10255                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10256            if (isSystemApp(pkg)) {
10257                // For updated system applications, a system permission
10258                // is granted only if it had been defined by the original application.
10259                if (pkg.isUpdatedSystemApp()) {
10260                    final PackageSetting sysPs = mSettings
10261                            .getDisabledSystemPkgLPr(pkg.packageName);
10262                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10263                        // If the original was granted this permission, we take
10264                        // that grant decision as read and propagate it to the
10265                        // update.
10266                        if (sysPs.isPrivileged()) {
10267                            allowed = true;
10268                        }
10269                    } else {
10270                        // The system apk may have been updated with an older
10271                        // version of the one on the data partition, but which
10272                        // granted a new system permission that it didn't have
10273                        // before.  In this case we do want to allow the app to
10274                        // now get the new permission if the ancestral apk is
10275                        // privileged to get it.
10276                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10277                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10278                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10279                                    allowed = true;
10280                                    break;
10281                                }
10282                            }
10283                        }
10284                        // Also if a privileged parent package on the system image or any of
10285                        // its children requested a privileged permission, the updated child
10286                        // packages can also get the permission.
10287                        if (pkg.parentPackage != null) {
10288                            final PackageSetting disabledSysParentPs = mSettings
10289                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10290                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10291                                    && disabledSysParentPs.isPrivileged()) {
10292                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10293                                    allowed = true;
10294                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10295                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10296                                    for (int i = 0; i < count; i++) {
10297                                        PackageParser.Package disabledSysChildPkg =
10298                                                disabledSysParentPs.pkg.childPackages.get(i);
10299                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10300                                                perm)) {
10301                                            allowed = true;
10302                                            break;
10303                                        }
10304                                    }
10305                                }
10306                            }
10307                        }
10308                    }
10309                } else {
10310                    allowed = isPrivilegedApp(pkg);
10311                }
10312            }
10313        }
10314        if (!allowed) {
10315            if (!allowed && (bp.protectionLevel
10316                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10317                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10318                // If this was a previously normal/dangerous permission that got moved
10319                // to a system permission as part of the runtime permission redesign, then
10320                // we still want to blindly grant it to old apps.
10321                allowed = true;
10322            }
10323            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10324                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10325                // If this permission is to be granted to the system installer and
10326                // this app is an installer, then it gets the permission.
10327                allowed = true;
10328            }
10329            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10330                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10331                // If this permission is to be granted to the system verifier and
10332                // this app is a verifier, then it gets the permission.
10333                allowed = true;
10334            }
10335            if (!allowed && (bp.protectionLevel
10336                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10337                    && isSystemApp(pkg)) {
10338                // Any pre-installed system app is allowed to get this permission.
10339                allowed = true;
10340            }
10341            if (!allowed && (bp.protectionLevel
10342                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10343                // For development permissions, a development permission
10344                // is granted only if it was already granted.
10345                allowed = origPermissions.hasInstallPermission(perm);
10346            }
10347            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10348                    && pkg.packageName.equals(mSetupWizardPackage)) {
10349                // If this permission is to be granted to the system setup wizard and
10350                // this app is a setup wizard, then it gets the permission.
10351                allowed = true;
10352            }
10353        }
10354        return allowed;
10355    }
10356
10357    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10358        final int permCount = pkg.requestedPermissions.size();
10359        for (int j = 0; j < permCount; j++) {
10360            String requestedPermission = pkg.requestedPermissions.get(j);
10361            if (permission.equals(requestedPermission)) {
10362                return true;
10363            }
10364        }
10365        return false;
10366    }
10367
10368    final class ActivityIntentResolver
10369            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10370        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10371                boolean defaultOnly, int userId) {
10372            if (!sUserManager.exists(userId)) return null;
10373            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10374            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10375        }
10376
10377        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10378                int userId) {
10379            if (!sUserManager.exists(userId)) return null;
10380            mFlags = flags;
10381            return super.queryIntent(intent, resolvedType,
10382                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10383        }
10384
10385        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10386                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10387            if (!sUserManager.exists(userId)) return null;
10388            if (packageActivities == null) {
10389                return null;
10390            }
10391            mFlags = flags;
10392            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10393            final int N = packageActivities.size();
10394            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10395                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10396
10397            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10398            for (int i = 0; i < N; ++i) {
10399                intentFilters = packageActivities.get(i).intents;
10400                if (intentFilters != null && intentFilters.size() > 0) {
10401                    PackageParser.ActivityIntentInfo[] array =
10402                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10403                    intentFilters.toArray(array);
10404                    listCut.add(array);
10405                }
10406            }
10407            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10408        }
10409
10410        /**
10411         * Finds a privileged activity that matches the specified activity names.
10412         */
10413        private PackageParser.Activity findMatchingActivity(
10414                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10415            for (PackageParser.Activity sysActivity : activityList) {
10416                if (sysActivity.info.name.equals(activityInfo.name)) {
10417                    return sysActivity;
10418                }
10419                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10420                    return sysActivity;
10421                }
10422                if (sysActivity.info.targetActivity != null) {
10423                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10424                        return sysActivity;
10425                    }
10426                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10427                        return sysActivity;
10428                    }
10429                }
10430            }
10431            return null;
10432        }
10433
10434        public class IterGenerator<E> {
10435            public Iterator<E> generate(ActivityIntentInfo info) {
10436                return null;
10437            }
10438        }
10439
10440        public class ActionIterGenerator extends IterGenerator<String> {
10441            @Override
10442            public Iterator<String> generate(ActivityIntentInfo info) {
10443                return info.actionsIterator();
10444            }
10445        }
10446
10447        public class CategoriesIterGenerator extends IterGenerator<String> {
10448            @Override
10449            public Iterator<String> generate(ActivityIntentInfo info) {
10450                return info.categoriesIterator();
10451            }
10452        }
10453
10454        public class SchemesIterGenerator extends IterGenerator<String> {
10455            @Override
10456            public Iterator<String> generate(ActivityIntentInfo info) {
10457                return info.schemesIterator();
10458            }
10459        }
10460
10461        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10462            @Override
10463            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10464                return info.authoritiesIterator();
10465            }
10466        }
10467
10468        /**
10469         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10470         * MODIFIED. Do not pass in a list that should not be changed.
10471         */
10472        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10473                IterGenerator<T> generator, Iterator<T> searchIterator) {
10474            // loop through the set of actions; every one must be found in the intent filter
10475            while (searchIterator.hasNext()) {
10476                // we must have at least one filter in the list to consider a match
10477                if (intentList.size() == 0) {
10478                    break;
10479                }
10480
10481                final T searchAction = searchIterator.next();
10482
10483                // loop through the set of intent filters
10484                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10485                while (intentIter.hasNext()) {
10486                    final ActivityIntentInfo intentInfo = intentIter.next();
10487                    boolean selectionFound = false;
10488
10489                    // loop through the intent filter's selection criteria; at least one
10490                    // of them must match the searched criteria
10491                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10492                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10493                        final T intentSelection = intentSelectionIter.next();
10494                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10495                            selectionFound = true;
10496                            break;
10497                        }
10498                    }
10499
10500                    // the selection criteria wasn't found in this filter's set; this filter
10501                    // is not a potential match
10502                    if (!selectionFound) {
10503                        intentIter.remove();
10504                    }
10505                }
10506            }
10507        }
10508
10509        private boolean isProtectedAction(ActivityIntentInfo filter) {
10510            final Iterator<String> actionsIter = filter.actionsIterator();
10511            while (actionsIter != null && actionsIter.hasNext()) {
10512                final String filterAction = actionsIter.next();
10513                if (PROTECTED_ACTIONS.contains(filterAction)) {
10514                    return true;
10515                }
10516            }
10517            return false;
10518        }
10519
10520        /**
10521         * Adjusts the priority of the given intent filter according to policy.
10522         * <p>
10523         * <ul>
10524         * <li>The priority for non privileged applications is capped to '0'</li>
10525         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10526         * <li>The priority for unbundled updates to privileged applications is capped to the
10527         *      priority defined on the system partition</li>
10528         * </ul>
10529         * <p>
10530         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10531         * allowed to obtain any priority on any action.
10532         */
10533        private void adjustPriority(
10534                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10535            // nothing to do; priority is fine as-is
10536            if (intent.getPriority() <= 0) {
10537                return;
10538            }
10539
10540            final ActivityInfo activityInfo = intent.activity.info;
10541            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10542
10543            final boolean privilegedApp =
10544                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10545            if (!privilegedApp) {
10546                // non-privileged applications can never define a priority >0
10547                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10548                        + " package: " + applicationInfo.packageName
10549                        + " activity: " + intent.activity.className
10550                        + " origPrio: " + intent.getPriority());
10551                intent.setPriority(0);
10552                return;
10553            }
10554
10555            if (systemActivities == null) {
10556                // the system package is not disabled; we're parsing the system partition
10557                if (isProtectedAction(intent)) {
10558                    if (mDeferProtectedFilters) {
10559                        // We can't deal with these just yet. No component should ever obtain a
10560                        // >0 priority for a protected actions, with ONE exception -- the setup
10561                        // wizard. The setup wizard, however, cannot be known until we're able to
10562                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10563                        // until all intent filters have been processed. Chicken, meet egg.
10564                        // Let the filter temporarily have a high priority and rectify the
10565                        // priorities after all system packages have been scanned.
10566                        mProtectedFilters.add(intent);
10567                        if (DEBUG_FILTERS) {
10568                            Slog.i(TAG, "Protected action; save for later;"
10569                                    + " package: " + applicationInfo.packageName
10570                                    + " activity: " + intent.activity.className
10571                                    + " origPrio: " + intent.getPriority());
10572                        }
10573                        return;
10574                    } else {
10575                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10576                            Slog.i(TAG, "No setup wizard;"
10577                                + " All protected intents capped to priority 0");
10578                        }
10579                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10580                            if (DEBUG_FILTERS) {
10581                                Slog.i(TAG, "Found setup wizard;"
10582                                    + " allow priority " + intent.getPriority() + ";"
10583                                    + " package: " + intent.activity.info.packageName
10584                                    + " activity: " + intent.activity.className
10585                                    + " priority: " + intent.getPriority());
10586                            }
10587                            // setup wizard gets whatever it wants
10588                            return;
10589                        }
10590                        Slog.w(TAG, "Protected action; cap priority to 0;"
10591                                + " package: " + intent.activity.info.packageName
10592                                + " activity: " + intent.activity.className
10593                                + " origPrio: " + intent.getPriority());
10594                        intent.setPriority(0);
10595                        return;
10596                    }
10597                }
10598                // privileged apps on the system image get whatever priority they request
10599                return;
10600            }
10601
10602            // privileged app unbundled update ... try to find the same activity
10603            final PackageParser.Activity foundActivity =
10604                    findMatchingActivity(systemActivities, activityInfo);
10605            if (foundActivity == null) {
10606                // this is a new activity; it cannot obtain >0 priority
10607                if (DEBUG_FILTERS) {
10608                    Slog.i(TAG, "New activity; cap priority to 0;"
10609                            + " package: " + applicationInfo.packageName
10610                            + " activity: " + intent.activity.className
10611                            + " origPrio: " + intent.getPriority());
10612                }
10613                intent.setPriority(0);
10614                return;
10615            }
10616
10617            // found activity, now check for filter equivalence
10618
10619            // a shallow copy is enough; we modify the list, not its contents
10620            final List<ActivityIntentInfo> intentListCopy =
10621                    new ArrayList<>(foundActivity.intents);
10622            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10623
10624            // find matching action subsets
10625            final Iterator<String> actionsIterator = intent.actionsIterator();
10626            if (actionsIterator != null) {
10627                getIntentListSubset(
10628                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10629                if (intentListCopy.size() == 0) {
10630                    // no more intents to match; we're not equivalent
10631                    if (DEBUG_FILTERS) {
10632                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10633                                + " package: " + applicationInfo.packageName
10634                                + " activity: " + intent.activity.className
10635                                + " origPrio: " + intent.getPriority());
10636                    }
10637                    intent.setPriority(0);
10638                    return;
10639                }
10640            }
10641
10642            // find matching category subsets
10643            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10644            if (categoriesIterator != null) {
10645                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10646                        categoriesIterator);
10647                if (intentListCopy.size() == 0) {
10648                    // no more intents to match; we're not equivalent
10649                    if (DEBUG_FILTERS) {
10650                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10651                                + " package: " + applicationInfo.packageName
10652                                + " activity: " + intent.activity.className
10653                                + " origPrio: " + intent.getPriority());
10654                    }
10655                    intent.setPriority(0);
10656                    return;
10657                }
10658            }
10659
10660            // find matching schemes subsets
10661            final Iterator<String> schemesIterator = intent.schemesIterator();
10662            if (schemesIterator != null) {
10663                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10664                        schemesIterator);
10665                if (intentListCopy.size() == 0) {
10666                    // no more intents to match; we're not equivalent
10667                    if (DEBUG_FILTERS) {
10668                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10669                                + " package: " + applicationInfo.packageName
10670                                + " activity: " + intent.activity.className
10671                                + " origPrio: " + intent.getPriority());
10672                    }
10673                    intent.setPriority(0);
10674                    return;
10675                }
10676            }
10677
10678            // find matching authorities subsets
10679            final Iterator<IntentFilter.AuthorityEntry>
10680                    authoritiesIterator = intent.authoritiesIterator();
10681            if (authoritiesIterator != null) {
10682                getIntentListSubset(intentListCopy,
10683                        new AuthoritiesIterGenerator(),
10684                        authoritiesIterator);
10685                if (intentListCopy.size() == 0) {
10686                    // no more intents to match; we're not equivalent
10687                    if (DEBUG_FILTERS) {
10688                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10689                                + " package: " + applicationInfo.packageName
10690                                + " activity: " + intent.activity.className
10691                                + " origPrio: " + intent.getPriority());
10692                    }
10693                    intent.setPriority(0);
10694                    return;
10695                }
10696            }
10697
10698            // we found matching filter(s); app gets the max priority of all intents
10699            int cappedPriority = 0;
10700            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10701                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10702            }
10703            if (intent.getPriority() > cappedPriority) {
10704                if (DEBUG_FILTERS) {
10705                    Slog.i(TAG, "Found matching filter(s);"
10706                            + " cap priority to " + cappedPriority + ";"
10707                            + " package: " + applicationInfo.packageName
10708                            + " activity: " + intent.activity.className
10709                            + " origPrio: " + intent.getPriority());
10710                }
10711                intent.setPriority(cappedPriority);
10712                return;
10713            }
10714            // all this for nothing; the requested priority was <= what was on the system
10715        }
10716
10717        public final void addActivity(PackageParser.Activity a, String type) {
10718            mActivities.put(a.getComponentName(), a);
10719            if (DEBUG_SHOW_INFO)
10720                Log.v(
10721                TAG, "  " + type + " " +
10722                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10723            if (DEBUG_SHOW_INFO)
10724                Log.v(TAG, "    Class=" + a.info.name);
10725            final int NI = a.intents.size();
10726            for (int j=0; j<NI; j++) {
10727                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10728                if ("activity".equals(type)) {
10729                    final PackageSetting ps =
10730                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10731                    final List<PackageParser.Activity> systemActivities =
10732                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10733                    adjustPriority(systemActivities, intent);
10734                }
10735                if (DEBUG_SHOW_INFO) {
10736                    Log.v(TAG, "    IntentFilter:");
10737                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10738                }
10739                if (!intent.debugCheck()) {
10740                    Log.w(TAG, "==> For Activity " + a.info.name);
10741                }
10742                addFilter(intent);
10743            }
10744        }
10745
10746        public final void removeActivity(PackageParser.Activity a, String type) {
10747            mActivities.remove(a.getComponentName());
10748            if (DEBUG_SHOW_INFO) {
10749                Log.v(TAG, "  " + type + " "
10750                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10751                                : a.info.name) + ":");
10752                Log.v(TAG, "    Class=" + a.info.name);
10753            }
10754            final int NI = a.intents.size();
10755            for (int j=0; j<NI; j++) {
10756                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10757                if (DEBUG_SHOW_INFO) {
10758                    Log.v(TAG, "    IntentFilter:");
10759                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10760                }
10761                removeFilter(intent);
10762            }
10763        }
10764
10765        @Override
10766        protected boolean allowFilterResult(
10767                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10768            ActivityInfo filterAi = filter.activity.info;
10769            for (int i=dest.size()-1; i>=0; i--) {
10770                ActivityInfo destAi = dest.get(i).activityInfo;
10771                if (destAi.name == filterAi.name
10772                        && destAi.packageName == filterAi.packageName) {
10773                    return false;
10774                }
10775            }
10776            return true;
10777        }
10778
10779        @Override
10780        protected ActivityIntentInfo[] newArray(int size) {
10781            return new ActivityIntentInfo[size];
10782        }
10783
10784        @Override
10785        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10786            if (!sUserManager.exists(userId)) return true;
10787            PackageParser.Package p = filter.activity.owner;
10788            if (p != null) {
10789                PackageSetting ps = (PackageSetting)p.mExtras;
10790                if (ps != null) {
10791                    // System apps are never considered stopped for purposes of
10792                    // filtering, because there may be no way for the user to
10793                    // actually re-launch them.
10794                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10795                            && ps.getStopped(userId);
10796                }
10797            }
10798            return false;
10799        }
10800
10801        @Override
10802        protected boolean isPackageForFilter(String packageName,
10803                PackageParser.ActivityIntentInfo info) {
10804            return packageName.equals(info.activity.owner.packageName);
10805        }
10806
10807        @Override
10808        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10809                int match, int userId) {
10810            if (!sUserManager.exists(userId)) return null;
10811            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10812                return null;
10813            }
10814            final PackageParser.Activity activity = info.activity;
10815            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10816            if (ps == null) {
10817                return null;
10818            }
10819            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10820                    ps.readUserState(userId), userId);
10821            if (ai == null) {
10822                return null;
10823            }
10824            final ResolveInfo res = new ResolveInfo();
10825            res.activityInfo = ai;
10826            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10827                res.filter = info;
10828            }
10829            if (info != null) {
10830                res.handleAllWebDataURI = info.handleAllWebDataURI();
10831            }
10832            res.priority = info.getPriority();
10833            res.preferredOrder = activity.owner.mPreferredOrder;
10834            //System.out.println("Result: " + res.activityInfo.className +
10835            //                   " = " + res.priority);
10836            res.match = match;
10837            res.isDefault = info.hasDefault;
10838            res.labelRes = info.labelRes;
10839            res.nonLocalizedLabel = info.nonLocalizedLabel;
10840            if (userNeedsBadging(userId)) {
10841                res.noResourceId = true;
10842            } else {
10843                res.icon = info.icon;
10844            }
10845            res.iconResourceId = info.icon;
10846            res.system = res.activityInfo.applicationInfo.isSystemApp();
10847            return res;
10848        }
10849
10850        @Override
10851        protected void sortResults(List<ResolveInfo> results) {
10852            Collections.sort(results, mResolvePrioritySorter);
10853        }
10854
10855        @Override
10856        protected void dumpFilter(PrintWriter out, String prefix,
10857                PackageParser.ActivityIntentInfo filter) {
10858            out.print(prefix); out.print(
10859                    Integer.toHexString(System.identityHashCode(filter.activity)));
10860                    out.print(' ');
10861                    filter.activity.printComponentShortName(out);
10862                    out.print(" filter ");
10863                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10864        }
10865
10866        @Override
10867        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10868            return filter.activity;
10869        }
10870
10871        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10872            PackageParser.Activity activity = (PackageParser.Activity)label;
10873            out.print(prefix); out.print(
10874                    Integer.toHexString(System.identityHashCode(activity)));
10875                    out.print(' ');
10876                    activity.printComponentShortName(out);
10877            if (count > 1) {
10878                out.print(" ("); out.print(count); out.print(" filters)");
10879            }
10880            out.println();
10881        }
10882
10883        // Keys are String (activity class name), values are Activity.
10884        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10885                = new ArrayMap<ComponentName, PackageParser.Activity>();
10886        private int mFlags;
10887    }
10888
10889    private final class ServiceIntentResolver
10890            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10891        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10892                boolean defaultOnly, int userId) {
10893            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10894            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10895        }
10896
10897        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10898                int userId) {
10899            if (!sUserManager.exists(userId)) return null;
10900            mFlags = flags;
10901            return super.queryIntent(intent, resolvedType,
10902                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10903        }
10904
10905        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10906                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10907            if (!sUserManager.exists(userId)) return null;
10908            if (packageServices == null) {
10909                return null;
10910            }
10911            mFlags = flags;
10912            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10913            final int N = packageServices.size();
10914            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10915                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10916
10917            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10918            for (int i = 0; i < N; ++i) {
10919                intentFilters = packageServices.get(i).intents;
10920                if (intentFilters != null && intentFilters.size() > 0) {
10921                    PackageParser.ServiceIntentInfo[] array =
10922                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10923                    intentFilters.toArray(array);
10924                    listCut.add(array);
10925                }
10926            }
10927            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10928        }
10929
10930        public final void addService(PackageParser.Service s) {
10931            mServices.put(s.getComponentName(), s);
10932            if (DEBUG_SHOW_INFO) {
10933                Log.v(TAG, "  "
10934                        + (s.info.nonLocalizedLabel != null
10935                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10936                Log.v(TAG, "    Class=" + s.info.name);
10937            }
10938            final int NI = s.intents.size();
10939            int j;
10940            for (j=0; j<NI; j++) {
10941                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10942                if (DEBUG_SHOW_INFO) {
10943                    Log.v(TAG, "    IntentFilter:");
10944                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10945                }
10946                if (!intent.debugCheck()) {
10947                    Log.w(TAG, "==> For Service " + s.info.name);
10948                }
10949                addFilter(intent);
10950            }
10951        }
10952
10953        public final void removeService(PackageParser.Service s) {
10954            mServices.remove(s.getComponentName());
10955            if (DEBUG_SHOW_INFO) {
10956                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10957                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10958                Log.v(TAG, "    Class=" + s.info.name);
10959            }
10960            final int NI = s.intents.size();
10961            int j;
10962            for (j=0; j<NI; j++) {
10963                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10964                if (DEBUG_SHOW_INFO) {
10965                    Log.v(TAG, "    IntentFilter:");
10966                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10967                }
10968                removeFilter(intent);
10969            }
10970        }
10971
10972        @Override
10973        protected boolean allowFilterResult(
10974                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10975            ServiceInfo filterSi = filter.service.info;
10976            for (int i=dest.size()-1; i>=0; i--) {
10977                ServiceInfo destAi = dest.get(i).serviceInfo;
10978                if (destAi.name == filterSi.name
10979                        && destAi.packageName == filterSi.packageName) {
10980                    return false;
10981                }
10982            }
10983            return true;
10984        }
10985
10986        @Override
10987        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10988            return new PackageParser.ServiceIntentInfo[size];
10989        }
10990
10991        @Override
10992        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10993            if (!sUserManager.exists(userId)) return true;
10994            PackageParser.Package p = filter.service.owner;
10995            if (p != null) {
10996                PackageSetting ps = (PackageSetting)p.mExtras;
10997                if (ps != null) {
10998                    // System apps are never considered stopped for purposes of
10999                    // filtering, because there may be no way for the user to
11000                    // actually re-launch them.
11001                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11002                            && ps.getStopped(userId);
11003                }
11004            }
11005            return false;
11006        }
11007
11008        @Override
11009        protected boolean isPackageForFilter(String packageName,
11010                PackageParser.ServiceIntentInfo info) {
11011            return packageName.equals(info.service.owner.packageName);
11012        }
11013
11014        @Override
11015        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11016                int match, int userId) {
11017            if (!sUserManager.exists(userId)) return null;
11018            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11019            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11020                return null;
11021            }
11022            final PackageParser.Service service = info.service;
11023            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11024            if (ps == null) {
11025                return null;
11026            }
11027            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11028                    ps.readUserState(userId), userId);
11029            if (si == null) {
11030                return null;
11031            }
11032            final ResolveInfo res = new ResolveInfo();
11033            res.serviceInfo = si;
11034            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11035                res.filter = filter;
11036            }
11037            res.priority = info.getPriority();
11038            res.preferredOrder = service.owner.mPreferredOrder;
11039            res.match = match;
11040            res.isDefault = info.hasDefault;
11041            res.labelRes = info.labelRes;
11042            res.nonLocalizedLabel = info.nonLocalizedLabel;
11043            res.icon = info.icon;
11044            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11045            return res;
11046        }
11047
11048        @Override
11049        protected void sortResults(List<ResolveInfo> results) {
11050            Collections.sort(results, mResolvePrioritySorter);
11051        }
11052
11053        @Override
11054        protected void dumpFilter(PrintWriter out, String prefix,
11055                PackageParser.ServiceIntentInfo filter) {
11056            out.print(prefix); out.print(
11057                    Integer.toHexString(System.identityHashCode(filter.service)));
11058                    out.print(' ');
11059                    filter.service.printComponentShortName(out);
11060                    out.print(" filter ");
11061                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11062        }
11063
11064        @Override
11065        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11066            return filter.service;
11067        }
11068
11069        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11070            PackageParser.Service service = (PackageParser.Service)label;
11071            out.print(prefix); out.print(
11072                    Integer.toHexString(System.identityHashCode(service)));
11073                    out.print(' ');
11074                    service.printComponentShortName(out);
11075            if (count > 1) {
11076                out.print(" ("); out.print(count); out.print(" filters)");
11077            }
11078            out.println();
11079        }
11080
11081//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11082//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11083//            final List<ResolveInfo> retList = Lists.newArrayList();
11084//            while (i.hasNext()) {
11085//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11086//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11087//                    retList.add(resolveInfo);
11088//                }
11089//            }
11090//            return retList;
11091//        }
11092
11093        // Keys are String (activity class name), values are Activity.
11094        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11095                = new ArrayMap<ComponentName, PackageParser.Service>();
11096        private int mFlags;
11097    };
11098
11099    private final class ProviderIntentResolver
11100            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11101        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11102                boolean defaultOnly, int userId) {
11103            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11104            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11105        }
11106
11107        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11108                int userId) {
11109            if (!sUserManager.exists(userId))
11110                return null;
11111            mFlags = flags;
11112            return super.queryIntent(intent, resolvedType,
11113                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11114        }
11115
11116        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11117                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11118            if (!sUserManager.exists(userId))
11119                return null;
11120            if (packageProviders == null) {
11121                return null;
11122            }
11123            mFlags = flags;
11124            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11125            final int N = packageProviders.size();
11126            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11127                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11128
11129            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11130            for (int i = 0; i < N; ++i) {
11131                intentFilters = packageProviders.get(i).intents;
11132                if (intentFilters != null && intentFilters.size() > 0) {
11133                    PackageParser.ProviderIntentInfo[] array =
11134                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11135                    intentFilters.toArray(array);
11136                    listCut.add(array);
11137                }
11138            }
11139            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11140        }
11141
11142        public final void addProvider(PackageParser.Provider p) {
11143            if (mProviders.containsKey(p.getComponentName())) {
11144                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11145                return;
11146            }
11147
11148            mProviders.put(p.getComponentName(), p);
11149            if (DEBUG_SHOW_INFO) {
11150                Log.v(TAG, "  "
11151                        + (p.info.nonLocalizedLabel != null
11152                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11153                Log.v(TAG, "    Class=" + p.info.name);
11154            }
11155            final int NI = p.intents.size();
11156            int j;
11157            for (j = 0; j < NI; j++) {
11158                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11159                if (DEBUG_SHOW_INFO) {
11160                    Log.v(TAG, "    IntentFilter:");
11161                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11162                }
11163                if (!intent.debugCheck()) {
11164                    Log.w(TAG, "==> For Provider " + p.info.name);
11165                }
11166                addFilter(intent);
11167            }
11168        }
11169
11170        public final void removeProvider(PackageParser.Provider p) {
11171            mProviders.remove(p.getComponentName());
11172            if (DEBUG_SHOW_INFO) {
11173                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11174                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11175                Log.v(TAG, "    Class=" + p.info.name);
11176            }
11177            final int NI = p.intents.size();
11178            int j;
11179            for (j = 0; j < NI; j++) {
11180                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11181                if (DEBUG_SHOW_INFO) {
11182                    Log.v(TAG, "    IntentFilter:");
11183                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11184                }
11185                removeFilter(intent);
11186            }
11187        }
11188
11189        @Override
11190        protected boolean allowFilterResult(
11191                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11192            ProviderInfo filterPi = filter.provider.info;
11193            for (int i = dest.size() - 1; i >= 0; i--) {
11194                ProviderInfo destPi = dest.get(i).providerInfo;
11195                if (destPi.name == filterPi.name
11196                        && destPi.packageName == filterPi.packageName) {
11197                    return false;
11198                }
11199            }
11200            return true;
11201        }
11202
11203        @Override
11204        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11205            return new PackageParser.ProviderIntentInfo[size];
11206        }
11207
11208        @Override
11209        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11210            if (!sUserManager.exists(userId))
11211                return true;
11212            PackageParser.Package p = filter.provider.owner;
11213            if (p != null) {
11214                PackageSetting ps = (PackageSetting) p.mExtras;
11215                if (ps != null) {
11216                    // System apps are never considered stopped for purposes of
11217                    // filtering, because there may be no way for the user to
11218                    // actually re-launch them.
11219                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11220                            && ps.getStopped(userId);
11221                }
11222            }
11223            return false;
11224        }
11225
11226        @Override
11227        protected boolean isPackageForFilter(String packageName,
11228                PackageParser.ProviderIntentInfo info) {
11229            return packageName.equals(info.provider.owner.packageName);
11230        }
11231
11232        @Override
11233        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11234                int match, int userId) {
11235            if (!sUserManager.exists(userId))
11236                return null;
11237            final PackageParser.ProviderIntentInfo info = filter;
11238            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11239                return null;
11240            }
11241            final PackageParser.Provider provider = info.provider;
11242            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11243            if (ps == null) {
11244                return null;
11245            }
11246            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11247                    ps.readUserState(userId), userId);
11248            if (pi == null) {
11249                return null;
11250            }
11251            final ResolveInfo res = new ResolveInfo();
11252            res.providerInfo = pi;
11253            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11254                res.filter = filter;
11255            }
11256            res.priority = info.getPriority();
11257            res.preferredOrder = provider.owner.mPreferredOrder;
11258            res.match = match;
11259            res.isDefault = info.hasDefault;
11260            res.labelRes = info.labelRes;
11261            res.nonLocalizedLabel = info.nonLocalizedLabel;
11262            res.icon = info.icon;
11263            res.system = res.providerInfo.applicationInfo.isSystemApp();
11264            return res;
11265        }
11266
11267        @Override
11268        protected void sortResults(List<ResolveInfo> results) {
11269            Collections.sort(results, mResolvePrioritySorter);
11270        }
11271
11272        @Override
11273        protected void dumpFilter(PrintWriter out, String prefix,
11274                PackageParser.ProviderIntentInfo filter) {
11275            out.print(prefix);
11276            out.print(
11277                    Integer.toHexString(System.identityHashCode(filter.provider)));
11278            out.print(' ');
11279            filter.provider.printComponentShortName(out);
11280            out.print(" filter ");
11281            out.println(Integer.toHexString(System.identityHashCode(filter)));
11282        }
11283
11284        @Override
11285        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11286            return filter.provider;
11287        }
11288
11289        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11290            PackageParser.Provider provider = (PackageParser.Provider)label;
11291            out.print(prefix); out.print(
11292                    Integer.toHexString(System.identityHashCode(provider)));
11293                    out.print(' ');
11294                    provider.printComponentShortName(out);
11295            if (count > 1) {
11296                out.print(" ("); out.print(count); out.print(" filters)");
11297            }
11298            out.println();
11299        }
11300
11301        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11302                = new ArrayMap<ComponentName, PackageParser.Provider>();
11303        private int mFlags;
11304    }
11305
11306    private static final class EphemeralIntentResolver
11307            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11308        /**
11309         * The result that has the highest defined order. Ordering applies on a
11310         * per-package basis. Mapping is from package name to Pair of order and
11311         * EphemeralResolveInfo.
11312         * <p>
11313         * NOTE: This is implemented as a field variable for convenience and efficiency.
11314         * By having a field variable, we're able to track filter ordering as soon as
11315         * a non-zero order is defined. Otherwise, multiple loops across the result set
11316         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11317         * this needs to be contained entirely within {@link #filterResults()}.
11318         */
11319        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11320
11321        @Override
11322        protected EphemeralResolveIntentInfo[] newArray(int size) {
11323            return new EphemeralResolveIntentInfo[size];
11324        }
11325
11326        @Override
11327        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11328            return true;
11329        }
11330
11331        @Override
11332        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11333                int userId) {
11334            if (!sUserManager.exists(userId)) {
11335                return null;
11336            }
11337            final String packageName = info.getEphemeralResolveInfo().getPackageName();
11338            final Integer order = info.getOrder();
11339            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11340                    mOrderResult.get(packageName);
11341            // ordering is enabled and this item's order isn't high enough
11342            if (lastOrderResult != null && lastOrderResult.first >= order) {
11343                return null;
11344            }
11345            final EphemeralResolveInfo res = info.getEphemeralResolveInfo();
11346            if (order > 0) {
11347                // non-zero order, enable ordering
11348                mOrderResult.put(packageName, new Pair<>(order, res));
11349            }
11350            return res;
11351        }
11352
11353        @Override
11354        protected void filterResults(List<EphemeralResolveInfo> results) {
11355            // only do work if ordering is enabled [most of the time it won't be]
11356            if (mOrderResult.size() == 0) {
11357                return;
11358            }
11359            int resultSize = results.size();
11360            for (int i = 0; i < resultSize; i++) {
11361                final EphemeralResolveInfo info = results.get(i);
11362                final String packageName = info.getPackageName();
11363                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11364                if (savedInfo == null) {
11365                    // package doesn't having ordering
11366                    continue;
11367                }
11368                if (savedInfo.second == info) {
11369                    // circled back to the highest ordered item; remove from order list
11370                    mOrderResult.remove(savedInfo);
11371                    if (mOrderResult.size() == 0) {
11372                        // no more ordered items
11373                        break;
11374                    }
11375                    continue;
11376                }
11377                // item has a worse order, remove it from the result list
11378                results.remove(i);
11379                resultSize--;
11380                i--;
11381            }
11382        }
11383    }
11384
11385    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11386            new Comparator<ResolveInfo>() {
11387        public int compare(ResolveInfo r1, ResolveInfo r2) {
11388            int v1 = r1.priority;
11389            int v2 = r2.priority;
11390            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11391            if (v1 != v2) {
11392                return (v1 > v2) ? -1 : 1;
11393            }
11394            v1 = r1.preferredOrder;
11395            v2 = r2.preferredOrder;
11396            if (v1 != v2) {
11397                return (v1 > v2) ? -1 : 1;
11398            }
11399            if (r1.isDefault != r2.isDefault) {
11400                return r1.isDefault ? -1 : 1;
11401            }
11402            v1 = r1.match;
11403            v2 = r2.match;
11404            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11405            if (v1 != v2) {
11406                return (v1 > v2) ? -1 : 1;
11407            }
11408            if (r1.system != r2.system) {
11409                return r1.system ? -1 : 1;
11410            }
11411            if (r1.activityInfo != null) {
11412                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11413            }
11414            if (r1.serviceInfo != null) {
11415                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11416            }
11417            if (r1.providerInfo != null) {
11418                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11419            }
11420            return 0;
11421        }
11422    };
11423
11424    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11425            new Comparator<ProviderInfo>() {
11426        public int compare(ProviderInfo p1, ProviderInfo p2) {
11427            final int v1 = p1.initOrder;
11428            final int v2 = p2.initOrder;
11429            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11430        }
11431    };
11432
11433    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11434            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11435            final int[] userIds) {
11436        mHandler.post(new Runnable() {
11437            @Override
11438            public void run() {
11439                try {
11440                    final IActivityManager am = ActivityManagerNative.getDefault();
11441                    if (am == null) return;
11442                    final int[] resolvedUserIds;
11443                    if (userIds == null) {
11444                        resolvedUserIds = am.getRunningUserIds();
11445                    } else {
11446                        resolvedUserIds = userIds;
11447                    }
11448                    for (int id : resolvedUserIds) {
11449                        final Intent intent = new Intent(action,
11450                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11451                        if (extras != null) {
11452                            intent.putExtras(extras);
11453                        }
11454                        if (targetPkg != null) {
11455                            intent.setPackage(targetPkg);
11456                        }
11457                        // Modify the UID when posting to other users
11458                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11459                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11460                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11461                            intent.putExtra(Intent.EXTRA_UID, uid);
11462                        }
11463                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11464                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11465                        if (DEBUG_BROADCASTS) {
11466                            RuntimeException here = new RuntimeException("here");
11467                            here.fillInStackTrace();
11468                            Slog.d(TAG, "Sending to user " + id + ": "
11469                                    + intent.toShortString(false, true, false, false)
11470                                    + " " + intent.getExtras(), here);
11471                        }
11472                        am.broadcastIntent(null, intent, null, finishedReceiver,
11473                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11474                                null, finishedReceiver != null, false, id);
11475                    }
11476                } catch (RemoteException ex) {
11477                }
11478            }
11479        });
11480    }
11481
11482    /**
11483     * Check if the external storage media is available. This is true if there
11484     * is a mounted external storage medium or if the external storage is
11485     * emulated.
11486     */
11487    private boolean isExternalMediaAvailable() {
11488        return mMediaMounted || Environment.isExternalStorageEmulated();
11489    }
11490
11491    @Override
11492    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11493        // writer
11494        synchronized (mPackages) {
11495            if (!isExternalMediaAvailable()) {
11496                // If the external storage is no longer mounted at this point,
11497                // the caller may not have been able to delete all of this
11498                // packages files and can not delete any more.  Bail.
11499                return null;
11500            }
11501            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11502            if (lastPackage != null) {
11503                pkgs.remove(lastPackage);
11504            }
11505            if (pkgs.size() > 0) {
11506                return pkgs.get(0);
11507            }
11508        }
11509        return null;
11510    }
11511
11512    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11513        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11514                userId, andCode ? 1 : 0, packageName);
11515        if (mSystemReady) {
11516            msg.sendToTarget();
11517        } else {
11518            if (mPostSystemReadyMessages == null) {
11519                mPostSystemReadyMessages = new ArrayList<>();
11520            }
11521            mPostSystemReadyMessages.add(msg);
11522        }
11523    }
11524
11525    void startCleaningPackages() {
11526        // reader
11527        if (!isExternalMediaAvailable()) {
11528            return;
11529        }
11530        synchronized (mPackages) {
11531            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11532                return;
11533            }
11534        }
11535        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11536        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11537        IActivityManager am = ActivityManagerNative.getDefault();
11538        if (am != null) {
11539            try {
11540                am.startService(null, intent, null, mContext.getOpPackageName(),
11541                        UserHandle.USER_SYSTEM);
11542            } catch (RemoteException e) {
11543            }
11544        }
11545    }
11546
11547    @Override
11548    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11549            int installFlags, String installerPackageName, int userId) {
11550        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11551
11552        final int callingUid = Binder.getCallingUid();
11553        enforceCrossUserPermission(callingUid, userId,
11554                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11555
11556        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11557            try {
11558                if (observer != null) {
11559                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11560                }
11561            } catch (RemoteException re) {
11562            }
11563            return;
11564        }
11565
11566        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11567            installFlags |= PackageManager.INSTALL_FROM_ADB;
11568
11569        } else {
11570            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11571            // about installerPackageName.
11572
11573            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11574            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11575        }
11576
11577        UserHandle user;
11578        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11579            user = UserHandle.ALL;
11580        } else {
11581            user = new UserHandle(userId);
11582        }
11583
11584        // Only system components can circumvent runtime permissions when installing.
11585        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11586                && mContext.checkCallingOrSelfPermission(Manifest.permission
11587                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11588            throw new SecurityException("You need the "
11589                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11590                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11591        }
11592
11593        final File originFile = new File(originPath);
11594        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11595
11596        final Message msg = mHandler.obtainMessage(INIT_COPY);
11597        final VerificationInfo verificationInfo = new VerificationInfo(
11598                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11599        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11600                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11601                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11602                null /*certificates*/);
11603        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11604        msg.obj = params;
11605
11606        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11607                System.identityHashCode(msg.obj));
11608        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11609                System.identityHashCode(msg.obj));
11610
11611        mHandler.sendMessage(msg);
11612    }
11613
11614    void installStage(String packageName, File stagedDir, String stagedCid,
11615            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11616            String installerPackageName, int installerUid, UserHandle user,
11617            Certificate[][] certificates) {
11618        if (DEBUG_EPHEMERAL) {
11619            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11620                Slog.d(TAG, "Ephemeral install of " + packageName);
11621            }
11622        }
11623        final VerificationInfo verificationInfo = new VerificationInfo(
11624                sessionParams.originatingUri, sessionParams.referrerUri,
11625                sessionParams.originatingUid, installerUid);
11626
11627        final OriginInfo origin;
11628        if (stagedDir != null) {
11629            origin = OriginInfo.fromStagedFile(stagedDir);
11630        } else {
11631            origin = OriginInfo.fromStagedContainer(stagedCid);
11632        }
11633
11634        final Message msg = mHandler.obtainMessage(INIT_COPY);
11635        final InstallParams params = new InstallParams(origin, null, observer,
11636                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11637                verificationInfo, user, sessionParams.abiOverride,
11638                sessionParams.grantedRuntimePermissions, certificates);
11639        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11640        msg.obj = params;
11641
11642        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11643                System.identityHashCode(msg.obj));
11644        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11645                System.identityHashCode(msg.obj));
11646
11647        mHandler.sendMessage(msg);
11648    }
11649
11650    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11651            int userId) {
11652        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11653        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11654    }
11655
11656    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11657            int appId, int userId) {
11658        Bundle extras = new Bundle(1);
11659        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11660
11661        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11662                packageName, extras, 0, null, null, new int[] {userId});
11663        try {
11664            IActivityManager am = ActivityManagerNative.getDefault();
11665            if (isSystem && am.isUserRunning(userId, 0)) {
11666                // The just-installed/enabled app is bundled on the system, so presumed
11667                // to be able to run automatically without needing an explicit launch.
11668                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11669                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11670                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11671                        .setPackage(packageName);
11672                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11673                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11674            }
11675        } catch (RemoteException e) {
11676            // shouldn't happen
11677            Slog.w(TAG, "Unable to bootstrap installed package", e);
11678        }
11679    }
11680
11681    @Override
11682    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11683            int userId) {
11684        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11685        PackageSetting pkgSetting;
11686        final int uid = Binder.getCallingUid();
11687        enforceCrossUserPermission(uid, userId,
11688                true /* requireFullPermission */, true /* checkShell */,
11689                "setApplicationHiddenSetting for user " + userId);
11690
11691        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11692            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11693            return false;
11694        }
11695
11696        long callingId = Binder.clearCallingIdentity();
11697        try {
11698            boolean sendAdded = false;
11699            boolean sendRemoved = false;
11700            // writer
11701            synchronized (mPackages) {
11702                pkgSetting = mSettings.mPackages.get(packageName);
11703                if (pkgSetting == null) {
11704                    return false;
11705                }
11706                // Do not allow "android" is being disabled
11707                if ("android".equals(packageName)) {
11708                    Slog.w(TAG, "Cannot hide package: android");
11709                    return false;
11710                }
11711                // Only allow protected packages to hide themselves.
11712                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11713                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11714                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11715                    return false;
11716                }
11717
11718                if (pkgSetting.getHidden(userId) != hidden) {
11719                    pkgSetting.setHidden(hidden, userId);
11720                    mSettings.writePackageRestrictionsLPr(userId);
11721                    if (hidden) {
11722                        sendRemoved = true;
11723                    } else {
11724                        sendAdded = true;
11725                    }
11726                }
11727            }
11728            if (sendAdded) {
11729                sendPackageAddedForUser(packageName, pkgSetting, userId);
11730                return true;
11731            }
11732            if (sendRemoved) {
11733                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11734                        "hiding pkg");
11735                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11736                return true;
11737            }
11738        } finally {
11739            Binder.restoreCallingIdentity(callingId);
11740        }
11741        return false;
11742    }
11743
11744    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11745            int userId) {
11746        final PackageRemovedInfo info = new PackageRemovedInfo();
11747        info.removedPackage = packageName;
11748        info.removedUsers = new int[] {userId};
11749        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11750        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11751    }
11752
11753    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11754        if (pkgList.length > 0) {
11755            Bundle extras = new Bundle(1);
11756            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11757
11758            sendPackageBroadcast(
11759                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11760                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11761                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11762                    new int[] {userId});
11763        }
11764    }
11765
11766    /**
11767     * Returns true if application is not found or there was an error. Otherwise it returns
11768     * the hidden state of the package for the given user.
11769     */
11770    @Override
11771    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11772        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11773        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11774                true /* requireFullPermission */, false /* checkShell */,
11775                "getApplicationHidden for user " + userId);
11776        PackageSetting pkgSetting;
11777        long callingId = Binder.clearCallingIdentity();
11778        try {
11779            // writer
11780            synchronized (mPackages) {
11781                pkgSetting = mSettings.mPackages.get(packageName);
11782                if (pkgSetting == null) {
11783                    return true;
11784                }
11785                return pkgSetting.getHidden(userId);
11786            }
11787        } finally {
11788            Binder.restoreCallingIdentity(callingId);
11789        }
11790    }
11791
11792    /**
11793     * @hide
11794     */
11795    @Override
11796    public int installExistingPackageAsUser(String packageName, int userId) {
11797        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11798                null);
11799        PackageSetting pkgSetting;
11800        final int uid = Binder.getCallingUid();
11801        enforceCrossUserPermission(uid, userId,
11802                true /* requireFullPermission */, true /* checkShell */,
11803                "installExistingPackage for user " + userId);
11804        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11805            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11806        }
11807
11808        long callingId = Binder.clearCallingIdentity();
11809        try {
11810            boolean installed = false;
11811
11812            // writer
11813            synchronized (mPackages) {
11814                pkgSetting = mSettings.mPackages.get(packageName);
11815                if (pkgSetting == null) {
11816                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11817                }
11818                if (!pkgSetting.getInstalled(userId)) {
11819                    pkgSetting.setInstalled(true, userId);
11820                    pkgSetting.setHidden(false, userId);
11821                    mSettings.writePackageRestrictionsLPr(userId);
11822                    installed = true;
11823                }
11824            }
11825
11826            if (installed) {
11827                if (pkgSetting.pkg != null) {
11828                    synchronized (mInstallLock) {
11829                        // We don't need to freeze for a brand new install
11830                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11831                    }
11832                }
11833                sendPackageAddedForUser(packageName, pkgSetting, userId);
11834            }
11835        } finally {
11836            Binder.restoreCallingIdentity(callingId);
11837        }
11838
11839        return PackageManager.INSTALL_SUCCEEDED;
11840    }
11841
11842    boolean isUserRestricted(int userId, String restrictionKey) {
11843        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11844        if (restrictions.getBoolean(restrictionKey, false)) {
11845            Log.w(TAG, "User is restricted: " + restrictionKey);
11846            return true;
11847        }
11848        return false;
11849    }
11850
11851    @Override
11852    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11853            int userId) {
11854        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11855        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11856                true /* requireFullPermission */, true /* checkShell */,
11857                "setPackagesSuspended for user " + userId);
11858
11859        if (ArrayUtils.isEmpty(packageNames)) {
11860            return packageNames;
11861        }
11862
11863        // List of package names for whom the suspended state has changed.
11864        List<String> changedPackages = new ArrayList<>(packageNames.length);
11865        // List of package names for whom the suspended state is not set as requested in this
11866        // method.
11867        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11868        long callingId = Binder.clearCallingIdentity();
11869        try {
11870            for (int i = 0; i < packageNames.length; i++) {
11871                String packageName = packageNames[i];
11872                boolean changed = false;
11873                final int appId;
11874                synchronized (mPackages) {
11875                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11876                    if (pkgSetting == null) {
11877                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11878                                + "\". Skipping suspending/un-suspending.");
11879                        unactionedPackages.add(packageName);
11880                        continue;
11881                    }
11882                    appId = pkgSetting.appId;
11883                    if (pkgSetting.getSuspended(userId) != suspended) {
11884                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11885                            unactionedPackages.add(packageName);
11886                            continue;
11887                        }
11888                        pkgSetting.setSuspended(suspended, userId);
11889                        mSettings.writePackageRestrictionsLPr(userId);
11890                        changed = true;
11891                        changedPackages.add(packageName);
11892                    }
11893                }
11894
11895                if (changed && suspended) {
11896                    killApplication(packageName, UserHandle.getUid(userId, appId),
11897                            "suspending package");
11898                }
11899            }
11900        } finally {
11901            Binder.restoreCallingIdentity(callingId);
11902        }
11903
11904        if (!changedPackages.isEmpty()) {
11905            sendPackagesSuspendedForUser(changedPackages.toArray(
11906                    new String[changedPackages.size()]), userId, suspended);
11907        }
11908
11909        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11910    }
11911
11912    @Override
11913    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11914        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11915                true /* requireFullPermission */, false /* checkShell */,
11916                "isPackageSuspendedForUser for user " + userId);
11917        synchronized (mPackages) {
11918            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11919            if (pkgSetting == null) {
11920                throw new IllegalArgumentException("Unknown target package: " + packageName);
11921            }
11922            return pkgSetting.getSuspended(userId);
11923        }
11924    }
11925
11926    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11927        if (isPackageDeviceAdmin(packageName, userId)) {
11928            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11929                    + "\": has an active device admin");
11930            return false;
11931        }
11932
11933        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11934        if (packageName.equals(activeLauncherPackageName)) {
11935            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11936                    + "\": contains the active launcher");
11937            return false;
11938        }
11939
11940        if (packageName.equals(mRequiredInstallerPackage)) {
11941            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11942                    + "\": required for package installation");
11943            return false;
11944        }
11945
11946        if (packageName.equals(mRequiredUninstallerPackage)) {
11947            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11948                    + "\": required for package uninstallation");
11949            return false;
11950        }
11951
11952        if (packageName.equals(mRequiredVerifierPackage)) {
11953            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11954                    + "\": required for package verification");
11955            return false;
11956        }
11957
11958        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11959            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11960                    + "\": is the default dialer");
11961            return false;
11962        }
11963
11964        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11965            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11966                    + "\": protected package");
11967            return false;
11968        }
11969
11970        return true;
11971    }
11972
11973    private String getActiveLauncherPackageName(int userId) {
11974        Intent intent = new Intent(Intent.ACTION_MAIN);
11975        intent.addCategory(Intent.CATEGORY_HOME);
11976        ResolveInfo resolveInfo = resolveIntent(
11977                intent,
11978                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11979                PackageManager.MATCH_DEFAULT_ONLY,
11980                userId);
11981
11982        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11983    }
11984
11985    private String getDefaultDialerPackageName(int userId) {
11986        synchronized (mPackages) {
11987            return mSettings.getDefaultDialerPackageNameLPw(userId);
11988        }
11989    }
11990
11991    @Override
11992    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11993        mContext.enforceCallingOrSelfPermission(
11994                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11995                "Only package verification agents can verify applications");
11996
11997        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11998        final PackageVerificationResponse response = new PackageVerificationResponse(
11999                verificationCode, Binder.getCallingUid());
12000        msg.arg1 = id;
12001        msg.obj = response;
12002        mHandler.sendMessage(msg);
12003    }
12004
12005    @Override
12006    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12007            long millisecondsToDelay) {
12008        mContext.enforceCallingOrSelfPermission(
12009                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12010                "Only package verification agents can extend verification timeouts");
12011
12012        final PackageVerificationState state = mPendingVerification.get(id);
12013        final PackageVerificationResponse response = new PackageVerificationResponse(
12014                verificationCodeAtTimeout, Binder.getCallingUid());
12015
12016        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12017            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12018        }
12019        if (millisecondsToDelay < 0) {
12020            millisecondsToDelay = 0;
12021        }
12022        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12023                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12024            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12025        }
12026
12027        if ((state != null) && !state.timeoutExtended()) {
12028            state.extendTimeout();
12029
12030            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12031            msg.arg1 = id;
12032            msg.obj = response;
12033            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12034        }
12035    }
12036
12037    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12038            int verificationCode, UserHandle user) {
12039        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12040        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12041        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12042        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12043        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12044
12045        mContext.sendBroadcastAsUser(intent, user,
12046                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12047    }
12048
12049    private ComponentName matchComponentForVerifier(String packageName,
12050            List<ResolveInfo> receivers) {
12051        ActivityInfo targetReceiver = null;
12052
12053        final int NR = receivers.size();
12054        for (int i = 0; i < NR; i++) {
12055            final ResolveInfo info = receivers.get(i);
12056            if (info.activityInfo == null) {
12057                continue;
12058            }
12059
12060            if (packageName.equals(info.activityInfo.packageName)) {
12061                targetReceiver = info.activityInfo;
12062                break;
12063            }
12064        }
12065
12066        if (targetReceiver == null) {
12067            return null;
12068        }
12069
12070        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12071    }
12072
12073    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12074            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12075        if (pkgInfo.verifiers.length == 0) {
12076            return null;
12077        }
12078
12079        final int N = pkgInfo.verifiers.length;
12080        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12081        for (int i = 0; i < N; i++) {
12082            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12083
12084            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12085                    receivers);
12086            if (comp == null) {
12087                continue;
12088            }
12089
12090            final int verifierUid = getUidForVerifier(verifierInfo);
12091            if (verifierUid == -1) {
12092                continue;
12093            }
12094
12095            if (DEBUG_VERIFY) {
12096                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12097                        + " with the correct signature");
12098            }
12099            sufficientVerifiers.add(comp);
12100            verificationState.addSufficientVerifier(verifierUid);
12101        }
12102
12103        return sufficientVerifiers;
12104    }
12105
12106    private int getUidForVerifier(VerifierInfo verifierInfo) {
12107        synchronized (mPackages) {
12108            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12109            if (pkg == null) {
12110                return -1;
12111            } else if (pkg.mSignatures.length != 1) {
12112                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12113                        + " has more than one signature; ignoring");
12114                return -1;
12115            }
12116
12117            /*
12118             * If the public key of the package's signature does not match
12119             * our expected public key, then this is a different package and
12120             * we should skip.
12121             */
12122
12123            final byte[] expectedPublicKey;
12124            try {
12125                final Signature verifierSig = pkg.mSignatures[0];
12126                final PublicKey publicKey = verifierSig.getPublicKey();
12127                expectedPublicKey = publicKey.getEncoded();
12128            } catch (CertificateException e) {
12129                return -1;
12130            }
12131
12132            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12133
12134            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12135                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12136                        + " does not have the expected public key; ignoring");
12137                return -1;
12138            }
12139
12140            return pkg.applicationInfo.uid;
12141        }
12142    }
12143
12144    @Override
12145    public void finishPackageInstall(int token, boolean didLaunch) {
12146        enforceSystemOrRoot("Only the system is allowed to finish installs");
12147
12148        if (DEBUG_INSTALL) {
12149            Slog.v(TAG, "BM finishing package install for " + token);
12150        }
12151        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12152
12153        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12154        mHandler.sendMessage(msg);
12155    }
12156
12157    /**
12158     * Get the verification agent timeout.
12159     *
12160     * @return verification timeout in milliseconds
12161     */
12162    private long getVerificationTimeout() {
12163        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12164                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12165                DEFAULT_VERIFICATION_TIMEOUT);
12166    }
12167
12168    /**
12169     * Get the default verification agent response code.
12170     *
12171     * @return default verification response code
12172     */
12173    private int getDefaultVerificationResponse() {
12174        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12175                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12176                DEFAULT_VERIFICATION_RESPONSE);
12177    }
12178
12179    /**
12180     * Check whether or not package verification has been enabled.
12181     *
12182     * @return true if verification should be performed
12183     */
12184    private boolean isVerificationEnabled(int userId, int installFlags) {
12185        if (!DEFAULT_VERIFY_ENABLE) {
12186            return false;
12187        }
12188        // Ephemeral apps don't get the full verification treatment
12189        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12190            if (DEBUG_EPHEMERAL) {
12191                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12192            }
12193            return false;
12194        }
12195
12196        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12197
12198        // Check if installing from ADB
12199        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12200            // Do not run verification in a test harness environment
12201            if (ActivityManager.isRunningInTestHarness()) {
12202                return false;
12203            }
12204            if (ensureVerifyAppsEnabled) {
12205                return true;
12206            }
12207            // Check if the developer does not want package verification for ADB installs
12208            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12209                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12210                return false;
12211            }
12212        }
12213
12214        if (ensureVerifyAppsEnabled) {
12215            return true;
12216        }
12217
12218        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12219                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12220    }
12221
12222    @Override
12223    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12224            throws RemoteException {
12225        mContext.enforceCallingOrSelfPermission(
12226                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12227                "Only intentfilter verification agents can verify applications");
12228
12229        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12230        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12231                Binder.getCallingUid(), verificationCode, failedDomains);
12232        msg.arg1 = id;
12233        msg.obj = response;
12234        mHandler.sendMessage(msg);
12235    }
12236
12237    @Override
12238    public int getIntentVerificationStatus(String packageName, int userId) {
12239        synchronized (mPackages) {
12240            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12241        }
12242    }
12243
12244    @Override
12245    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12246        mContext.enforceCallingOrSelfPermission(
12247                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12248
12249        boolean result = false;
12250        synchronized (mPackages) {
12251            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12252        }
12253        if (result) {
12254            scheduleWritePackageRestrictionsLocked(userId);
12255        }
12256        return result;
12257    }
12258
12259    @Override
12260    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12261            String packageName) {
12262        synchronized (mPackages) {
12263            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12264        }
12265    }
12266
12267    @Override
12268    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12269        if (TextUtils.isEmpty(packageName)) {
12270            return ParceledListSlice.emptyList();
12271        }
12272        synchronized (mPackages) {
12273            PackageParser.Package pkg = mPackages.get(packageName);
12274            if (pkg == null || pkg.activities == null) {
12275                return ParceledListSlice.emptyList();
12276            }
12277            final int count = pkg.activities.size();
12278            ArrayList<IntentFilter> result = new ArrayList<>();
12279            for (int n=0; n<count; n++) {
12280                PackageParser.Activity activity = pkg.activities.get(n);
12281                if (activity.intents != null && activity.intents.size() > 0) {
12282                    result.addAll(activity.intents);
12283                }
12284            }
12285            return new ParceledListSlice<>(result);
12286        }
12287    }
12288
12289    @Override
12290    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12291        mContext.enforceCallingOrSelfPermission(
12292                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12293
12294        synchronized (mPackages) {
12295            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12296            if (packageName != null) {
12297                result |= updateIntentVerificationStatus(packageName,
12298                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12299                        userId);
12300                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12301                        packageName, userId);
12302            }
12303            return result;
12304        }
12305    }
12306
12307    @Override
12308    public String getDefaultBrowserPackageName(int userId) {
12309        synchronized (mPackages) {
12310            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12311        }
12312    }
12313
12314    /**
12315     * Get the "allow unknown sources" setting.
12316     *
12317     * @return the current "allow unknown sources" setting
12318     */
12319    private int getUnknownSourcesSettings() {
12320        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12321                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12322                -1);
12323    }
12324
12325    @Override
12326    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12327        final int uid = Binder.getCallingUid();
12328        // writer
12329        synchronized (mPackages) {
12330            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12331            if (targetPackageSetting == null) {
12332                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12333            }
12334
12335            PackageSetting installerPackageSetting;
12336            if (installerPackageName != null) {
12337                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12338                if (installerPackageSetting == null) {
12339                    throw new IllegalArgumentException("Unknown installer package: "
12340                            + installerPackageName);
12341                }
12342            } else {
12343                installerPackageSetting = null;
12344            }
12345
12346            Signature[] callerSignature;
12347            Object obj = mSettings.getUserIdLPr(uid);
12348            if (obj != null) {
12349                if (obj instanceof SharedUserSetting) {
12350                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12351                } else if (obj instanceof PackageSetting) {
12352                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12353                } else {
12354                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12355                }
12356            } else {
12357                throw new SecurityException("Unknown calling UID: " + uid);
12358            }
12359
12360            // Verify: can't set installerPackageName to a package that is
12361            // not signed with the same cert as the caller.
12362            if (installerPackageSetting != null) {
12363                if (compareSignatures(callerSignature,
12364                        installerPackageSetting.signatures.mSignatures)
12365                        != PackageManager.SIGNATURE_MATCH) {
12366                    throw new SecurityException(
12367                            "Caller does not have same cert as new installer package "
12368                            + installerPackageName);
12369                }
12370            }
12371
12372            // Verify: if target already has an installer package, it must
12373            // be signed with the same cert as the caller.
12374            if (targetPackageSetting.installerPackageName != null) {
12375                PackageSetting setting = mSettings.mPackages.get(
12376                        targetPackageSetting.installerPackageName);
12377                // If the currently set package isn't valid, then it's always
12378                // okay to change it.
12379                if (setting != null) {
12380                    if (compareSignatures(callerSignature,
12381                            setting.signatures.mSignatures)
12382                            != PackageManager.SIGNATURE_MATCH) {
12383                        throw new SecurityException(
12384                                "Caller does not have same cert as old installer package "
12385                                + targetPackageSetting.installerPackageName);
12386                    }
12387                }
12388            }
12389
12390            // Okay!
12391            targetPackageSetting.installerPackageName = installerPackageName;
12392            if (installerPackageName != null) {
12393                mSettings.mInstallerPackages.add(installerPackageName);
12394            }
12395            scheduleWriteSettingsLocked();
12396        }
12397    }
12398
12399    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12400        // Queue up an async operation since the package installation may take a little while.
12401        mHandler.post(new Runnable() {
12402            public void run() {
12403                mHandler.removeCallbacks(this);
12404                 // Result object to be returned
12405                PackageInstalledInfo res = new PackageInstalledInfo();
12406                res.setReturnCode(currentStatus);
12407                res.uid = -1;
12408                res.pkg = null;
12409                res.removedInfo = null;
12410                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12411                    args.doPreInstall(res.returnCode);
12412                    synchronized (mInstallLock) {
12413                        installPackageTracedLI(args, res);
12414                    }
12415                    args.doPostInstall(res.returnCode, res.uid);
12416                }
12417
12418                // A restore should be performed at this point if (a) the install
12419                // succeeded, (b) the operation is not an update, and (c) the new
12420                // package has not opted out of backup participation.
12421                final boolean update = res.removedInfo != null
12422                        && res.removedInfo.removedPackage != null;
12423                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12424                boolean doRestore = !update
12425                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12426
12427                // Set up the post-install work request bookkeeping.  This will be used
12428                // and cleaned up by the post-install event handling regardless of whether
12429                // there's a restore pass performed.  Token values are >= 1.
12430                int token;
12431                if (mNextInstallToken < 0) mNextInstallToken = 1;
12432                token = mNextInstallToken++;
12433
12434                PostInstallData data = new PostInstallData(args, res);
12435                mRunningInstalls.put(token, data);
12436                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12437
12438                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12439                    // Pass responsibility to the Backup Manager.  It will perform a
12440                    // restore if appropriate, then pass responsibility back to the
12441                    // Package Manager to run the post-install observer callbacks
12442                    // and broadcasts.
12443                    IBackupManager bm = IBackupManager.Stub.asInterface(
12444                            ServiceManager.getService(Context.BACKUP_SERVICE));
12445                    if (bm != null) {
12446                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12447                                + " to BM for possible restore");
12448                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12449                        try {
12450                            // TODO: http://b/22388012
12451                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12452                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12453                            } else {
12454                                doRestore = false;
12455                            }
12456                        } catch (RemoteException e) {
12457                            // can't happen; the backup manager is local
12458                        } catch (Exception e) {
12459                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12460                            doRestore = false;
12461                        }
12462                    } else {
12463                        Slog.e(TAG, "Backup Manager not found!");
12464                        doRestore = false;
12465                    }
12466                }
12467
12468                if (!doRestore) {
12469                    // No restore possible, or the Backup Manager was mysteriously not
12470                    // available -- just fire the post-install work request directly.
12471                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12472
12473                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12474
12475                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12476                    mHandler.sendMessage(msg);
12477                }
12478            }
12479        });
12480    }
12481
12482    /**
12483     * Callback from PackageSettings whenever an app is first transitioned out of the
12484     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12485     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12486     * here whether the app is the target of an ongoing install, and only send the
12487     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12488     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12489     * handling.
12490     */
12491    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12492        // Serialize this with the rest of the install-process message chain.  In the
12493        // restore-at-install case, this Runnable will necessarily run before the
12494        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12495        // are coherent.  In the non-restore case, the app has already completed install
12496        // and been launched through some other means, so it is not in a problematic
12497        // state for observers to see the FIRST_LAUNCH signal.
12498        mHandler.post(new Runnable() {
12499            @Override
12500            public void run() {
12501                for (int i = 0; i < mRunningInstalls.size(); i++) {
12502                    final PostInstallData data = mRunningInstalls.valueAt(i);
12503                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12504                        continue;
12505                    }
12506                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12507                        // right package; but is it for the right user?
12508                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12509                            if (userId == data.res.newUsers[uIndex]) {
12510                                if (DEBUG_BACKUP) {
12511                                    Slog.i(TAG, "Package " + pkgName
12512                                            + " being restored so deferring FIRST_LAUNCH");
12513                                }
12514                                return;
12515                            }
12516                        }
12517                    }
12518                }
12519                // didn't find it, so not being restored
12520                if (DEBUG_BACKUP) {
12521                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12522                }
12523                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12524            }
12525        });
12526    }
12527
12528    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12529        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12530                installerPkg, null, userIds);
12531    }
12532
12533    private abstract class HandlerParams {
12534        private static final int MAX_RETRIES = 4;
12535
12536        /**
12537         * Number of times startCopy() has been attempted and had a non-fatal
12538         * error.
12539         */
12540        private int mRetries = 0;
12541
12542        /** User handle for the user requesting the information or installation. */
12543        private final UserHandle mUser;
12544        String traceMethod;
12545        int traceCookie;
12546
12547        HandlerParams(UserHandle user) {
12548            mUser = user;
12549        }
12550
12551        UserHandle getUser() {
12552            return mUser;
12553        }
12554
12555        HandlerParams setTraceMethod(String traceMethod) {
12556            this.traceMethod = traceMethod;
12557            return this;
12558        }
12559
12560        HandlerParams setTraceCookie(int traceCookie) {
12561            this.traceCookie = traceCookie;
12562            return this;
12563        }
12564
12565        final boolean startCopy() {
12566            boolean res;
12567            try {
12568                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12569
12570                if (++mRetries > MAX_RETRIES) {
12571                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12572                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12573                    handleServiceError();
12574                    return false;
12575                } else {
12576                    handleStartCopy();
12577                    res = true;
12578                }
12579            } catch (RemoteException e) {
12580                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12581                mHandler.sendEmptyMessage(MCS_RECONNECT);
12582                res = false;
12583            }
12584            handleReturnCode();
12585            return res;
12586        }
12587
12588        final void serviceError() {
12589            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12590            handleServiceError();
12591            handleReturnCode();
12592        }
12593
12594        abstract void handleStartCopy() throws RemoteException;
12595        abstract void handleServiceError();
12596        abstract void handleReturnCode();
12597    }
12598
12599    class MeasureParams extends HandlerParams {
12600        private final PackageStats mStats;
12601        private boolean mSuccess;
12602
12603        private final IPackageStatsObserver mObserver;
12604
12605        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12606            super(new UserHandle(stats.userHandle));
12607            mObserver = observer;
12608            mStats = stats;
12609        }
12610
12611        @Override
12612        public String toString() {
12613            return "MeasureParams{"
12614                + Integer.toHexString(System.identityHashCode(this))
12615                + " " + mStats.packageName + "}";
12616        }
12617
12618        @Override
12619        void handleStartCopy() throws RemoteException {
12620            synchronized (mInstallLock) {
12621                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12622            }
12623
12624            if (mSuccess) {
12625                boolean mounted = false;
12626                try {
12627                    final String status = Environment.getExternalStorageState();
12628                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12629                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12630                } catch (Exception e) {
12631                }
12632
12633                if (mounted) {
12634                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12635
12636                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12637                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12638
12639                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12640                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12641
12642                    // Always subtract cache size, since it's a subdirectory
12643                    mStats.externalDataSize -= mStats.externalCacheSize;
12644
12645                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12646                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12647
12648                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12649                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12650                }
12651            }
12652        }
12653
12654        @Override
12655        void handleReturnCode() {
12656            if (mObserver != null) {
12657                try {
12658                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12659                } catch (RemoteException e) {
12660                    Slog.i(TAG, "Observer no longer exists.");
12661                }
12662            }
12663        }
12664
12665        @Override
12666        void handleServiceError() {
12667            Slog.e(TAG, "Could not measure application " + mStats.packageName
12668                            + " external storage");
12669        }
12670    }
12671
12672    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12673            throws RemoteException {
12674        long result = 0;
12675        for (File path : paths) {
12676            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12677        }
12678        return result;
12679    }
12680
12681    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12682        for (File path : paths) {
12683            try {
12684                mcs.clearDirectory(path.getAbsolutePath());
12685            } catch (RemoteException e) {
12686            }
12687        }
12688    }
12689
12690    static class OriginInfo {
12691        /**
12692         * Location where install is coming from, before it has been
12693         * copied/renamed into place. This could be a single monolithic APK
12694         * file, or a cluster directory. This location may be untrusted.
12695         */
12696        final File file;
12697        final String cid;
12698
12699        /**
12700         * Flag indicating that {@link #file} or {@link #cid} has already been
12701         * staged, meaning downstream users don't need to defensively copy the
12702         * contents.
12703         */
12704        final boolean staged;
12705
12706        /**
12707         * Flag indicating that {@link #file} or {@link #cid} is an already
12708         * installed app that is being moved.
12709         */
12710        final boolean existing;
12711
12712        final String resolvedPath;
12713        final File resolvedFile;
12714
12715        static OriginInfo fromNothing() {
12716            return new OriginInfo(null, null, false, false);
12717        }
12718
12719        static OriginInfo fromUntrustedFile(File file) {
12720            return new OriginInfo(file, null, false, false);
12721        }
12722
12723        static OriginInfo fromExistingFile(File file) {
12724            return new OriginInfo(file, null, false, true);
12725        }
12726
12727        static OriginInfo fromStagedFile(File file) {
12728            return new OriginInfo(file, null, true, false);
12729        }
12730
12731        static OriginInfo fromStagedContainer(String cid) {
12732            return new OriginInfo(null, cid, true, false);
12733        }
12734
12735        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12736            this.file = file;
12737            this.cid = cid;
12738            this.staged = staged;
12739            this.existing = existing;
12740
12741            if (cid != null) {
12742                resolvedPath = PackageHelper.getSdDir(cid);
12743                resolvedFile = new File(resolvedPath);
12744            } else if (file != null) {
12745                resolvedPath = file.getAbsolutePath();
12746                resolvedFile = file;
12747            } else {
12748                resolvedPath = null;
12749                resolvedFile = null;
12750            }
12751        }
12752    }
12753
12754    static class MoveInfo {
12755        final int moveId;
12756        final String fromUuid;
12757        final String toUuid;
12758        final String packageName;
12759        final String dataAppName;
12760        final int appId;
12761        final String seinfo;
12762        final int targetSdkVersion;
12763
12764        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12765                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12766            this.moveId = moveId;
12767            this.fromUuid = fromUuid;
12768            this.toUuid = toUuid;
12769            this.packageName = packageName;
12770            this.dataAppName = dataAppName;
12771            this.appId = appId;
12772            this.seinfo = seinfo;
12773            this.targetSdkVersion = targetSdkVersion;
12774        }
12775    }
12776
12777    static class VerificationInfo {
12778        /** A constant used to indicate that a uid value is not present. */
12779        public static final int NO_UID = -1;
12780
12781        /** URI referencing where the package was downloaded from. */
12782        final Uri originatingUri;
12783
12784        /** HTTP referrer URI associated with the originatingURI. */
12785        final Uri referrer;
12786
12787        /** UID of the application that the install request originated from. */
12788        final int originatingUid;
12789
12790        /** UID of application requesting the install */
12791        final int installerUid;
12792
12793        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12794            this.originatingUri = originatingUri;
12795            this.referrer = referrer;
12796            this.originatingUid = originatingUid;
12797            this.installerUid = installerUid;
12798        }
12799    }
12800
12801    class InstallParams extends HandlerParams {
12802        final OriginInfo origin;
12803        final MoveInfo move;
12804        final IPackageInstallObserver2 observer;
12805        int installFlags;
12806        final String installerPackageName;
12807        final String volumeUuid;
12808        private InstallArgs mArgs;
12809        private int mRet;
12810        final String packageAbiOverride;
12811        final String[] grantedRuntimePermissions;
12812        final VerificationInfo verificationInfo;
12813        final Certificate[][] certificates;
12814
12815        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12816                int installFlags, String installerPackageName, String volumeUuid,
12817                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12818                String[] grantedPermissions, Certificate[][] certificates) {
12819            super(user);
12820            this.origin = origin;
12821            this.move = move;
12822            this.observer = observer;
12823            this.installFlags = installFlags;
12824            this.installerPackageName = installerPackageName;
12825            this.volumeUuid = volumeUuid;
12826            this.verificationInfo = verificationInfo;
12827            this.packageAbiOverride = packageAbiOverride;
12828            this.grantedRuntimePermissions = grantedPermissions;
12829            this.certificates = certificates;
12830        }
12831
12832        @Override
12833        public String toString() {
12834            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12835                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12836        }
12837
12838        private int installLocationPolicy(PackageInfoLite pkgLite) {
12839            String packageName = pkgLite.packageName;
12840            int installLocation = pkgLite.installLocation;
12841            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12842            // reader
12843            synchronized (mPackages) {
12844                // Currently installed package which the new package is attempting to replace or
12845                // null if no such package is installed.
12846                PackageParser.Package installedPkg = mPackages.get(packageName);
12847                // Package which currently owns the data which the new package will own if installed.
12848                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12849                // will be null whereas dataOwnerPkg will contain information about the package
12850                // which was uninstalled while keeping its data.
12851                PackageParser.Package dataOwnerPkg = installedPkg;
12852                if (dataOwnerPkg  == null) {
12853                    PackageSetting ps = mSettings.mPackages.get(packageName);
12854                    if (ps != null) {
12855                        dataOwnerPkg = ps.pkg;
12856                    }
12857                }
12858
12859                if (dataOwnerPkg != null) {
12860                    // If installed, the package will get access to data left on the device by its
12861                    // predecessor. As a security measure, this is permited only if this is not a
12862                    // version downgrade or if the predecessor package is marked as debuggable and
12863                    // a downgrade is explicitly requested.
12864                    //
12865                    // On debuggable platform builds, downgrades are permitted even for
12866                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12867                    // not offer security guarantees and thus it's OK to disable some security
12868                    // mechanisms to make debugging/testing easier on those builds. However, even on
12869                    // debuggable builds downgrades of packages are permitted only if requested via
12870                    // installFlags. This is because we aim to keep the behavior of debuggable
12871                    // platform builds as close as possible to the behavior of non-debuggable
12872                    // platform builds.
12873                    final boolean downgradeRequested =
12874                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12875                    final boolean packageDebuggable =
12876                                (dataOwnerPkg.applicationInfo.flags
12877                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12878                    final boolean downgradePermitted =
12879                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12880                    if (!downgradePermitted) {
12881                        try {
12882                            checkDowngrade(dataOwnerPkg, pkgLite);
12883                        } catch (PackageManagerException e) {
12884                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12885                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12886                        }
12887                    }
12888                }
12889
12890                if (installedPkg != null) {
12891                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12892                        // Check for updated system application.
12893                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12894                            if (onSd) {
12895                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12896                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12897                            }
12898                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12899                        } else {
12900                            if (onSd) {
12901                                // Install flag overrides everything.
12902                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12903                            }
12904                            // If current upgrade specifies particular preference
12905                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12906                                // Application explicitly specified internal.
12907                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12908                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12909                                // App explictly prefers external. Let policy decide
12910                            } else {
12911                                // Prefer previous location
12912                                if (isExternal(installedPkg)) {
12913                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12914                                }
12915                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12916                            }
12917                        }
12918                    } else {
12919                        // Invalid install. Return error code
12920                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12921                    }
12922                }
12923            }
12924            // All the special cases have been taken care of.
12925            // Return result based on recommended install location.
12926            if (onSd) {
12927                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12928            }
12929            return pkgLite.recommendedInstallLocation;
12930        }
12931
12932        /*
12933         * Invoke remote method to get package information and install
12934         * location values. Override install location based on default
12935         * policy if needed and then create install arguments based
12936         * on the install location.
12937         */
12938        public void handleStartCopy() throws RemoteException {
12939            int ret = PackageManager.INSTALL_SUCCEEDED;
12940
12941            // If we're already staged, we've firmly committed to an install location
12942            if (origin.staged) {
12943                if (origin.file != null) {
12944                    installFlags |= PackageManager.INSTALL_INTERNAL;
12945                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12946                } else if (origin.cid != null) {
12947                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12948                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12949                } else {
12950                    throw new IllegalStateException("Invalid stage location");
12951                }
12952            }
12953
12954            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12955            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12956            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12957            PackageInfoLite pkgLite = null;
12958
12959            if (onInt && onSd) {
12960                // Check if both bits are set.
12961                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12962                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12963            } else if (onSd && ephemeral) {
12964                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12965                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12966            } else {
12967                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12968                        packageAbiOverride);
12969
12970                if (DEBUG_EPHEMERAL && ephemeral) {
12971                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12972                }
12973
12974                /*
12975                 * If we have too little free space, try to free cache
12976                 * before giving up.
12977                 */
12978                if (!origin.staged && pkgLite.recommendedInstallLocation
12979                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12980                    // TODO: focus freeing disk space on the target device
12981                    final StorageManager storage = StorageManager.from(mContext);
12982                    final long lowThreshold = storage.getStorageLowBytes(
12983                            Environment.getDataDirectory());
12984
12985                    final long sizeBytes = mContainerService.calculateInstalledSize(
12986                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12987
12988                    try {
12989                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
12990                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12991                                installFlags, packageAbiOverride);
12992                    } catch (InstallerException e) {
12993                        Slog.w(TAG, "Failed to free cache", e);
12994                    }
12995
12996                    /*
12997                     * The cache free must have deleted the file we
12998                     * downloaded to install.
12999                     *
13000                     * TODO: fix the "freeCache" call to not delete
13001                     *       the file we care about.
13002                     */
13003                    if (pkgLite.recommendedInstallLocation
13004                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13005                        pkgLite.recommendedInstallLocation
13006                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13007                    }
13008                }
13009            }
13010
13011            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13012                int loc = pkgLite.recommendedInstallLocation;
13013                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13014                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13015                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13016                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13017                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13018                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13019                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13020                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13021                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13022                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13023                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13024                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13025                } else {
13026                    // Override with defaults if needed.
13027                    loc = installLocationPolicy(pkgLite);
13028                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13029                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13030                    } else if (!onSd && !onInt) {
13031                        // Override install location with flags
13032                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13033                            // Set the flag to install on external media.
13034                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13035                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13036                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13037                            if (DEBUG_EPHEMERAL) {
13038                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13039                            }
13040                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13041                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13042                                    |PackageManager.INSTALL_INTERNAL);
13043                        } else {
13044                            // Make sure the flag for installing on external
13045                            // media is unset
13046                            installFlags |= PackageManager.INSTALL_INTERNAL;
13047                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13048                        }
13049                    }
13050                }
13051            }
13052
13053            final InstallArgs args = createInstallArgs(this);
13054            mArgs = args;
13055
13056            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13057                // TODO: http://b/22976637
13058                // Apps installed for "all" users use the device owner to verify the app
13059                UserHandle verifierUser = getUser();
13060                if (verifierUser == UserHandle.ALL) {
13061                    verifierUser = UserHandle.SYSTEM;
13062                }
13063
13064                /*
13065                 * Determine if we have any installed package verifiers. If we
13066                 * do, then we'll defer to them to verify the packages.
13067                 */
13068                final int requiredUid = mRequiredVerifierPackage == null ? -1
13069                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13070                                verifierUser.getIdentifier());
13071                if (!origin.existing && requiredUid != -1
13072                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13073                    final Intent verification = new Intent(
13074                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13075                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13076                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13077                            PACKAGE_MIME_TYPE);
13078                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13079
13080                    // Query all live verifiers based on current user state
13081                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13082                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13083
13084                    if (DEBUG_VERIFY) {
13085                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13086                                + verification.toString() + " with " + pkgLite.verifiers.length
13087                                + " optional verifiers");
13088                    }
13089
13090                    final int verificationId = mPendingVerificationToken++;
13091
13092                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13093
13094                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13095                            installerPackageName);
13096
13097                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13098                            installFlags);
13099
13100                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13101                            pkgLite.packageName);
13102
13103                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13104                            pkgLite.versionCode);
13105
13106                    if (verificationInfo != null) {
13107                        if (verificationInfo.originatingUri != null) {
13108                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13109                                    verificationInfo.originatingUri);
13110                        }
13111                        if (verificationInfo.referrer != null) {
13112                            verification.putExtra(Intent.EXTRA_REFERRER,
13113                                    verificationInfo.referrer);
13114                        }
13115                        if (verificationInfo.originatingUid >= 0) {
13116                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13117                                    verificationInfo.originatingUid);
13118                        }
13119                        if (verificationInfo.installerUid >= 0) {
13120                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13121                                    verificationInfo.installerUid);
13122                        }
13123                    }
13124
13125                    final PackageVerificationState verificationState = new PackageVerificationState(
13126                            requiredUid, args);
13127
13128                    mPendingVerification.append(verificationId, verificationState);
13129
13130                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13131                            receivers, verificationState);
13132
13133                    /*
13134                     * If any sufficient verifiers were listed in the package
13135                     * manifest, attempt to ask them.
13136                     */
13137                    if (sufficientVerifiers != null) {
13138                        final int N = sufficientVerifiers.size();
13139                        if (N == 0) {
13140                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13141                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13142                        } else {
13143                            for (int i = 0; i < N; i++) {
13144                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13145
13146                                final Intent sufficientIntent = new Intent(verification);
13147                                sufficientIntent.setComponent(verifierComponent);
13148                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13149                            }
13150                        }
13151                    }
13152
13153                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13154                            mRequiredVerifierPackage, receivers);
13155                    if (ret == PackageManager.INSTALL_SUCCEEDED
13156                            && mRequiredVerifierPackage != null) {
13157                        Trace.asyncTraceBegin(
13158                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13159                        /*
13160                         * Send the intent to the required verification agent,
13161                         * but only start the verification timeout after the
13162                         * target BroadcastReceivers have run.
13163                         */
13164                        verification.setComponent(requiredVerifierComponent);
13165                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13166                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13167                                new BroadcastReceiver() {
13168                                    @Override
13169                                    public void onReceive(Context context, Intent intent) {
13170                                        final Message msg = mHandler
13171                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13172                                        msg.arg1 = verificationId;
13173                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13174                                    }
13175                                }, null, 0, null, null);
13176
13177                        /*
13178                         * We don't want the copy to proceed until verification
13179                         * succeeds, so null out this field.
13180                         */
13181                        mArgs = null;
13182                    }
13183                } else {
13184                    /*
13185                     * No package verification is enabled, so immediately start
13186                     * the remote call to initiate copy using temporary file.
13187                     */
13188                    ret = args.copyApk(mContainerService, true);
13189                }
13190            }
13191
13192            mRet = ret;
13193        }
13194
13195        @Override
13196        void handleReturnCode() {
13197            // If mArgs is null, then MCS couldn't be reached. When it
13198            // reconnects, it will try again to install. At that point, this
13199            // will succeed.
13200            if (mArgs != null) {
13201                processPendingInstall(mArgs, mRet);
13202            }
13203        }
13204
13205        @Override
13206        void handleServiceError() {
13207            mArgs = createInstallArgs(this);
13208            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13209        }
13210
13211        public boolean isForwardLocked() {
13212            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13213        }
13214    }
13215
13216    /**
13217     * Used during creation of InstallArgs
13218     *
13219     * @param installFlags package installation flags
13220     * @return true if should be installed on external storage
13221     */
13222    private static boolean installOnExternalAsec(int installFlags) {
13223        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13224            return false;
13225        }
13226        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13227            return true;
13228        }
13229        return false;
13230    }
13231
13232    /**
13233     * Used during creation of InstallArgs
13234     *
13235     * @param installFlags package installation flags
13236     * @return true if should be installed as forward locked
13237     */
13238    private static boolean installForwardLocked(int installFlags) {
13239        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13240    }
13241
13242    private InstallArgs createInstallArgs(InstallParams params) {
13243        if (params.move != null) {
13244            return new MoveInstallArgs(params);
13245        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13246            return new AsecInstallArgs(params);
13247        } else {
13248            return new FileInstallArgs(params);
13249        }
13250    }
13251
13252    /**
13253     * Create args that describe an existing installed package. Typically used
13254     * when cleaning up old installs, or used as a move source.
13255     */
13256    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13257            String resourcePath, String[] instructionSets) {
13258        final boolean isInAsec;
13259        if (installOnExternalAsec(installFlags)) {
13260            /* Apps on SD card are always in ASEC containers. */
13261            isInAsec = true;
13262        } else if (installForwardLocked(installFlags)
13263                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13264            /*
13265             * Forward-locked apps are only in ASEC containers if they're the
13266             * new style
13267             */
13268            isInAsec = true;
13269        } else {
13270            isInAsec = false;
13271        }
13272
13273        if (isInAsec) {
13274            return new AsecInstallArgs(codePath, instructionSets,
13275                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13276        } else {
13277            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13278        }
13279    }
13280
13281    static abstract class InstallArgs {
13282        /** @see InstallParams#origin */
13283        final OriginInfo origin;
13284        /** @see InstallParams#move */
13285        final MoveInfo move;
13286
13287        final IPackageInstallObserver2 observer;
13288        // Always refers to PackageManager flags only
13289        final int installFlags;
13290        final String installerPackageName;
13291        final String volumeUuid;
13292        final UserHandle user;
13293        final String abiOverride;
13294        final String[] installGrantPermissions;
13295        /** If non-null, drop an async trace when the install completes */
13296        final String traceMethod;
13297        final int traceCookie;
13298        final Certificate[][] certificates;
13299
13300        // The list of instruction sets supported by this app. This is currently
13301        // only used during the rmdex() phase to clean up resources. We can get rid of this
13302        // if we move dex files under the common app path.
13303        /* nullable */ String[] instructionSets;
13304
13305        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13306                int installFlags, String installerPackageName, String volumeUuid,
13307                UserHandle user, String[] instructionSets,
13308                String abiOverride, String[] installGrantPermissions,
13309                String traceMethod, int traceCookie, Certificate[][] certificates) {
13310            this.origin = origin;
13311            this.move = move;
13312            this.installFlags = installFlags;
13313            this.observer = observer;
13314            this.installerPackageName = installerPackageName;
13315            this.volumeUuid = volumeUuid;
13316            this.user = user;
13317            this.instructionSets = instructionSets;
13318            this.abiOverride = abiOverride;
13319            this.installGrantPermissions = installGrantPermissions;
13320            this.traceMethod = traceMethod;
13321            this.traceCookie = traceCookie;
13322            this.certificates = certificates;
13323        }
13324
13325        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13326        abstract int doPreInstall(int status);
13327
13328        /**
13329         * Rename package into final resting place. All paths on the given
13330         * scanned package should be updated to reflect the rename.
13331         */
13332        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13333        abstract int doPostInstall(int status, int uid);
13334
13335        /** @see PackageSettingBase#codePathString */
13336        abstract String getCodePath();
13337        /** @see PackageSettingBase#resourcePathString */
13338        abstract String getResourcePath();
13339
13340        // Need installer lock especially for dex file removal.
13341        abstract void cleanUpResourcesLI();
13342        abstract boolean doPostDeleteLI(boolean delete);
13343
13344        /**
13345         * Called before the source arguments are copied. This is used mostly
13346         * for MoveParams when it needs to read the source file to put it in the
13347         * destination.
13348         */
13349        int doPreCopy() {
13350            return PackageManager.INSTALL_SUCCEEDED;
13351        }
13352
13353        /**
13354         * Called after the source arguments are copied. This is used mostly for
13355         * MoveParams when it needs to read the source file to put it in the
13356         * destination.
13357         */
13358        int doPostCopy(int uid) {
13359            return PackageManager.INSTALL_SUCCEEDED;
13360        }
13361
13362        protected boolean isFwdLocked() {
13363            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13364        }
13365
13366        protected boolean isExternalAsec() {
13367            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13368        }
13369
13370        protected boolean isEphemeral() {
13371            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13372        }
13373
13374        UserHandle getUser() {
13375            return user;
13376        }
13377    }
13378
13379    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13380        if (!allCodePaths.isEmpty()) {
13381            if (instructionSets == null) {
13382                throw new IllegalStateException("instructionSet == null");
13383            }
13384            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13385            for (String codePath : allCodePaths) {
13386                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13387                    try {
13388                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13389                    } catch (InstallerException ignored) {
13390                    }
13391                }
13392            }
13393        }
13394    }
13395
13396    /**
13397     * Logic to handle installation of non-ASEC applications, including copying
13398     * and renaming logic.
13399     */
13400    class FileInstallArgs extends InstallArgs {
13401        private File codeFile;
13402        private File resourceFile;
13403
13404        // Example topology:
13405        // /data/app/com.example/base.apk
13406        // /data/app/com.example/split_foo.apk
13407        // /data/app/com.example/lib/arm/libfoo.so
13408        // /data/app/com.example/lib/arm64/libfoo.so
13409        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13410
13411        /** New install */
13412        FileInstallArgs(InstallParams params) {
13413            super(params.origin, params.move, params.observer, params.installFlags,
13414                    params.installerPackageName, params.volumeUuid,
13415                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13416                    params.grantedRuntimePermissions,
13417                    params.traceMethod, params.traceCookie, params.certificates);
13418            if (isFwdLocked()) {
13419                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13420            }
13421        }
13422
13423        /** Existing install */
13424        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13425            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13426                    null, null, null, 0, null /*certificates*/);
13427            this.codeFile = (codePath != null) ? new File(codePath) : null;
13428            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13429        }
13430
13431        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13432            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13433            try {
13434                return doCopyApk(imcs, temp);
13435            } finally {
13436                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13437            }
13438        }
13439
13440        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13441            if (origin.staged) {
13442                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13443                codeFile = origin.file;
13444                resourceFile = origin.file;
13445                return PackageManager.INSTALL_SUCCEEDED;
13446            }
13447
13448            try {
13449                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13450                final File tempDir =
13451                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13452                codeFile = tempDir;
13453                resourceFile = tempDir;
13454            } catch (IOException e) {
13455                Slog.w(TAG, "Failed to create copy file: " + e);
13456                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13457            }
13458
13459            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13460                @Override
13461                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13462                    if (!FileUtils.isValidExtFilename(name)) {
13463                        throw new IllegalArgumentException("Invalid filename: " + name);
13464                    }
13465                    try {
13466                        final File file = new File(codeFile, name);
13467                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13468                                O_RDWR | O_CREAT, 0644);
13469                        Os.chmod(file.getAbsolutePath(), 0644);
13470                        return new ParcelFileDescriptor(fd);
13471                    } catch (ErrnoException e) {
13472                        throw new RemoteException("Failed to open: " + e.getMessage());
13473                    }
13474                }
13475            };
13476
13477            int ret = PackageManager.INSTALL_SUCCEEDED;
13478            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13479            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13480                Slog.e(TAG, "Failed to copy package");
13481                return ret;
13482            }
13483
13484            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13485            NativeLibraryHelper.Handle handle = null;
13486            try {
13487                handle = NativeLibraryHelper.Handle.create(codeFile);
13488                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13489                        abiOverride);
13490            } catch (IOException e) {
13491                Slog.e(TAG, "Copying native libraries failed", e);
13492                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13493            } finally {
13494                IoUtils.closeQuietly(handle);
13495            }
13496
13497            return ret;
13498        }
13499
13500        int doPreInstall(int status) {
13501            if (status != PackageManager.INSTALL_SUCCEEDED) {
13502                cleanUp();
13503            }
13504            return status;
13505        }
13506
13507        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13508            if (status != PackageManager.INSTALL_SUCCEEDED) {
13509                cleanUp();
13510                return false;
13511            }
13512
13513            final File targetDir = codeFile.getParentFile();
13514            final File beforeCodeFile = codeFile;
13515            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13516
13517            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13518            try {
13519                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13520            } catch (ErrnoException e) {
13521                Slog.w(TAG, "Failed to rename", e);
13522                return false;
13523            }
13524
13525            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13526                Slog.w(TAG, "Failed to restorecon");
13527                return false;
13528            }
13529
13530            // Reflect the rename internally
13531            codeFile = afterCodeFile;
13532            resourceFile = afterCodeFile;
13533
13534            // Reflect the rename in scanned details
13535            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13536            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13537                    afterCodeFile, pkg.baseCodePath));
13538            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13539                    afterCodeFile, pkg.splitCodePaths));
13540
13541            // Reflect the rename in app info
13542            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13543            pkg.setApplicationInfoCodePath(pkg.codePath);
13544            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13545            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13546            pkg.setApplicationInfoResourcePath(pkg.codePath);
13547            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13548            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13549
13550            return true;
13551        }
13552
13553        int doPostInstall(int status, int uid) {
13554            if (status != PackageManager.INSTALL_SUCCEEDED) {
13555                cleanUp();
13556            }
13557            return status;
13558        }
13559
13560        @Override
13561        String getCodePath() {
13562            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13563        }
13564
13565        @Override
13566        String getResourcePath() {
13567            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13568        }
13569
13570        private boolean cleanUp() {
13571            if (codeFile == null || !codeFile.exists()) {
13572                return false;
13573            }
13574
13575            removeCodePathLI(codeFile);
13576
13577            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13578                resourceFile.delete();
13579            }
13580
13581            return true;
13582        }
13583
13584        void cleanUpResourcesLI() {
13585            // Try enumerating all code paths before deleting
13586            List<String> allCodePaths = Collections.EMPTY_LIST;
13587            if (codeFile != null && codeFile.exists()) {
13588                try {
13589                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13590                    allCodePaths = pkg.getAllCodePaths();
13591                } catch (PackageParserException e) {
13592                    // Ignored; we tried our best
13593                }
13594            }
13595
13596            cleanUp();
13597            removeDexFiles(allCodePaths, instructionSets);
13598        }
13599
13600        boolean doPostDeleteLI(boolean delete) {
13601            // XXX err, shouldn't we respect the delete flag?
13602            cleanUpResourcesLI();
13603            return true;
13604        }
13605    }
13606
13607    private boolean isAsecExternal(String cid) {
13608        final String asecPath = PackageHelper.getSdFilesystem(cid);
13609        return !asecPath.startsWith(mAsecInternalPath);
13610    }
13611
13612    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13613            PackageManagerException {
13614        if (copyRet < 0) {
13615            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13616                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13617                throw new PackageManagerException(copyRet, message);
13618            }
13619        }
13620    }
13621
13622    /**
13623     * Extract the MountService "container ID" from the full code path of an
13624     * .apk.
13625     */
13626    static String cidFromCodePath(String fullCodePath) {
13627        int eidx = fullCodePath.lastIndexOf("/");
13628        String subStr1 = fullCodePath.substring(0, eidx);
13629        int sidx = subStr1.lastIndexOf("/");
13630        return subStr1.substring(sidx+1, eidx);
13631    }
13632
13633    /**
13634     * Logic to handle installation of ASEC applications, including copying and
13635     * renaming logic.
13636     */
13637    class AsecInstallArgs extends InstallArgs {
13638        static final String RES_FILE_NAME = "pkg.apk";
13639        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13640
13641        String cid;
13642        String packagePath;
13643        String resourcePath;
13644
13645        /** New install */
13646        AsecInstallArgs(InstallParams params) {
13647            super(params.origin, params.move, params.observer, params.installFlags,
13648                    params.installerPackageName, params.volumeUuid,
13649                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13650                    params.grantedRuntimePermissions,
13651                    params.traceMethod, params.traceCookie, params.certificates);
13652        }
13653
13654        /** Existing install */
13655        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13656                        boolean isExternal, boolean isForwardLocked) {
13657            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13658              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13659                    instructionSets, null, null, null, 0, null /*certificates*/);
13660            // Hackily pretend we're still looking at a full code path
13661            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13662                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13663            }
13664
13665            // Extract cid from fullCodePath
13666            int eidx = fullCodePath.lastIndexOf("/");
13667            String subStr1 = fullCodePath.substring(0, eidx);
13668            int sidx = subStr1.lastIndexOf("/");
13669            cid = subStr1.substring(sidx+1, eidx);
13670            setMountPath(subStr1);
13671        }
13672
13673        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13674            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13675              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13676                    instructionSets, null, null, null, 0, null /*certificates*/);
13677            this.cid = cid;
13678            setMountPath(PackageHelper.getSdDir(cid));
13679        }
13680
13681        void createCopyFile() {
13682            cid = mInstallerService.allocateExternalStageCidLegacy();
13683        }
13684
13685        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13686            if (origin.staged && origin.cid != null) {
13687                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13688                cid = origin.cid;
13689                setMountPath(PackageHelper.getSdDir(cid));
13690                return PackageManager.INSTALL_SUCCEEDED;
13691            }
13692
13693            if (temp) {
13694                createCopyFile();
13695            } else {
13696                /*
13697                 * Pre-emptively destroy the container since it's destroyed if
13698                 * copying fails due to it existing anyway.
13699                 */
13700                PackageHelper.destroySdDir(cid);
13701            }
13702
13703            final String newMountPath = imcs.copyPackageToContainer(
13704                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13705                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13706
13707            if (newMountPath != null) {
13708                setMountPath(newMountPath);
13709                return PackageManager.INSTALL_SUCCEEDED;
13710            } else {
13711                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13712            }
13713        }
13714
13715        @Override
13716        String getCodePath() {
13717            return packagePath;
13718        }
13719
13720        @Override
13721        String getResourcePath() {
13722            return resourcePath;
13723        }
13724
13725        int doPreInstall(int status) {
13726            if (status != PackageManager.INSTALL_SUCCEEDED) {
13727                // Destroy container
13728                PackageHelper.destroySdDir(cid);
13729            } else {
13730                boolean mounted = PackageHelper.isContainerMounted(cid);
13731                if (!mounted) {
13732                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13733                            Process.SYSTEM_UID);
13734                    if (newMountPath != null) {
13735                        setMountPath(newMountPath);
13736                    } else {
13737                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13738                    }
13739                }
13740            }
13741            return status;
13742        }
13743
13744        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13745            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13746            String newMountPath = null;
13747            if (PackageHelper.isContainerMounted(cid)) {
13748                // Unmount the container
13749                if (!PackageHelper.unMountSdDir(cid)) {
13750                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13751                    return false;
13752                }
13753            }
13754            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13755                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13756                        " which might be stale. Will try to clean up.");
13757                // Clean up the stale container and proceed to recreate.
13758                if (!PackageHelper.destroySdDir(newCacheId)) {
13759                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13760                    return false;
13761                }
13762                // Successfully cleaned up stale container. Try to rename again.
13763                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13764                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13765                            + " inspite of cleaning it up.");
13766                    return false;
13767                }
13768            }
13769            if (!PackageHelper.isContainerMounted(newCacheId)) {
13770                Slog.w(TAG, "Mounting container " + newCacheId);
13771                newMountPath = PackageHelper.mountSdDir(newCacheId,
13772                        getEncryptKey(), Process.SYSTEM_UID);
13773            } else {
13774                newMountPath = PackageHelper.getSdDir(newCacheId);
13775            }
13776            if (newMountPath == null) {
13777                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13778                return false;
13779            }
13780            Log.i(TAG, "Succesfully renamed " + cid +
13781                    " to " + newCacheId +
13782                    " at new path: " + newMountPath);
13783            cid = newCacheId;
13784
13785            final File beforeCodeFile = new File(packagePath);
13786            setMountPath(newMountPath);
13787            final File afterCodeFile = new File(packagePath);
13788
13789            // Reflect the rename in scanned details
13790            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13791            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13792                    afterCodeFile, pkg.baseCodePath));
13793            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13794                    afterCodeFile, pkg.splitCodePaths));
13795
13796            // Reflect the rename in app info
13797            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13798            pkg.setApplicationInfoCodePath(pkg.codePath);
13799            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13800            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13801            pkg.setApplicationInfoResourcePath(pkg.codePath);
13802            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13803            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13804
13805            return true;
13806        }
13807
13808        private void setMountPath(String mountPath) {
13809            final File mountFile = new File(mountPath);
13810
13811            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13812            if (monolithicFile.exists()) {
13813                packagePath = monolithicFile.getAbsolutePath();
13814                if (isFwdLocked()) {
13815                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13816                } else {
13817                    resourcePath = packagePath;
13818                }
13819            } else {
13820                packagePath = mountFile.getAbsolutePath();
13821                resourcePath = packagePath;
13822            }
13823        }
13824
13825        int doPostInstall(int status, int uid) {
13826            if (status != PackageManager.INSTALL_SUCCEEDED) {
13827                cleanUp();
13828            } else {
13829                final int groupOwner;
13830                final String protectedFile;
13831                if (isFwdLocked()) {
13832                    groupOwner = UserHandle.getSharedAppGid(uid);
13833                    protectedFile = RES_FILE_NAME;
13834                } else {
13835                    groupOwner = -1;
13836                    protectedFile = null;
13837                }
13838
13839                if (uid < Process.FIRST_APPLICATION_UID
13840                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13841                    Slog.e(TAG, "Failed to finalize " + cid);
13842                    PackageHelper.destroySdDir(cid);
13843                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13844                }
13845
13846                boolean mounted = PackageHelper.isContainerMounted(cid);
13847                if (!mounted) {
13848                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13849                }
13850            }
13851            return status;
13852        }
13853
13854        private void cleanUp() {
13855            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13856
13857            // Destroy secure container
13858            PackageHelper.destroySdDir(cid);
13859        }
13860
13861        private List<String> getAllCodePaths() {
13862            final File codeFile = new File(getCodePath());
13863            if (codeFile != null && codeFile.exists()) {
13864                try {
13865                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13866                    return pkg.getAllCodePaths();
13867                } catch (PackageParserException e) {
13868                    // Ignored; we tried our best
13869                }
13870            }
13871            return Collections.EMPTY_LIST;
13872        }
13873
13874        void cleanUpResourcesLI() {
13875            // Enumerate all code paths before deleting
13876            cleanUpResourcesLI(getAllCodePaths());
13877        }
13878
13879        private void cleanUpResourcesLI(List<String> allCodePaths) {
13880            cleanUp();
13881            removeDexFiles(allCodePaths, instructionSets);
13882        }
13883
13884        String getPackageName() {
13885            return getAsecPackageName(cid);
13886        }
13887
13888        boolean doPostDeleteLI(boolean delete) {
13889            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13890            final List<String> allCodePaths = getAllCodePaths();
13891            boolean mounted = PackageHelper.isContainerMounted(cid);
13892            if (mounted) {
13893                // Unmount first
13894                if (PackageHelper.unMountSdDir(cid)) {
13895                    mounted = false;
13896                }
13897            }
13898            if (!mounted && delete) {
13899                cleanUpResourcesLI(allCodePaths);
13900            }
13901            return !mounted;
13902        }
13903
13904        @Override
13905        int doPreCopy() {
13906            if (isFwdLocked()) {
13907                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13908                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13909                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13910                }
13911            }
13912
13913            return PackageManager.INSTALL_SUCCEEDED;
13914        }
13915
13916        @Override
13917        int doPostCopy(int uid) {
13918            if (isFwdLocked()) {
13919                if (uid < Process.FIRST_APPLICATION_UID
13920                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13921                                RES_FILE_NAME)) {
13922                    Slog.e(TAG, "Failed to finalize " + cid);
13923                    PackageHelper.destroySdDir(cid);
13924                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13925                }
13926            }
13927
13928            return PackageManager.INSTALL_SUCCEEDED;
13929        }
13930    }
13931
13932    /**
13933     * Logic to handle movement of existing installed applications.
13934     */
13935    class MoveInstallArgs extends InstallArgs {
13936        private File codeFile;
13937        private File resourceFile;
13938
13939        /** New install */
13940        MoveInstallArgs(InstallParams params) {
13941            super(params.origin, params.move, params.observer, params.installFlags,
13942                    params.installerPackageName, params.volumeUuid,
13943                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13944                    params.grantedRuntimePermissions,
13945                    params.traceMethod, params.traceCookie, params.certificates);
13946        }
13947
13948        int copyApk(IMediaContainerService imcs, boolean temp) {
13949            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13950                    + move.fromUuid + " to " + move.toUuid);
13951            synchronized (mInstaller) {
13952                try {
13953                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13954                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13955                } catch (InstallerException e) {
13956                    Slog.w(TAG, "Failed to move app", e);
13957                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13958                }
13959            }
13960
13961            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13962            resourceFile = codeFile;
13963            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13964
13965            return PackageManager.INSTALL_SUCCEEDED;
13966        }
13967
13968        int doPreInstall(int status) {
13969            if (status != PackageManager.INSTALL_SUCCEEDED) {
13970                cleanUp(move.toUuid);
13971            }
13972            return status;
13973        }
13974
13975        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13976            if (status != PackageManager.INSTALL_SUCCEEDED) {
13977                cleanUp(move.toUuid);
13978                return false;
13979            }
13980
13981            // Reflect the move in app info
13982            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13983            pkg.setApplicationInfoCodePath(pkg.codePath);
13984            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13985            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13986            pkg.setApplicationInfoResourcePath(pkg.codePath);
13987            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13988            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13989
13990            return true;
13991        }
13992
13993        int doPostInstall(int status, int uid) {
13994            if (status == PackageManager.INSTALL_SUCCEEDED) {
13995                cleanUp(move.fromUuid);
13996            } else {
13997                cleanUp(move.toUuid);
13998            }
13999            return status;
14000        }
14001
14002        @Override
14003        String getCodePath() {
14004            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14005        }
14006
14007        @Override
14008        String getResourcePath() {
14009            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14010        }
14011
14012        private boolean cleanUp(String volumeUuid) {
14013            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14014                    move.dataAppName);
14015            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14016            final int[] userIds = sUserManager.getUserIds();
14017            synchronized (mInstallLock) {
14018                // Clean up both app data and code
14019                // All package moves are frozen until finished
14020                for (int userId : userIds) {
14021                    try {
14022                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14023                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14024                    } catch (InstallerException e) {
14025                        Slog.w(TAG, String.valueOf(e));
14026                    }
14027                }
14028                removeCodePathLI(codeFile);
14029            }
14030            return true;
14031        }
14032
14033        void cleanUpResourcesLI() {
14034            throw new UnsupportedOperationException();
14035        }
14036
14037        boolean doPostDeleteLI(boolean delete) {
14038            throw new UnsupportedOperationException();
14039        }
14040    }
14041
14042    static String getAsecPackageName(String packageCid) {
14043        int idx = packageCid.lastIndexOf("-");
14044        if (idx == -1) {
14045            return packageCid;
14046        }
14047        return packageCid.substring(0, idx);
14048    }
14049
14050    // Utility method used to create code paths based on package name and available index.
14051    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14052        String idxStr = "";
14053        int idx = 1;
14054        // Fall back to default value of idx=1 if prefix is not
14055        // part of oldCodePath
14056        if (oldCodePath != null) {
14057            String subStr = oldCodePath;
14058            // Drop the suffix right away
14059            if (suffix != null && subStr.endsWith(suffix)) {
14060                subStr = subStr.substring(0, subStr.length() - suffix.length());
14061            }
14062            // If oldCodePath already contains prefix find out the
14063            // ending index to either increment or decrement.
14064            int sidx = subStr.lastIndexOf(prefix);
14065            if (sidx != -1) {
14066                subStr = subStr.substring(sidx + prefix.length());
14067                if (subStr != null) {
14068                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14069                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14070                    }
14071                    try {
14072                        idx = Integer.parseInt(subStr);
14073                        if (idx <= 1) {
14074                            idx++;
14075                        } else {
14076                            idx--;
14077                        }
14078                    } catch(NumberFormatException e) {
14079                    }
14080                }
14081            }
14082        }
14083        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14084        return prefix + idxStr;
14085    }
14086
14087    private File getNextCodePath(File targetDir, String packageName) {
14088        int suffix = 1;
14089        File result;
14090        do {
14091            result = new File(targetDir, packageName + "-" + suffix);
14092            suffix++;
14093        } while (result.exists());
14094        return result;
14095    }
14096
14097    // Utility method that returns the relative package path with respect
14098    // to the installation directory. Like say for /data/data/com.test-1.apk
14099    // string com.test-1 is returned.
14100    static String deriveCodePathName(String codePath) {
14101        if (codePath == null) {
14102            return null;
14103        }
14104        final File codeFile = new File(codePath);
14105        final String name = codeFile.getName();
14106        if (codeFile.isDirectory()) {
14107            return name;
14108        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14109            final int lastDot = name.lastIndexOf('.');
14110            return name.substring(0, lastDot);
14111        } else {
14112            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14113            return null;
14114        }
14115    }
14116
14117    static class PackageInstalledInfo {
14118        String name;
14119        int uid;
14120        // The set of users that originally had this package installed.
14121        int[] origUsers;
14122        // The set of users that now have this package installed.
14123        int[] newUsers;
14124        PackageParser.Package pkg;
14125        int returnCode;
14126        String returnMsg;
14127        PackageRemovedInfo removedInfo;
14128        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14129
14130        public void setError(int code, String msg) {
14131            setReturnCode(code);
14132            setReturnMessage(msg);
14133            Slog.w(TAG, msg);
14134        }
14135
14136        public void setError(String msg, PackageParserException e) {
14137            setReturnCode(e.error);
14138            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14139            Slog.w(TAG, msg, e);
14140        }
14141
14142        public void setError(String msg, PackageManagerException e) {
14143            returnCode = e.error;
14144            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14145            Slog.w(TAG, msg, e);
14146        }
14147
14148        public void setReturnCode(int returnCode) {
14149            this.returnCode = returnCode;
14150            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14151            for (int i = 0; i < childCount; i++) {
14152                addedChildPackages.valueAt(i).returnCode = returnCode;
14153            }
14154        }
14155
14156        private void setReturnMessage(String returnMsg) {
14157            this.returnMsg = returnMsg;
14158            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14159            for (int i = 0; i < childCount; i++) {
14160                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14161            }
14162        }
14163
14164        // In some error cases we want to convey more info back to the observer
14165        String origPackage;
14166        String origPermission;
14167    }
14168
14169    /*
14170     * Install a non-existing package.
14171     */
14172    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14173            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14174            PackageInstalledInfo res) {
14175        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14176
14177        // Remember this for later, in case we need to rollback this install
14178        String pkgName = pkg.packageName;
14179
14180        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14181
14182        synchronized(mPackages) {
14183            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14184                // A package with the same name is already installed, though
14185                // it has been renamed to an older name.  The package we
14186                // are trying to install should be installed as an update to
14187                // the existing one, but that has not been requested, so bail.
14188                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14189                        + " without first uninstalling package running as "
14190                        + mSettings.mRenamedPackages.get(pkgName));
14191                return;
14192            }
14193            if (mPackages.containsKey(pkgName)) {
14194                // Don't allow installation over an existing package with the same name.
14195                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14196                        + " without first uninstalling.");
14197                return;
14198            }
14199        }
14200
14201        try {
14202            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14203                    System.currentTimeMillis(), user);
14204
14205            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14206
14207            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14208                prepareAppDataAfterInstallLIF(newPackage);
14209
14210            } else {
14211                // Remove package from internal structures, but keep around any
14212                // data that might have already existed
14213                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14214                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14215            }
14216        } catch (PackageManagerException e) {
14217            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14218        }
14219
14220        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14221    }
14222
14223    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14224        // Can't rotate keys during boot or if sharedUser.
14225        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14226                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14227            return false;
14228        }
14229        // app is using upgradeKeySets; make sure all are valid
14230        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14231        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14232        for (int i = 0; i < upgradeKeySets.length; i++) {
14233            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14234                Slog.wtf(TAG, "Package "
14235                         + (oldPs.name != null ? oldPs.name : "<null>")
14236                         + " contains upgrade-key-set reference to unknown key-set: "
14237                         + upgradeKeySets[i]
14238                         + " reverting to signatures check.");
14239                return false;
14240            }
14241        }
14242        return true;
14243    }
14244
14245    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14246        // Upgrade keysets are being used.  Determine if new package has a superset of the
14247        // required keys.
14248        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14249        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14250        for (int i = 0; i < upgradeKeySets.length; i++) {
14251            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14252            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14253                return true;
14254            }
14255        }
14256        return false;
14257    }
14258
14259    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14260        try (DigestInputStream digestStream =
14261                new DigestInputStream(new FileInputStream(file), digest)) {
14262            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14263        }
14264    }
14265
14266    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14267            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14268        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14269
14270        final PackageParser.Package oldPackage;
14271        final String pkgName = pkg.packageName;
14272        final int[] allUsers;
14273        final int[] installedUsers;
14274
14275        synchronized(mPackages) {
14276            oldPackage = mPackages.get(pkgName);
14277            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14278
14279            // don't allow upgrade to target a release SDK from a pre-release SDK
14280            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14281                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14282            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14283                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14284            if (oldTargetsPreRelease
14285                    && !newTargetsPreRelease
14286                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14287                Slog.w(TAG, "Can't install package targeting released sdk");
14288                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14289                return;
14290            }
14291
14292            // don't allow an upgrade from full to ephemeral
14293            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14294            if (isEphemeral && !oldIsEphemeral) {
14295                // can't downgrade from full to ephemeral
14296                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14297                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14298                return;
14299            }
14300
14301            // verify signatures are valid
14302            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14303            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14304                if (!checkUpgradeKeySetLP(ps, pkg)) {
14305                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14306                            "New package not signed by keys specified by upgrade-keysets: "
14307                                    + pkgName);
14308                    return;
14309                }
14310            } else {
14311                // default to original signature matching
14312                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14313                        != PackageManager.SIGNATURE_MATCH) {
14314                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14315                            "New package has a different signature: " + pkgName);
14316                    return;
14317                }
14318            }
14319
14320            // don't allow a system upgrade unless the upgrade hash matches
14321            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14322                byte[] digestBytes = null;
14323                try {
14324                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14325                    updateDigest(digest, new File(pkg.baseCodePath));
14326                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14327                        for (String path : pkg.splitCodePaths) {
14328                            updateDigest(digest, new File(path));
14329                        }
14330                    }
14331                    digestBytes = digest.digest();
14332                } catch (NoSuchAlgorithmException | IOException e) {
14333                    res.setError(INSTALL_FAILED_INVALID_APK,
14334                            "Could not compute hash: " + pkgName);
14335                    return;
14336                }
14337                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14338                    res.setError(INSTALL_FAILED_INVALID_APK,
14339                            "New package fails restrict-update check: " + pkgName);
14340                    return;
14341                }
14342                // retain upgrade restriction
14343                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14344            }
14345
14346            // Check for shared user id changes
14347            String invalidPackageName =
14348                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14349            if (invalidPackageName != null) {
14350                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14351                        "Package " + invalidPackageName + " tried to change user "
14352                                + oldPackage.mSharedUserId);
14353                return;
14354            }
14355
14356            // In case of rollback, remember per-user/profile install state
14357            allUsers = sUserManager.getUserIds();
14358            installedUsers = ps.queryInstalledUsers(allUsers, true);
14359        }
14360
14361        // Update what is removed
14362        res.removedInfo = new PackageRemovedInfo();
14363        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14364        res.removedInfo.removedPackage = oldPackage.packageName;
14365        res.removedInfo.isUpdate = true;
14366        res.removedInfo.origUsers = installedUsers;
14367        final int childCount = (oldPackage.childPackages != null)
14368                ? oldPackage.childPackages.size() : 0;
14369        for (int i = 0; i < childCount; i++) {
14370            boolean childPackageUpdated = false;
14371            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14372            if (res.addedChildPackages != null) {
14373                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14374                if (childRes != null) {
14375                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14376                    childRes.removedInfo.removedPackage = childPkg.packageName;
14377                    childRes.removedInfo.isUpdate = true;
14378                    childPackageUpdated = true;
14379                }
14380            }
14381            if (!childPackageUpdated) {
14382                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14383                childRemovedRes.removedPackage = childPkg.packageName;
14384                childRemovedRes.isUpdate = false;
14385                childRemovedRes.dataRemoved = true;
14386                synchronized (mPackages) {
14387                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14388                    if (childPs != null) {
14389                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14390                    }
14391                }
14392                if (res.removedInfo.removedChildPackages == null) {
14393                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14394                }
14395                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14396            }
14397        }
14398
14399        boolean sysPkg = (isSystemApp(oldPackage));
14400        if (sysPkg) {
14401            // Set the system/privileged flags as needed
14402            final boolean privileged =
14403                    (oldPackage.applicationInfo.privateFlags
14404                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14405            final int systemPolicyFlags = policyFlags
14406                    | PackageParser.PARSE_IS_SYSTEM
14407                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14408
14409            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14410                    user, allUsers, installerPackageName, res);
14411        } else {
14412            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14413                    user, allUsers, installerPackageName, res);
14414        }
14415    }
14416
14417    public List<String> getPreviousCodePaths(String packageName) {
14418        final PackageSetting ps = mSettings.mPackages.get(packageName);
14419        final List<String> result = new ArrayList<String>();
14420        if (ps != null && ps.oldCodePaths != null) {
14421            result.addAll(ps.oldCodePaths);
14422        }
14423        return result;
14424    }
14425
14426    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14427            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14428            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14429        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14430                + deletedPackage);
14431
14432        String pkgName = deletedPackage.packageName;
14433        boolean deletedPkg = true;
14434        boolean addedPkg = false;
14435        boolean updatedSettings = false;
14436        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14437        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14438                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14439
14440        final long origUpdateTime = (pkg.mExtras != null)
14441                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14442
14443        // First delete the existing package while retaining the data directory
14444        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14445                res.removedInfo, true, pkg)) {
14446            // If the existing package wasn't successfully deleted
14447            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14448            deletedPkg = false;
14449        } else {
14450            // Successfully deleted the old package; proceed with replace.
14451
14452            // If deleted package lived in a container, give users a chance to
14453            // relinquish resources before killing.
14454            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14455                if (DEBUG_INSTALL) {
14456                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14457                }
14458                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14459                final ArrayList<String> pkgList = new ArrayList<String>(1);
14460                pkgList.add(deletedPackage.applicationInfo.packageName);
14461                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14462            }
14463
14464            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14465                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14466            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14467
14468            try {
14469                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14470                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14471                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14472
14473                // Update the in-memory copy of the previous code paths.
14474                PackageSetting ps = mSettings.mPackages.get(pkgName);
14475                if (!killApp) {
14476                    if (ps.oldCodePaths == null) {
14477                        ps.oldCodePaths = new ArraySet<>();
14478                    }
14479                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14480                    if (deletedPackage.splitCodePaths != null) {
14481                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14482                    }
14483                } else {
14484                    ps.oldCodePaths = null;
14485                }
14486                if (ps.childPackageNames != null) {
14487                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14488                        final String childPkgName = ps.childPackageNames.get(i);
14489                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14490                        childPs.oldCodePaths = ps.oldCodePaths;
14491                    }
14492                }
14493                prepareAppDataAfterInstallLIF(newPackage);
14494                addedPkg = true;
14495                mDexManager.notifyPackageUpdated(newPackage.packageName,
14496                        newPackage.baseCodePath, newPackage.splitCodePaths);
14497            } catch (PackageManagerException e) {
14498                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14499            }
14500        }
14501
14502        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14503            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14504
14505            // Revert all internal state mutations and added folders for the failed install
14506            if (addedPkg) {
14507                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14508                        res.removedInfo, true, null);
14509            }
14510
14511            // Restore the old package
14512            if (deletedPkg) {
14513                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14514                File restoreFile = new File(deletedPackage.codePath);
14515                // Parse old package
14516                boolean oldExternal = isExternal(deletedPackage);
14517                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14518                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14519                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14520                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14521                try {
14522                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14523                            null);
14524                } catch (PackageManagerException e) {
14525                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14526                            + e.getMessage());
14527                    return;
14528                }
14529
14530                synchronized (mPackages) {
14531                    // Ensure the installer package name up to date
14532                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14533
14534                    // Update permissions for restored package
14535                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14536
14537                    mSettings.writeLPr();
14538                }
14539
14540                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14541            }
14542        } else {
14543            synchronized (mPackages) {
14544                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14545                if (ps != null) {
14546                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14547                    if (res.removedInfo.removedChildPackages != null) {
14548                        final int childCount = res.removedInfo.removedChildPackages.size();
14549                        // Iterate in reverse as we may modify the collection
14550                        for (int i = childCount - 1; i >= 0; i--) {
14551                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14552                            if (res.addedChildPackages.containsKey(childPackageName)) {
14553                                res.removedInfo.removedChildPackages.removeAt(i);
14554                            } else {
14555                                PackageRemovedInfo childInfo = res.removedInfo
14556                                        .removedChildPackages.valueAt(i);
14557                                childInfo.removedForAllUsers = mPackages.get(
14558                                        childInfo.removedPackage) == null;
14559                            }
14560                        }
14561                    }
14562                }
14563            }
14564        }
14565    }
14566
14567    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14568            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14569            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14570        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14571                + ", old=" + deletedPackage);
14572
14573        final boolean disabledSystem;
14574
14575        // Remove existing system package
14576        removePackageLI(deletedPackage, true);
14577
14578        synchronized (mPackages) {
14579            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14580        }
14581        if (!disabledSystem) {
14582            // We didn't need to disable the .apk as a current system package,
14583            // which means we are replacing another update that is already
14584            // installed.  We need to make sure to delete the older one's .apk.
14585            res.removedInfo.args = createInstallArgsForExisting(0,
14586                    deletedPackage.applicationInfo.getCodePath(),
14587                    deletedPackage.applicationInfo.getResourcePath(),
14588                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14589        } else {
14590            res.removedInfo.args = null;
14591        }
14592
14593        // Successfully disabled the old package. Now proceed with re-installation
14594        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14595                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14596        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14597
14598        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14599        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14600                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14601
14602        PackageParser.Package newPackage = null;
14603        try {
14604            // Add the package to the internal data structures
14605            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14606
14607            // Set the update and install times
14608            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14609            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14610                    System.currentTimeMillis());
14611
14612            // Update the package dynamic state if succeeded
14613            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14614                // Now that the install succeeded make sure we remove data
14615                // directories for any child package the update removed.
14616                final int deletedChildCount = (deletedPackage.childPackages != null)
14617                        ? deletedPackage.childPackages.size() : 0;
14618                final int newChildCount = (newPackage.childPackages != null)
14619                        ? newPackage.childPackages.size() : 0;
14620                for (int i = 0; i < deletedChildCount; i++) {
14621                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14622                    boolean childPackageDeleted = true;
14623                    for (int j = 0; j < newChildCount; j++) {
14624                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14625                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14626                            childPackageDeleted = false;
14627                            break;
14628                        }
14629                    }
14630                    if (childPackageDeleted) {
14631                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14632                                deletedChildPkg.packageName);
14633                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14634                            PackageRemovedInfo removedChildRes = res.removedInfo
14635                                    .removedChildPackages.get(deletedChildPkg.packageName);
14636                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14637                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14638                        }
14639                    }
14640                }
14641
14642                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14643                prepareAppDataAfterInstallLIF(newPackage);
14644
14645                mDexManager.notifyPackageUpdated(newPackage.packageName,
14646                            newPackage.baseCodePath, newPackage.splitCodePaths);
14647            }
14648        } catch (PackageManagerException e) {
14649            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14650            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14651        }
14652
14653        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14654            // Re installation failed. Restore old information
14655            // Remove new pkg information
14656            if (newPackage != null) {
14657                removeInstalledPackageLI(newPackage, true);
14658            }
14659            // Add back the old system package
14660            try {
14661                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14662            } catch (PackageManagerException e) {
14663                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14664            }
14665
14666            synchronized (mPackages) {
14667                if (disabledSystem) {
14668                    enableSystemPackageLPw(deletedPackage);
14669                }
14670
14671                // Ensure the installer package name up to date
14672                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14673
14674                // Update permissions for restored package
14675                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14676
14677                mSettings.writeLPr();
14678            }
14679
14680            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14681                    + " after failed upgrade");
14682        }
14683    }
14684
14685    /**
14686     * Checks whether the parent or any of the child packages have a change shared
14687     * user. For a package to be a valid update the shred users of the parent and
14688     * the children should match. We may later support changing child shared users.
14689     * @param oldPkg The updated package.
14690     * @param newPkg The update package.
14691     * @return The shared user that change between the versions.
14692     */
14693    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14694            PackageParser.Package newPkg) {
14695        // Check parent shared user
14696        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14697            return newPkg.packageName;
14698        }
14699        // Check child shared users
14700        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14701        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14702        for (int i = 0; i < newChildCount; i++) {
14703            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14704            // If this child was present, did it have the same shared user?
14705            for (int j = 0; j < oldChildCount; j++) {
14706                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14707                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14708                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14709                    return newChildPkg.packageName;
14710                }
14711            }
14712        }
14713        return null;
14714    }
14715
14716    private void removeNativeBinariesLI(PackageSetting ps) {
14717        // Remove the lib path for the parent package
14718        if (ps != null) {
14719            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14720            // Remove the lib path for the child packages
14721            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14722            for (int i = 0; i < childCount; i++) {
14723                PackageSetting childPs = null;
14724                synchronized (mPackages) {
14725                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14726                }
14727                if (childPs != null) {
14728                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14729                            .legacyNativeLibraryPathString);
14730                }
14731            }
14732        }
14733    }
14734
14735    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14736        // Enable the parent package
14737        mSettings.enableSystemPackageLPw(pkg.packageName);
14738        // Enable the child packages
14739        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14740        for (int i = 0; i < childCount; i++) {
14741            PackageParser.Package childPkg = pkg.childPackages.get(i);
14742            mSettings.enableSystemPackageLPw(childPkg.packageName);
14743        }
14744    }
14745
14746    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14747            PackageParser.Package newPkg) {
14748        // Disable the parent package (parent always replaced)
14749        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14750        // Disable the child packages
14751        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14752        for (int i = 0; i < childCount; i++) {
14753            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14754            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14755            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14756        }
14757        return disabled;
14758    }
14759
14760    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14761            String installerPackageName) {
14762        // Enable the parent package
14763        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14764        // Enable the child packages
14765        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14766        for (int i = 0; i < childCount; i++) {
14767            PackageParser.Package childPkg = pkg.childPackages.get(i);
14768            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14769        }
14770    }
14771
14772    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14773        // Collect all used permissions in the UID
14774        ArraySet<String> usedPermissions = new ArraySet<>();
14775        final int packageCount = su.packages.size();
14776        for (int i = 0; i < packageCount; i++) {
14777            PackageSetting ps = su.packages.valueAt(i);
14778            if (ps.pkg == null) {
14779                continue;
14780            }
14781            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14782            for (int j = 0; j < requestedPermCount; j++) {
14783                String permission = ps.pkg.requestedPermissions.get(j);
14784                BasePermission bp = mSettings.mPermissions.get(permission);
14785                if (bp != null) {
14786                    usedPermissions.add(permission);
14787                }
14788            }
14789        }
14790
14791        PermissionsState permissionsState = su.getPermissionsState();
14792        // Prune install permissions
14793        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14794        final int installPermCount = installPermStates.size();
14795        for (int i = installPermCount - 1; i >= 0;  i--) {
14796            PermissionState permissionState = installPermStates.get(i);
14797            if (!usedPermissions.contains(permissionState.getName())) {
14798                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14799                if (bp != null) {
14800                    permissionsState.revokeInstallPermission(bp);
14801                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14802                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14803                }
14804            }
14805        }
14806
14807        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14808
14809        // Prune runtime permissions
14810        for (int userId : allUserIds) {
14811            List<PermissionState> runtimePermStates = permissionsState
14812                    .getRuntimePermissionStates(userId);
14813            final int runtimePermCount = runtimePermStates.size();
14814            for (int i = runtimePermCount - 1; i >= 0; i--) {
14815                PermissionState permissionState = runtimePermStates.get(i);
14816                if (!usedPermissions.contains(permissionState.getName())) {
14817                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14818                    if (bp != null) {
14819                        permissionsState.revokeRuntimePermission(bp, userId);
14820                        permissionsState.updatePermissionFlags(bp, userId,
14821                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14822                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14823                                runtimePermissionChangedUserIds, userId);
14824                    }
14825                }
14826            }
14827        }
14828
14829        return runtimePermissionChangedUserIds;
14830    }
14831
14832    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14833            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14834        // Update the parent package setting
14835        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14836                res, user);
14837        // Update the child packages setting
14838        final int childCount = (newPackage.childPackages != null)
14839                ? newPackage.childPackages.size() : 0;
14840        for (int i = 0; i < childCount; i++) {
14841            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14842            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14843            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14844                    childRes.origUsers, childRes, user);
14845        }
14846    }
14847
14848    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14849            String installerPackageName, int[] allUsers, int[] installedForUsers,
14850            PackageInstalledInfo res, UserHandle user) {
14851        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14852
14853        String pkgName = newPackage.packageName;
14854        synchronized (mPackages) {
14855            //write settings. the installStatus will be incomplete at this stage.
14856            //note that the new package setting would have already been
14857            //added to mPackages. It hasn't been persisted yet.
14858            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14859            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14860            mSettings.writeLPr();
14861            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14862        }
14863
14864        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14865        synchronized (mPackages) {
14866            updatePermissionsLPw(newPackage.packageName, newPackage,
14867                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14868                            ? UPDATE_PERMISSIONS_ALL : 0));
14869            // For system-bundled packages, we assume that installing an upgraded version
14870            // of the package implies that the user actually wants to run that new code,
14871            // so we enable the package.
14872            PackageSetting ps = mSettings.mPackages.get(pkgName);
14873            final int userId = user.getIdentifier();
14874            if (ps != null) {
14875                if (isSystemApp(newPackage)) {
14876                    if (DEBUG_INSTALL) {
14877                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14878                    }
14879                    // Enable system package for requested users
14880                    if (res.origUsers != null) {
14881                        for (int origUserId : res.origUsers) {
14882                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14883                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14884                                        origUserId, installerPackageName);
14885                            }
14886                        }
14887                    }
14888                    // Also convey the prior install/uninstall state
14889                    if (allUsers != null && installedForUsers != null) {
14890                        for (int currentUserId : allUsers) {
14891                            final boolean installed = ArrayUtils.contains(
14892                                    installedForUsers, currentUserId);
14893                            if (DEBUG_INSTALL) {
14894                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14895                            }
14896                            ps.setInstalled(installed, currentUserId);
14897                        }
14898                        // these install state changes will be persisted in the
14899                        // upcoming call to mSettings.writeLPr().
14900                    }
14901                }
14902                // It's implied that when a user requests installation, they want the app to be
14903                // installed and enabled.
14904                if (userId != UserHandle.USER_ALL) {
14905                    ps.setInstalled(true, userId);
14906                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14907                }
14908            }
14909            res.name = pkgName;
14910            res.uid = newPackage.applicationInfo.uid;
14911            res.pkg = newPackage;
14912            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14913            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14914            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14915            //to update install status
14916            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14917            mSettings.writeLPr();
14918            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14919        }
14920
14921        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14922    }
14923
14924    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14925        try {
14926            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14927            installPackageLI(args, res);
14928        } finally {
14929            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14930        }
14931    }
14932
14933    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14934        final int installFlags = args.installFlags;
14935        final String installerPackageName = args.installerPackageName;
14936        final String volumeUuid = args.volumeUuid;
14937        final File tmpPackageFile = new File(args.getCodePath());
14938        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14939        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14940                || (args.volumeUuid != null));
14941        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14942        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14943        boolean replace = false;
14944        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14945        if (args.move != null) {
14946            // moving a complete application; perform an initial scan on the new install location
14947            scanFlags |= SCAN_INITIAL;
14948        }
14949        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14950            scanFlags |= SCAN_DONT_KILL_APP;
14951        }
14952
14953        // Result object to be returned
14954        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14955
14956        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14957
14958        // Sanity check
14959        if (ephemeral && (forwardLocked || onExternal)) {
14960            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14961                    + " external=" + onExternal);
14962            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14963            return;
14964        }
14965
14966        // Retrieve PackageSettings and parse package
14967        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14968                | PackageParser.PARSE_ENFORCE_CODE
14969                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14970                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14971                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14972                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14973        PackageParser pp = new PackageParser();
14974        pp.setSeparateProcesses(mSeparateProcesses);
14975        pp.setDisplayMetrics(mMetrics);
14976
14977        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14978        final PackageParser.Package pkg;
14979        try {
14980            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14981        } catch (PackageParserException e) {
14982            res.setError("Failed parse during installPackageLI", e);
14983            return;
14984        } finally {
14985            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14986        }
14987
14988        // If we are installing a clustered package add results for the children
14989        if (pkg.childPackages != null) {
14990            synchronized (mPackages) {
14991                final int childCount = pkg.childPackages.size();
14992                for (int i = 0; i < childCount; i++) {
14993                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14994                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14995                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14996                    childRes.pkg = childPkg;
14997                    childRes.name = childPkg.packageName;
14998                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14999                    if (childPs != null) {
15000                        childRes.origUsers = childPs.queryInstalledUsers(
15001                                sUserManager.getUserIds(), true);
15002                    }
15003                    if ((mPackages.containsKey(childPkg.packageName))) {
15004                        childRes.removedInfo = new PackageRemovedInfo();
15005                        childRes.removedInfo.removedPackage = childPkg.packageName;
15006                    }
15007                    if (res.addedChildPackages == null) {
15008                        res.addedChildPackages = new ArrayMap<>();
15009                    }
15010                    res.addedChildPackages.put(childPkg.packageName, childRes);
15011                }
15012            }
15013        }
15014
15015        // If package doesn't declare API override, mark that we have an install
15016        // time CPU ABI override.
15017        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15018            pkg.cpuAbiOverride = args.abiOverride;
15019        }
15020
15021        String pkgName = res.name = pkg.packageName;
15022        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15023            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15024                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15025                return;
15026            }
15027        }
15028
15029        try {
15030            // either use what we've been given or parse directly from the APK
15031            if (args.certificates != null) {
15032                try {
15033                    PackageParser.populateCertificates(pkg, args.certificates);
15034                } catch (PackageParserException e) {
15035                    // there was something wrong with the certificates we were given;
15036                    // try to pull them from the APK
15037                    PackageParser.collectCertificates(pkg, parseFlags);
15038                }
15039            } else {
15040                PackageParser.collectCertificates(pkg, parseFlags);
15041            }
15042        } catch (PackageParserException e) {
15043            res.setError("Failed collect during installPackageLI", e);
15044            return;
15045        }
15046
15047        // Get rid of all references to package scan path via parser.
15048        pp = null;
15049        String oldCodePath = null;
15050        boolean systemApp = false;
15051        synchronized (mPackages) {
15052            // Check if installing already existing package
15053            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15054                String oldName = mSettings.mRenamedPackages.get(pkgName);
15055                if (pkg.mOriginalPackages != null
15056                        && pkg.mOriginalPackages.contains(oldName)
15057                        && mPackages.containsKey(oldName)) {
15058                    // This package is derived from an original package,
15059                    // and this device has been updating from that original
15060                    // name.  We must continue using the original name, so
15061                    // rename the new package here.
15062                    pkg.setPackageName(oldName);
15063                    pkgName = pkg.packageName;
15064                    replace = true;
15065                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15066                            + oldName + " pkgName=" + pkgName);
15067                } else if (mPackages.containsKey(pkgName)) {
15068                    // This package, under its official name, already exists
15069                    // on the device; we should replace it.
15070                    replace = true;
15071                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15072                }
15073
15074                // Child packages are installed through the parent package
15075                if (pkg.parentPackage != null) {
15076                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15077                            "Package " + pkg.packageName + " is child of package "
15078                                    + pkg.parentPackage.parentPackage + ". Child packages "
15079                                    + "can be updated only through the parent package.");
15080                    return;
15081                }
15082
15083                if (replace) {
15084                    // Prevent apps opting out from runtime permissions
15085                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15086                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15087                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15088                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15089                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15090                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15091                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15092                                        + " doesn't support runtime permissions but the old"
15093                                        + " target SDK " + oldTargetSdk + " does.");
15094                        return;
15095                    }
15096
15097                    // Prevent installing of child packages
15098                    if (oldPackage.parentPackage != null) {
15099                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15100                                "Package " + pkg.packageName + " is child of package "
15101                                        + oldPackage.parentPackage + ". Child packages "
15102                                        + "can be updated only through the parent package.");
15103                        return;
15104                    }
15105                }
15106            }
15107
15108            PackageSetting ps = mSettings.mPackages.get(pkgName);
15109            if (ps != null) {
15110                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15111
15112                // Quick sanity check that we're signed correctly if updating;
15113                // we'll check this again later when scanning, but we want to
15114                // bail early here before tripping over redefined permissions.
15115                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15116                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15117                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15118                                + pkg.packageName + " upgrade keys do not match the "
15119                                + "previously installed version");
15120                        return;
15121                    }
15122                } else {
15123                    try {
15124                        verifySignaturesLP(ps, pkg);
15125                    } catch (PackageManagerException e) {
15126                        res.setError(e.error, e.getMessage());
15127                        return;
15128                    }
15129                }
15130
15131                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15132                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15133                    systemApp = (ps.pkg.applicationInfo.flags &
15134                            ApplicationInfo.FLAG_SYSTEM) != 0;
15135                }
15136                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15137            }
15138
15139            // Check whether the newly-scanned package wants to define an already-defined perm
15140            int N = pkg.permissions.size();
15141            for (int i = N-1; i >= 0; i--) {
15142                PackageParser.Permission perm = pkg.permissions.get(i);
15143                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15144                if (bp != null) {
15145                    // If the defining package is signed with our cert, it's okay.  This
15146                    // also includes the "updating the same package" case, of course.
15147                    // "updating same package" could also involve key-rotation.
15148                    final boolean sigsOk;
15149                    if (bp.sourcePackage.equals(pkg.packageName)
15150                            && (bp.packageSetting instanceof PackageSetting)
15151                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15152                                    scanFlags))) {
15153                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15154                    } else {
15155                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15156                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15157                    }
15158                    if (!sigsOk) {
15159                        // If the owning package is the system itself, we log but allow
15160                        // install to proceed; we fail the install on all other permission
15161                        // redefinitions.
15162                        if (!bp.sourcePackage.equals("android")) {
15163                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15164                                    + pkg.packageName + " attempting to redeclare permission "
15165                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15166                            res.origPermission = perm.info.name;
15167                            res.origPackage = bp.sourcePackage;
15168                            return;
15169                        } else {
15170                            Slog.w(TAG, "Package " + pkg.packageName
15171                                    + " attempting to redeclare system permission "
15172                                    + perm.info.name + "; ignoring new declaration");
15173                            pkg.permissions.remove(i);
15174                        }
15175                    }
15176                }
15177            }
15178        }
15179
15180        if (systemApp) {
15181            if (onExternal) {
15182                // Abort update; system app can't be replaced with app on sdcard
15183                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15184                        "Cannot install updates to system apps on sdcard");
15185                return;
15186            } else if (ephemeral) {
15187                // Abort update; system app can't be replaced with an ephemeral app
15188                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15189                        "Cannot update a system app with an ephemeral app");
15190                return;
15191            }
15192        }
15193
15194        if (args.move != null) {
15195            // We did an in-place move, so dex is ready to roll
15196            scanFlags |= SCAN_NO_DEX;
15197            scanFlags |= SCAN_MOVE;
15198
15199            synchronized (mPackages) {
15200                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15201                if (ps == null) {
15202                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15203                            "Missing settings for moved package " + pkgName);
15204                }
15205
15206                // We moved the entire application as-is, so bring over the
15207                // previously derived ABI information.
15208                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15209                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15210            }
15211
15212        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15213            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15214            scanFlags |= SCAN_NO_DEX;
15215
15216            try {
15217                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15218                    args.abiOverride : pkg.cpuAbiOverride);
15219                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15220                        true /* extract libs */);
15221            } catch (PackageManagerException pme) {
15222                Slog.e(TAG, "Error deriving application ABI", pme);
15223                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15224                return;
15225            }
15226
15227            // Shared libraries for the package need to be updated.
15228            synchronized (mPackages) {
15229                try {
15230                    updateSharedLibrariesLPw(pkg, null);
15231                } catch (PackageManagerException e) {
15232                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15233                }
15234            }
15235            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15236            // Do not run PackageDexOptimizer through the local performDexOpt
15237            // method because `pkg` may not be in `mPackages` yet.
15238            //
15239            // Also, don't fail application installs if the dexopt step fails.
15240            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15241                    null /* instructionSets */, false /* checkProfiles */,
15242                    getCompilerFilterForReason(REASON_INSTALL),
15243                    getOrCreateCompilerPackageStats(pkg),
15244                    mDexManager.isUsedByOtherApps(pkg.packageName));
15245            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15246
15247            // Notify BackgroundDexOptService that the package has been changed.
15248            // If this is an update of a package which used to fail to compile,
15249            // BDOS will remove it from its blacklist.
15250            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15251        }
15252
15253        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15254            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15255            return;
15256        }
15257
15258        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15259
15260        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15261                "installPackageLI")) {
15262            if (replace) {
15263                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15264                        installerPackageName, res);
15265            } else {
15266                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15267                        args.user, installerPackageName, volumeUuid, res);
15268            }
15269        }
15270        synchronized (mPackages) {
15271            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15272            if (ps != null) {
15273                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15274            }
15275
15276            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15277            for (int i = 0; i < childCount; i++) {
15278                PackageParser.Package childPkg = pkg.childPackages.get(i);
15279                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15280                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15281                if (childPs != null) {
15282                    childRes.newUsers = childPs.queryInstalledUsers(
15283                            sUserManager.getUserIds(), true);
15284                }
15285            }
15286        }
15287    }
15288
15289    private void startIntentFilterVerifications(int userId, boolean replacing,
15290            PackageParser.Package pkg) {
15291        if (mIntentFilterVerifierComponent == null) {
15292            Slog.w(TAG, "No IntentFilter verification will not be done as "
15293                    + "there is no IntentFilterVerifier available!");
15294            return;
15295        }
15296
15297        final int verifierUid = getPackageUid(
15298                mIntentFilterVerifierComponent.getPackageName(),
15299                MATCH_DEBUG_TRIAGED_MISSING,
15300                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15301
15302        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15303        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15304        mHandler.sendMessage(msg);
15305
15306        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15307        for (int i = 0; i < childCount; i++) {
15308            PackageParser.Package childPkg = pkg.childPackages.get(i);
15309            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15310            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15311            mHandler.sendMessage(msg);
15312        }
15313    }
15314
15315    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15316            PackageParser.Package pkg) {
15317        int size = pkg.activities.size();
15318        if (size == 0) {
15319            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15320                    "No activity, so no need to verify any IntentFilter!");
15321            return;
15322        }
15323
15324        final boolean hasDomainURLs = hasDomainURLs(pkg);
15325        if (!hasDomainURLs) {
15326            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15327                    "No domain URLs, so no need to verify any IntentFilter!");
15328            return;
15329        }
15330
15331        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15332                + " if any IntentFilter from the " + size
15333                + " Activities needs verification ...");
15334
15335        int count = 0;
15336        final String packageName = pkg.packageName;
15337
15338        synchronized (mPackages) {
15339            // If this is a new install and we see that we've already run verification for this
15340            // package, we have nothing to do: it means the state was restored from backup.
15341            if (!replacing) {
15342                IntentFilterVerificationInfo ivi =
15343                        mSettings.getIntentFilterVerificationLPr(packageName);
15344                if (ivi != null) {
15345                    if (DEBUG_DOMAIN_VERIFICATION) {
15346                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15347                                + ivi.getStatusString());
15348                    }
15349                    return;
15350                }
15351            }
15352
15353            // If any filters need to be verified, then all need to be.
15354            boolean needToVerify = false;
15355            for (PackageParser.Activity a : pkg.activities) {
15356                for (ActivityIntentInfo filter : a.intents) {
15357                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15358                        if (DEBUG_DOMAIN_VERIFICATION) {
15359                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15360                        }
15361                        needToVerify = true;
15362                        break;
15363                    }
15364                }
15365            }
15366
15367            if (needToVerify) {
15368                final int verificationId = mIntentFilterVerificationToken++;
15369                for (PackageParser.Activity a : pkg.activities) {
15370                    for (ActivityIntentInfo filter : a.intents) {
15371                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15372                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15373                                    "Verification needed for IntentFilter:" + filter.toString());
15374                            mIntentFilterVerifier.addOneIntentFilterVerification(
15375                                    verifierUid, userId, verificationId, filter, packageName);
15376                            count++;
15377                        }
15378                    }
15379                }
15380            }
15381        }
15382
15383        if (count > 0) {
15384            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15385                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15386                    +  " for userId:" + userId);
15387            mIntentFilterVerifier.startVerifications(userId);
15388        } else {
15389            if (DEBUG_DOMAIN_VERIFICATION) {
15390                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15391            }
15392        }
15393    }
15394
15395    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15396        final ComponentName cn  = filter.activity.getComponentName();
15397        final String packageName = cn.getPackageName();
15398
15399        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15400                packageName);
15401        if (ivi == null) {
15402            return true;
15403        }
15404        int status = ivi.getStatus();
15405        switch (status) {
15406            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15407            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15408                return true;
15409
15410            default:
15411                // Nothing to do
15412                return false;
15413        }
15414    }
15415
15416    private static boolean isMultiArch(ApplicationInfo info) {
15417        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15418    }
15419
15420    private static boolean isExternal(PackageParser.Package pkg) {
15421        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15422    }
15423
15424    private static boolean isExternal(PackageSetting ps) {
15425        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15426    }
15427
15428    private static boolean isEphemeral(PackageParser.Package pkg) {
15429        return pkg.applicationInfo.isEphemeralApp();
15430    }
15431
15432    private static boolean isEphemeral(PackageSetting ps) {
15433        return ps.pkg != null && isEphemeral(ps.pkg);
15434    }
15435
15436    private static boolean isSystemApp(PackageParser.Package pkg) {
15437        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15438    }
15439
15440    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15441        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15442    }
15443
15444    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15445        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15446    }
15447
15448    private static boolean isSystemApp(PackageSetting ps) {
15449        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15450    }
15451
15452    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15453        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15454    }
15455
15456    private int packageFlagsToInstallFlags(PackageSetting ps) {
15457        int installFlags = 0;
15458        if (isEphemeral(ps)) {
15459            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15460        }
15461        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15462            // This existing package was an external ASEC install when we have
15463            // the external flag without a UUID
15464            installFlags |= PackageManager.INSTALL_EXTERNAL;
15465        }
15466        if (ps.isForwardLocked()) {
15467            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15468        }
15469        return installFlags;
15470    }
15471
15472    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15473        if (isExternal(pkg)) {
15474            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15475                return StorageManager.UUID_PRIMARY_PHYSICAL;
15476            } else {
15477                return pkg.volumeUuid;
15478            }
15479        } else {
15480            return StorageManager.UUID_PRIVATE_INTERNAL;
15481        }
15482    }
15483
15484    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15485        if (isExternal(pkg)) {
15486            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15487                return mSettings.getExternalVersion();
15488            } else {
15489                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15490            }
15491        } else {
15492            return mSettings.getInternalVersion();
15493        }
15494    }
15495
15496    private void deleteTempPackageFiles() {
15497        final FilenameFilter filter = new FilenameFilter() {
15498            public boolean accept(File dir, String name) {
15499                return name.startsWith("vmdl") && name.endsWith(".tmp");
15500            }
15501        };
15502        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15503            file.delete();
15504        }
15505    }
15506
15507    @Override
15508    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15509            int flags) {
15510        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15511                flags);
15512    }
15513
15514    @Override
15515    public void deletePackage(final String packageName,
15516            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15517        mContext.enforceCallingOrSelfPermission(
15518                android.Manifest.permission.DELETE_PACKAGES, null);
15519        Preconditions.checkNotNull(packageName);
15520        Preconditions.checkNotNull(observer);
15521        final int uid = Binder.getCallingUid();
15522        if (!isOrphaned(packageName)
15523                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15524            try {
15525                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15526                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15527                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15528                observer.onUserActionRequired(intent);
15529            } catch (RemoteException re) {
15530            }
15531            return;
15532        }
15533        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15534        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15535        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15536            mContext.enforceCallingOrSelfPermission(
15537                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15538                    "deletePackage for user " + userId);
15539        }
15540
15541        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15542            try {
15543                observer.onPackageDeleted(packageName,
15544                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15545            } catch (RemoteException re) {
15546            }
15547            return;
15548        }
15549
15550        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15551            try {
15552                observer.onPackageDeleted(packageName,
15553                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15554            } catch (RemoteException re) {
15555            }
15556            return;
15557        }
15558
15559        if (DEBUG_REMOVE) {
15560            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15561                    + " deleteAllUsers: " + deleteAllUsers );
15562        }
15563        // Queue up an async operation since the package deletion may take a little while.
15564        mHandler.post(new Runnable() {
15565            public void run() {
15566                mHandler.removeCallbacks(this);
15567                int returnCode;
15568                if (!deleteAllUsers) {
15569                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15570                } else {
15571                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15572                    // If nobody is blocking uninstall, proceed with delete for all users
15573                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15574                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15575                    } else {
15576                        // Otherwise uninstall individually for users with blockUninstalls=false
15577                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15578                        for (int userId : users) {
15579                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15580                                returnCode = deletePackageX(packageName, userId, userFlags);
15581                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15582                                    Slog.w(TAG, "Package delete failed for user " + userId
15583                                            + ", returnCode " + returnCode);
15584                                }
15585                            }
15586                        }
15587                        // The app has only been marked uninstalled for certain users.
15588                        // We still need to report that delete was blocked
15589                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15590                    }
15591                }
15592                try {
15593                    observer.onPackageDeleted(packageName, returnCode, null);
15594                } catch (RemoteException e) {
15595                    Log.i(TAG, "Observer no longer exists.");
15596                } //end catch
15597            } //end run
15598        });
15599    }
15600
15601    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15602        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15603              || callingUid == Process.SYSTEM_UID) {
15604            return true;
15605        }
15606        final int callingUserId = UserHandle.getUserId(callingUid);
15607        // If the caller installed the pkgName, then allow it to silently uninstall.
15608        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15609            return true;
15610        }
15611
15612        // Allow package verifier to silently uninstall.
15613        if (mRequiredVerifierPackage != null &&
15614                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15615            return true;
15616        }
15617
15618        // Allow package uninstaller to silently uninstall.
15619        if (mRequiredUninstallerPackage != null &&
15620                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15621            return true;
15622        }
15623
15624        // Allow storage manager to silently uninstall.
15625        if (mStorageManagerPackage != null &&
15626                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
15627            return true;
15628        }
15629        return false;
15630    }
15631
15632    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15633        int[] result = EMPTY_INT_ARRAY;
15634        for (int userId : userIds) {
15635            if (getBlockUninstallForUser(packageName, userId)) {
15636                result = ArrayUtils.appendInt(result, userId);
15637            }
15638        }
15639        return result;
15640    }
15641
15642    @Override
15643    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15644        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15645    }
15646
15647    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15648        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15649                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15650        try {
15651            if (dpm != null) {
15652                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15653                        /* callingUserOnly =*/ false);
15654                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15655                        : deviceOwnerComponentName.getPackageName();
15656                // Does the package contains the device owner?
15657                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15658                // this check is probably not needed, since DO should be registered as a device
15659                // admin on some user too. (Original bug for this: b/17657954)
15660                if (packageName.equals(deviceOwnerPackageName)) {
15661                    return true;
15662                }
15663                // Does it contain a device admin for any user?
15664                int[] users;
15665                if (userId == UserHandle.USER_ALL) {
15666                    users = sUserManager.getUserIds();
15667                } else {
15668                    users = new int[]{userId};
15669                }
15670                for (int i = 0; i < users.length; ++i) {
15671                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15672                        return true;
15673                    }
15674                }
15675            }
15676        } catch (RemoteException e) {
15677        }
15678        return false;
15679    }
15680
15681    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15682        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15683    }
15684
15685    /**
15686     *  This method is an internal method that could be get invoked either
15687     *  to delete an installed package or to clean up a failed installation.
15688     *  After deleting an installed package, a broadcast is sent to notify any
15689     *  listeners that the package has been removed. For cleaning up a failed
15690     *  installation, the broadcast is not necessary since the package's
15691     *  installation wouldn't have sent the initial broadcast either
15692     *  The key steps in deleting a package are
15693     *  deleting the package information in internal structures like mPackages,
15694     *  deleting the packages base directories through installd
15695     *  updating mSettings to reflect current status
15696     *  persisting settings for later use
15697     *  sending a broadcast if necessary
15698     */
15699    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15700        final PackageRemovedInfo info = new PackageRemovedInfo();
15701        final boolean res;
15702
15703        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15704                ? UserHandle.USER_ALL : userId;
15705
15706        if (isPackageDeviceAdmin(packageName, removeUser)) {
15707            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15708            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15709        }
15710
15711        PackageSetting uninstalledPs = null;
15712
15713        // for the uninstall-updates case and restricted profiles, remember the per-
15714        // user handle installed state
15715        int[] allUsers;
15716        synchronized (mPackages) {
15717            uninstalledPs = mSettings.mPackages.get(packageName);
15718            if (uninstalledPs == null) {
15719                Slog.w(TAG, "Not removing non-existent package " + packageName);
15720                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15721            }
15722            allUsers = sUserManager.getUserIds();
15723            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15724        }
15725
15726        final int freezeUser;
15727        if (isUpdatedSystemApp(uninstalledPs)
15728                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15729            // We're downgrading a system app, which will apply to all users, so
15730            // freeze them all during the downgrade
15731            freezeUser = UserHandle.USER_ALL;
15732        } else {
15733            freezeUser = removeUser;
15734        }
15735
15736        synchronized (mInstallLock) {
15737            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15738            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15739                    deleteFlags, "deletePackageX")) {
15740                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15741                        deleteFlags | REMOVE_CHATTY, info, true, null);
15742            }
15743            synchronized (mPackages) {
15744                if (res) {
15745                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15746                }
15747            }
15748        }
15749
15750        if (res) {
15751            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15752            info.sendPackageRemovedBroadcasts(killApp);
15753            info.sendSystemPackageUpdatedBroadcasts();
15754            info.sendSystemPackageAppearedBroadcasts();
15755        }
15756        // Force a gc here.
15757        Runtime.getRuntime().gc();
15758        // Delete the resources here after sending the broadcast to let
15759        // other processes clean up before deleting resources.
15760        if (info.args != null) {
15761            synchronized (mInstallLock) {
15762                info.args.doPostDeleteLI(true);
15763            }
15764        }
15765
15766        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15767    }
15768
15769    class PackageRemovedInfo {
15770        String removedPackage;
15771        int uid = -1;
15772        int removedAppId = -1;
15773        int[] origUsers;
15774        int[] removedUsers = null;
15775        boolean isRemovedPackageSystemUpdate = false;
15776        boolean isUpdate;
15777        boolean dataRemoved;
15778        boolean removedForAllUsers;
15779        // Clean up resources deleted packages.
15780        InstallArgs args = null;
15781        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15782        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15783
15784        void sendPackageRemovedBroadcasts(boolean killApp) {
15785            sendPackageRemovedBroadcastInternal(killApp);
15786            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15787            for (int i = 0; i < childCount; i++) {
15788                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15789                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15790            }
15791        }
15792
15793        void sendSystemPackageUpdatedBroadcasts() {
15794            if (isRemovedPackageSystemUpdate) {
15795                sendSystemPackageUpdatedBroadcastsInternal();
15796                final int childCount = (removedChildPackages != null)
15797                        ? removedChildPackages.size() : 0;
15798                for (int i = 0; i < childCount; i++) {
15799                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15800                    if (childInfo.isRemovedPackageSystemUpdate) {
15801                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15802                    }
15803                }
15804            }
15805        }
15806
15807        void sendSystemPackageAppearedBroadcasts() {
15808            final int packageCount = (appearedChildPackages != null)
15809                    ? appearedChildPackages.size() : 0;
15810            for (int i = 0; i < packageCount; i++) {
15811                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15812                for (int userId : installedInfo.newUsers) {
15813                    sendPackageAddedForUser(installedInfo.name, true,
15814                            UserHandle.getAppId(installedInfo.uid), userId);
15815                }
15816            }
15817        }
15818
15819        private void sendSystemPackageUpdatedBroadcastsInternal() {
15820            Bundle extras = new Bundle(2);
15821            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15822            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15823            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15824                    extras, 0, null, null, null);
15825            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15826                    extras, 0, null, null, null);
15827            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15828                    null, 0, removedPackage, null, null);
15829        }
15830
15831        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15832            Bundle extras = new Bundle(2);
15833            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15834            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15835            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15836            if (isUpdate || isRemovedPackageSystemUpdate) {
15837                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15838            }
15839            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15840            if (removedPackage != null) {
15841                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15842                        extras, 0, null, null, removedUsers);
15843                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15844                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15845                            removedPackage, extras, 0, null, null, removedUsers);
15846                }
15847            }
15848            if (removedAppId >= 0) {
15849                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15850                        removedUsers);
15851            }
15852        }
15853    }
15854
15855    /*
15856     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15857     * flag is not set, the data directory is removed as well.
15858     * make sure this flag is set for partially installed apps. If not its meaningless to
15859     * delete a partially installed application.
15860     */
15861    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15862            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15863        String packageName = ps.name;
15864        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15865        // Retrieve object to delete permissions for shared user later on
15866        final PackageParser.Package deletedPkg;
15867        final PackageSetting deletedPs;
15868        // reader
15869        synchronized (mPackages) {
15870            deletedPkg = mPackages.get(packageName);
15871            deletedPs = mSettings.mPackages.get(packageName);
15872            if (outInfo != null) {
15873                outInfo.removedPackage = packageName;
15874                outInfo.removedUsers = deletedPs != null
15875                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15876                        : null;
15877            }
15878        }
15879
15880        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15881
15882        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15883            final PackageParser.Package resolvedPkg;
15884            if (deletedPkg != null) {
15885                resolvedPkg = deletedPkg;
15886            } else {
15887                // We don't have a parsed package when it lives on an ejected
15888                // adopted storage device, so fake something together
15889                resolvedPkg = new PackageParser.Package(ps.name);
15890                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15891            }
15892            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15893                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15894            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15895            if (outInfo != null) {
15896                outInfo.dataRemoved = true;
15897            }
15898            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15899        }
15900
15901        // writer
15902        synchronized (mPackages) {
15903            if (deletedPs != null) {
15904                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15905                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15906                    clearDefaultBrowserIfNeeded(packageName);
15907                    if (outInfo != null) {
15908                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15909                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15910                    }
15911                    updatePermissionsLPw(deletedPs.name, null, 0);
15912                    if (deletedPs.sharedUser != null) {
15913                        // Remove permissions associated with package. Since runtime
15914                        // permissions are per user we have to kill the removed package
15915                        // or packages running under the shared user of the removed
15916                        // package if revoking the permissions requested only by the removed
15917                        // package is successful and this causes a change in gids.
15918                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15919                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15920                                    userId);
15921                            if (userIdToKill == UserHandle.USER_ALL
15922                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15923                                // If gids changed for this user, kill all affected packages.
15924                                mHandler.post(new Runnable() {
15925                                    @Override
15926                                    public void run() {
15927                                        // This has to happen with no lock held.
15928                                        killApplication(deletedPs.name, deletedPs.appId,
15929                                                KILL_APP_REASON_GIDS_CHANGED);
15930                                    }
15931                                });
15932                                break;
15933                            }
15934                        }
15935                    }
15936                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15937                }
15938                // make sure to preserve per-user disabled state if this removal was just
15939                // a downgrade of a system app to the factory package
15940                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15941                    if (DEBUG_REMOVE) {
15942                        Slog.d(TAG, "Propagating install state across downgrade");
15943                    }
15944                    for (int userId : allUserHandles) {
15945                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15946                        if (DEBUG_REMOVE) {
15947                            Slog.d(TAG, "    user " + userId + " => " + installed);
15948                        }
15949                        ps.setInstalled(installed, userId);
15950                    }
15951                }
15952            }
15953            // can downgrade to reader
15954            if (writeSettings) {
15955                // Save settings now
15956                mSettings.writeLPr();
15957            }
15958        }
15959        if (outInfo != null) {
15960            // A user ID was deleted here. Go through all users and remove it
15961            // from KeyStore.
15962            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15963        }
15964    }
15965
15966    static boolean locationIsPrivileged(File path) {
15967        try {
15968            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15969                    .getCanonicalPath();
15970            return path.getCanonicalPath().startsWith(privilegedAppDir);
15971        } catch (IOException e) {
15972            Slog.e(TAG, "Unable to access code path " + path);
15973        }
15974        return false;
15975    }
15976
15977    /*
15978     * Tries to delete system package.
15979     */
15980    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15981            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15982            boolean writeSettings) {
15983        if (deletedPs.parentPackageName != null) {
15984            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15985            return false;
15986        }
15987
15988        final boolean applyUserRestrictions
15989                = (allUserHandles != null) && (outInfo.origUsers != null);
15990        final PackageSetting disabledPs;
15991        // Confirm if the system package has been updated
15992        // An updated system app can be deleted. This will also have to restore
15993        // the system pkg from system partition
15994        // reader
15995        synchronized (mPackages) {
15996            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15997        }
15998
15999        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16000                + " disabledPs=" + disabledPs);
16001
16002        if (disabledPs == null) {
16003            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16004            return false;
16005        } else if (DEBUG_REMOVE) {
16006            Slog.d(TAG, "Deleting system pkg from data partition");
16007        }
16008
16009        if (DEBUG_REMOVE) {
16010            if (applyUserRestrictions) {
16011                Slog.d(TAG, "Remembering install states:");
16012                for (int userId : allUserHandles) {
16013                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16014                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
16015                }
16016            }
16017        }
16018
16019        // Delete the updated package
16020        outInfo.isRemovedPackageSystemUpdate = true;
16021        if (outInfo.removedChildPackages != null) {
16022            final int childCount = (deletedPs.childPackageNames != null)
16023                    ? deletedPs.childPackageNames.size() : 0;
16024            for (int i = 0; i < childCount; i++) {
16025                String childPackageName = deletedPs.childPackageNames.get(i);
16026                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16027                        .contains(childPackageName)) {
16028                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16029                            childPackageName);
16030                    if (childInfo != null) {
16031                        childInfo.isRemovedPackageSystemUpdate = true;
16032                    }
16033                }
16034            }
16035        }
16036
16037        if (disabledPs.versionCode < deletedPs.versionCode) {
16038            // Delete data for downgrades
16039            flags &= ~PackageManager.DELETE_KEEP_DATA;
16040        } else {
16041            // Preserve data by setting flag
16042            flags |= PackageManager.DELETE_KEEP_DATA;
16043        }
16044
16045        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16046                outInfo, writeSettings, disabledPs.pkg);
16047        if (!ret) {
16048            return false;
16049        }
16050
16051        // writer
16052        synchronized (mPackages) {
16053            // Reinstate the old system package
16054            enableSystemPackageLPw(disabledPs.pkg);
16055            // Remove any native libraries from the upgraded package.
16056            removeNativeBinariesLI(deletedPs);
16057        }
16058
16059        // Install the system package
16060        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16061        int parseFlags = mDefParseFlags
16062                | PackageParser.PARSE_MUST_BE_APK
16063                | PackageParser.PARSE_IS_SYSTEM
16064                | PackageParser.PARSE_IS_SYSTEM_DIR;
16065        if (locationIsPrivileged(disabledPs.codePath)) {
16066            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16067        }
16068
16069        final PackageParser.Package newPkg;
16070        try {
16071            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16072        } catch (PackageManagerException e) {
16073            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16074                    + e.getMessage());
16075            return false;
16076        }
16077        try {
16078            // update shared libraries for the newly re-installed system package
16079            updateSharedLibrariesLPw(newPkg, null);
16080        } catch (PackageManagerException e) {
16081            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16082        }
16083
16084        prepareAppDataAfterInstallLIF(newPkg);
16085
16086        // writer
16087        synchronized (mPackages) {
16088            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16089
16090            // Propagate the permissions state as we do not want to drop on the floor
16091            // runtime permissions. The update permissions method below will take
16092            // care of removing obsolete permissions and grant install permissions.
16093            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16094            updatePermissionsLPw(newPkg.packageName, newPkg,
16095                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16096
16097            if (applyUserRestrictions) {
16098                if (DEBUG_REMOVE) {
16099                    Slog.d(TAG, "Propagating install state across reinstall");
16100                }
16101                for (int userId : allUserHandles) {
16102                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16103                    if (DEBUG_REMOVE) {
16104                        Slog.d(TAG, "    user " + userId + " => " + installed);
16105                    }
16106                    ps.setInstalled(installed, userId);
16107
16108                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16109                }
16110                // Regardless of writeSettings we need to ensure that this restriction
16111                // state propagation is persisted
16112                mSettings.writeAllUsersPackageRestrictionsLPr();
16113            }
16114            // can downgrade to reader here
16115            if (writeSettings) {
16116                mSettings.writeLPr();
16117            }
16118        }
16119        return true;
16120    }
16121
16122    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16123            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16124            PackageRemovedInfo outInfo, boolean writeSettings,
16125            PackageParser.Package replacingPackage) {
16126        synchronized (mPackages) {
16127            if (outInfo != null) {
16128                outInfo.uid = ps.appId;
16129            }
16130
16131            if (outInfo != null && outInfo.removedChildPackages != null) {
16132                final int childCount = (ps.childPackageNames != null)
16133                        ? ps.childPackageNames.size() : 0;
16134                for (int i = 0; i < childCount; i++) {
16135                    String childPackageName = ps.childPackageNames.get(i);
16136                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16137                    if (childPs == null) {
16138                        return false;
16139                    }
16140                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16141                            childPackageName);
16142                    if (childInfo != null) {
16143                        childInfo.uid = childPs.appId;
16144                    }
16145                }
16146            }
16147        }
16148
16149        // Delete package data from internal structures and also remove data if flag is set
16150        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16151
16152        // Delete the child packages data
16153        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16154        for (int i = 0; i < childCount; i++) {
16155            PackageSetting childPs;
16156            synchronized (mPackages) {
16157                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16158            }
16159            if (childPs != null) {
16160                PackageRemovedInfo childOutInfo = (outInfo != null
16161                        && outInfo.removedChildPackages != null)
16162                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16163                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16164                        && (replacingPackage != null
16165                        && !replacingPackage.hasChildPackage(childPs.name))
16166                        ? flags & ~DELETE_KEEP_DATA : flags;
16167                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16168                        deleteFlags, writeSettings);
16169            }
16170        }
16171
16172        // Delete application code and resources only for parent packages
16173        if (ps.parentPackageName == null) {
16174            if (deleteCodeAndResources && (outInfo != null)) {
16175                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16176                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16177                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16178            }
16179        }
16180
16181        return true;
16182    }
16183
16184    @Override
16185    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16186            int userId) {
16187        mContext.enforceCallingOrSelfPermission(
16188                android.Manifest.permission.DELETE_PACKAGES, null);
16189        synchronized (mPackages) {
16190            PackageSetting ps = mSettings.mPackages.get(packageName);
16191            if (ps == null) {
16192                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16193                return false;
16194            }
16195            if (!ps.getInstalled(userId)) {
16196                // Can't block uninstall for an app that is not installed or enabled.
16197                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16198                return false;
16199            }
16200            ps.setBlockUninstall(blockUninstall, userId);
16201            mSettings.writePackageRestrictionsLPr(userId);
16202        }
16203        return true;
16204    }
16205
16206    @Override
16207    public boolean getBlockUninstallForUser(String packageName, int userId) {
16208        synchronized (mPackages) {
16209            PackageSetting ps = mSettings.mPackages.get(packageName);
16210            if (ps == null) {
16211                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16212                return false;
16213            }
16214            return ps.getBlockUninstall(userId);
16215        }
16216    }
16217
16218    @Override
16219    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16220        int callingUid = Binder.getCallingUid();
16221        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16222            throw new SecurityException(
16223                    "setRequiredForSystemUser can only be run by the system or root");
16224        }
16225        synchronized (mPackages) {
16226            PackageSetting ps = mSettings.mPackages.get(packageName);
16227            if (ps == null) {
16228                Log.w(TAG, "Package doesn't exist: " + packageName);
16229                return false;
16230            }
16231            if (systemUserApp) {
16232                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16233            } else {
16234                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16235            }
16236            mSettings.writeLPr();
16237        }
16238        return true;
16239    }
16240
16241    /*
16242     * This method handles package deletion in general
16243     */
16244    private boolean deletePackageLIF(String packageName, UserHandle user,
16245            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16246            PackageRemovedInfo outInfo, boolean writeSettings,
16247            PackageParser.Package replacingPackage) {
16248        if (packageName == null) {
16249            Slog.w(TAG, "Attempt to delete null packageName.");
16250            return false;
16251        }
16252
16253        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16254
16255        PackageSetting ps;
16256
16257        synchronized (mPackages) {
16258            ps = mSettings.mPackages.get(packageName);
16259            if (ps == null) {
16260                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16261                return false;
16262            }
16263
16264            if (ps.parentPackageName != null && (!isSystemApp(ps)
16265                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16266                if (DEBUG_REMOVE) {
16267                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16268                            + ((user == null) ? UserHandle.USER_ALL : user));
16269                }
16270                final int removedUserId = (user != null) ? user.getIdentifier()
16271                        : UserHandle.USER_ALL;
16272                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16273                    return false;
16274                }
16275                markPackageUninstalledForUserLPw(ps, user);
16276                scheduleWritePackageRestrictionsLocked(user);
16277                return true;
16278            }
16279        }
16280
16281        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16282                && user.getIdentifier() != UserHandle.USER_ALL)) {
16283            // The caller is asking that the package only be deleted for a single
16284            // user.  To do this, we just mark its uninstalled state and delete
16285            // its data. If this is a system app, we only allow this to happen if
16286            // they have set the special DELETE_SYSTEM_APP which requests different
16287            // semantics than normal for uninstalling system apps.
16288            markPackageUninstalledForUserLPw(ps, user);
16289
16290            if (!isSystemApp(ps)) {
16291                // Do not uninstall the APK if an app should be cached
16292                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16293                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16294                    // Other user still have this package installed, so all
16295                    // we need to do is clear this user's data and save that
16296                    // it is uninstalled.
16297                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16298                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16299                        return false;
16300                    }
16301                    scheduleWritePackageRestrictionsLocked(user);
16302                    return true;
16303                } else {
16304                    // We need to set it back to 'installed' so the uninstall
16305                    // broadcasts will be sent correctly.
16306                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16307                    ps.setInstalled(true, user.getIdentifier());
16308                }
16309            } else {
16310                // This is a system app, so we assume that the
16311                // other users still have this package installed, so all
16312                // we need to do is clear this user's data and save that
16313                // it is uninstalled.
16314                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16315                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16316                    return false;
16317                }
16318                scheduleWritePackageRestrictionsLocked(user);
16319                return true;
16320            }
16321        }
16322
16323        // If we are deleting a composite package for all users, keep track
16324        // of result for each child.
16325        if (ps.childPackageNames != null && outInfo != null) {
16326            synchronized (mPackages) {
16327                final int childCount = ps.childPackageNames.size();
16328                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16329                for (int i = 0; i < childCount; i++) {
16330                    String childPackageName = ps.childPackageNames.get(i);
16331                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16332                    childInfo.removedPackage = childPackageName;
16333                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16334                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16335                    if (childPs != null) {
16336                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16337                    }
16338                }
16339            }
16340        }
16341
16342        boolean ret = false;
16343        if (isSystemApp(ps)) {
16344            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16345            // When an updated system application is deleted we delete the existing resources
16346            // as well and fall back to existing code in system partition
16347            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16348        } else {
16349            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16350            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16351                    outInfo, writeSettings, replacingPackage);
16352        }
16353
16354        // Take a note whether we deleted the package for all users
16355        if (outInfo != null) {
16356            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16357            if (outInfo.removedChildPackages != null) {
16358                synchronized (mPackages) {
16359                    final int childCount = outInfo.removedChildPackages.size();
16360                    for (int i = 0; i < childCount; i++) {
16361                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16362                        if (childInfo != null) {
16363                            childInfo.removedForAllUsers = mPackages.get(
16364                                    childInfo.removedPackage) == null;
16365                        }
16366                    }
16367                }
16368            }
16369            // If we uninstalled an update to a system app there may be some
16370            // child packages that appeared as they are declared in the system
16371            // app but were not declared in the update.
16372            if (isSystemApp(ps)) {
16373                synchronized (mPackages) {
16374                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16375                    final int childCount = (updatedPs.childPackageNames != null)
16376                            ? updatedPs.childPackageNames.size() : 0;
16377                    for (int i = 0; i < childCount; i++) {
16378                        String childPackageName = updatedPs.childPackageNames.get(i);
16379                        if (outInfo.removedChildPackages == null
16380                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16381                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16382                            if (childPs == null) {
16383                                continue;
16384                            }
16385                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16386                            installRes.name = childPackageName;
16387                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16388                            installRes.pkg = mPackages.get(childPackageName);
16389                            installRes.uid = childPs.pkg.applicationInfo.uid;
16390                            if (outInfo.appearedChildPackages == null) {
16391                                outInfo.appearedChildPackages = new ArrayMap<>();
16392                            }
16393                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16394                        }
16395                    }
16396                }
16397            }
16398        }
16399
16400        return ret;
16401    }
16402
16403    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16404        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16405                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16406        for (int nextUserId : userIds) {
16407            if (DEBUG_REMOVE) {
16408                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16409            }
16410            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16411                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16412                    false /*hidden*/, false /*suspended*/, null, null, null,
16413                    false /*blockUninstall*/,
16414                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16415        }
16416    }
16417
16418    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16419            PackageRemovedInfo outInfo) {
16420        final PackageParser.Package pkg;
16421        synchronized (mPackages) {
16422            pkg = mPackages.get(ps.name);
16423        }
16424
16425        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16426                : new int[] {userId};
16427        for (int nextUserId : userIds) {
16428            if (DEBUG_REMOVE) {
16429                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16430                        + nextUserId);
16431            }
16432
16433            destroyAppDataLIF(pkg, userId,
16434                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16435            destroyAppProfilesLIF(pkg, userId);
16436            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16437            schedulePackageCleaning(ps.name, nextUserId, false);
16438            synchronized (mPackages) {
16439                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16440                    scheduleWritePackageRestrictionsLocked(nextUserId);
16441                }
16442                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16443            }
16444        }
16445
16446        if (outInfo != null) {
16447            outInfo.removedPackage = ps.name;
16448            outInfo.removedAppId = ps.appId;
16449            outInfo.removedUsers = userIds;
16450        }
16451
16452        return true;
16453    }
16454
16455    private final class ClearStorageConnection implements ServiceConnection {
16456        IMediaContainerService mContainerService;
16457
16458        @Override
16459        public void onServiceConnected(ComponentName name, IBinder service) {
16460            synchronized (this) {
16461                mContainerService = IMediaContainerService.Stub.asInterface(service);
16462                notifyAll();
16463            }
16464        }
16465
16466        @Override
16467        public void onServiceDisconnected(ComponentName name) {
16468        }
16469    }
16470
16471    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16472        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16473
16474        final boolean mounted;
16475        if (Environment.isExternalStorageEmulated()) {
16476            mounted = true;
16477        } else {
16478            final String status = Environment.getExternalStorageState();
16479
16480            mounted = status.equals(Environment.MEDIA_MOUNTED)
16481                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16482        }
16483
16484        if (!mounted) {
16485            return;
16486        }
16487
16488        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16489        int[] users;
16490        if (userId == UserHandle.USER_ALL) {
16491            users = sUserManager.getUserIds();
16492        } else {
16493            users = new int[] { userId };
16494        }
16495        final ClearStorageConnection conn = new ClearStorageConnection();
16496        if (mContext.bindServiceAsUser(
16497                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16498            try {
16499                for (int curUser : users) {
16500                    long timeout = SystemClock.uptimeMillis() + 5000;
16501                    synchronized (conn) {
16502                        long now;
16503                        while (conn.mContainerService == null &&
16504                                (now = SystemClock.uptimeMillis()) < timeout) {
16505                            try {
16506                                conn.wait(timeout - now);
16507                            } catch (InterruptedException e) {
16508                            }
16509                        }
16510                    }
16511                    if (conn.mContainerService == null) {
16512                        return;
16513                    }
16514
16515                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16516                    clearDirectory(conn.mContainerService,
16517                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16518                    if (allData) {
16519                        clearDirectory(conn.mContainerService,
16520                                userEnv.buildExternalStorageAppDataDirs(packageName));
16521                        clearDirectory(conn.mContainerService,
16522                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16523                    }
16524                }
16525            } finally {
16526                mContext.unbindService(conn);
16527            }
16528        }
16529    }
16530
16531    @Override
16532    public void clearApplicationProfileData(String packageName) {
16533        enforceSystemOrRoot("Only the system can clear all profile data");
16534
16535        final PackageParser.Package pkg;
16536        synchronized (mPackages) {
16537            pkg = mPackages.get(packageName);
16538        }
16539
16540        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16541            synchronized (mInstallLock) {
16542                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16543            }
16544        }
16545    }
16546
16547    @Override
16548    public void clearApplicationUserData(final String packageName,
16549            final IPackageDataObserver observer, final int userId) {
16550        mContext.enforceCallingOrSelfPermission(
16551                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16552
16553        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16554                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16555
16556        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16557            throw new SecurityException("Cannot clear data for a protected package: "
16558                    + packageName);
16559        }
16560        // Queue up an async operation since the package deletion may take a little while.
16561        mHandler.post(new Runnable() {
16562            public void run() {
16563                mHandler.removeCallbacks(this);
16564                final boolean succeeded;
16565                try (PackageFreezer freezer = freezePackage(packageName,
16566                        "clearApplicationUserData")) {
16567                    synchronized (mInstallLock) {
16568                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16569                    }
16570                    clearExternalStorageDataSync(packageName, userId, true);
16571                }
16572                if (succeeded) {
16573                    // invoke DeviceStorageMonitor's update method to clear any notifications
16574                    DeviceStorageMonitorInternal dsm = LocalServices
16575                            .getService(DeviceStorageMonitorInternal.class);
16576                    if (dsm != null) {
16577                        dsm.checkMemory();
16578                    }
16579                }
16580                if(observer != null) {
16581                    try {
16582                        observer.onRemoveCompleted(packageName, succeeded);
16583                    } catch (RemoteException e) {
16584                        Log.i(TAG, "Observer no longer exists.");
16585                    }
16586                } //end if observer
16587            } //end run
16588        });
16589    }
16590
16591    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16592        if (packageName == null) {
16593            Slog.w(TAG, "Attempt to delete null packageName.");
16594            return false;
16595        }
16596
16597        // Try finding details about the requested package
16598        PackageParser.Package pkg;
16599        synchronized (mPackages) {
16600            pkg = mPackages.get(packageName);
16601            if (pkg == null) {
16602                final PackageSetting ps = mSettings.mPackages.get(packageName);
16603                if (ps != null) {
16604                    pkg = ps.pkg;
16605                }
16606            }
16607
16608            if (pkg == null) {
16609                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16610                return false;
16611            }
16612
16613            PackageSetting ps = (PackageSetting) pkg.mExtras;
16614            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16615        }
16616
16617        clearAppDataLIF(pkg, userId,
16618                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16619
16620        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16621        removeKeystoreDataIfNeeded(userId, appId);
16622
16623        UserManagerInternal umInternal = getUserManagerInternal();
16624        final int flags;
16625        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16626            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16627        } else if (umInternal.isUserRunning(userId)) {
16628            flags = StorageManager.FLAG_STORAGE_DE;
16629        } else {
16630            flags = 0;
16631        }
16632        prepareAppDataContentsLIF(pkg, userId, flags);
16633
16634        return true;
16635    }
16636
16637    /**
16638     * Reverts user permission state changes (permissions and flags) in
16639     * all packages for a given user.
16640     *
16641     * @param userId The device user for which to do a reset.
16642     */
16643    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16644        final int packageCount = mPackages.size();
16645        for (int i = 0; i < packageCount; i++) {
16646            PackageParser.Package pkg = mPackages.valueAt(i);
16647            PackageSetting ps = (PackageSetting) pkg.mExtras;
16648            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16649        }
16650    }
16651
16652    private void resetNetworkPolicies(int userId) {
16653        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16654    }
16655
16656    /**
16657     * Reverts user permission state changes (permissions and flags).
16658     *
16659     * @param ps The package for which to reset.
16660     * @param userId The device user for which to do a reset.
16661     */
16662    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16663            final PackageSetting ps, final int userId) {
16664        if (ps.pkg == null) {
16665            return;
16666        }
16667
16668        // These are flags that can change base on user actions.
16669        final int userSettableMask = FLAG_PERMISSION_USER_SET
16670                | FLAG_PERMISSION_USER_FIXED
16671                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16672                | FLAG_PERMISSION_REVIEW_REQUIRED;
16673
16674        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16675                | FLAG_PERMISSION_POLICY_FIXED;
16676
16677        boolean writeInstallPermissions = false;
16678        boolean writeRuntimePermissions = false;
16679
16680        final int permissionCount = ps.pkg.requestedPermissions.size();
16681        for (int i = 0; i < permissionCount; i++) {
16682            String permission = ps.pkg.requestedPermissions.get(i);
16683
16684            BasePermission bp = mSettings.mPermissions.get(permission);
16685            if (bp == null) {
16686                continue;
16687            }
16688
16689            // If shared user we just reset the state to which only this app contributed.
16690            if (ps.sharedUser != null) {
16691                boolean used = false;
16692                final int packageCount = ps.sharedUser.packages.size();
16693                for (int j = 0; j < packageCount; j++) {
16694                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16695                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16696                            && pkg.pkg.requestedPermissions.contains(permission)) {
16697                        used = true;
16698                        break;
16699                    }
16700                }
16701                if (used) {
16702                    continue;
16703                }
16704            }
16705
16706            PermissionsState permissionsState = ps.getPermissionsState();
16707
16708            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16709
16710            // Always clear the user settable flags.
16711            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16712                    bp.name) != null;
16713            // If permission review is enabled and this is a legacy app, mark the
16714            // permission as requiring a review as this is the initial state.
16715            int flags = 0;
16716            if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
16717                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16718                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16719            }
16720            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16721                if (hasInstallState) {
16722                    writeInstallPermissions = true;
16723                } else {
16724                    writeRuntimePermissions = true;
16725                }
16726            }
16727
16728            // Below is only runtime permission handling.
16729            if (!bp.isRuntime()) {
16730                continue;
16731            }
16732
16733            // Never clobber system or policy.
16734            if ((oldFlags & policyOrSystemFlags) != 0) {
16735                continue;
16736            }
16737
16738            // If this permission was granted by default, make sure it is.
16739            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16740                if (permissionsState.grantRuntimePermission(bp, userId)
16741                        != PERMISSION_OPERATION_FAILURE) {
16742                    writeRuntimePermissions = true;
16743                }
16744            // If permission review is enabled the permissions for a legacy apps
16745            // are represented as constantly granted runtime ones, so don't revoke.
16746            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16747                // Otherwise, reset the permission.
16748                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16749                switch (revokeResult) {
16750                    case PERMISSION_OPERATION_SUCCESS:
16751                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16752                        writeRuntimePermissions = true;
16753                        final int appId = ps.appId;
16754                        mHandler.post(new Runnable() {
16755                            @Override
16756                            public void run() {
16757                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16758                            }
16759                        });
16760                    } break;
16761                }
16762            }
16763        }
16764
16765        // Synchronously write as we are taking permissions away.
16766        if (writeRuntimePermissions) {
16767            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16768        }
16769
16770        // Synchronously write as we are taking permissions away.
16771        if (writeInstallPermissions) {
16772            mSettings.writeLPr();
16773        }
16774    }
16775
16776    /**
16777     * Remove entries from the keystore daemon. Will only remove it if the
16778     * {@code appId} is valid.
16779     */
16780    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16781        if (appId < 0) {
16782            return;
16783        }
16784
16785        final KeyStore keyStore = KeyStore.getInstance();
16786        if (keyStore != null) {
16787            if (userId == UserHandle.USER_ALL) {
16788                for (final int individual : sUserManager.getUserIds()) {
16789                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16790                }
16791            } else {
16792                keyStore.clearUid(UserHandle.getUid(userId, appId));
16793            }
16794        } else {
16795            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16796        }
16797    }
16798
16799    @Override
16800    public void deleteApplicationCacheFiles(final String packageName,
16801            final IPackageDataObserver observer) {
16802        final int userId = UserHandle.getCallingUserId();
16803        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16804    }
16805
16806    @Override
16807    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16808            final IPackageDataObserver observer) {
16809        mContext.enforceCallingOrSelfPermission(
16810                android.Manifest.permission.DELETE_CACHE_FILES, null);
16811        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16812                /* requireFullPermission= */ true, /* checkShell= */ false,
16813                "delete application cache files");
16814
16815        final PackageParser.Package pkg;
16816        synchronized (mPackages) {
16817            pkg = mPackages.get(packageName);
16818        }
16819
16820        // Queue up an async operation since the package deletion may take a little while.
16821        mHandler.post(new Runnable() {
16822            public void run() {
16823                synchronized (mInstallLock) {
16824                    final int flags = StorageManager.FLAG_STORAGE_DE
16825                            | StorageManager.FLAG_STORAGE_CE;
16826                    // We're only clearing cache files, so we don't care if the
16827                    // app is unfrozen and still able to run
16828                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16829                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16830                }
16831                clearExternalStorageDataSync(packageName, userId, false);
16832                if (observer != null) {
16833                    try {
16834                        observer.onRemoveCompleted(packageName, true);
16835                    } catch (RemoteException e) {
16836                        Log.i(TAG, "Observer no longer exists.");
16837                    }
16838                }
16839            }
16840        });
16841    }
16842
16843    @Override
16844    public void getPackageSizeInfo(final String packageName, int userHandle,
16845            final IPackageStatsObserver observer) {
16846        mContext.enforceCallingOrSelfPermission(
16847                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16848        if (packageName == null) {
16849            throw new IllegalArgumentException("Attempt to get size of null packageName");
16850        }
16851
16852        PackageStats stats = new PackageStats(packageName, userHandle);
16853
16854        /*
16855         * Queue up an async operation since the package measurement may take a
16856         * little while.
16857         */
16858        Message msg = mHandler.obtainMessage(INIT_COPY);
16859        msg.obj = new MeasureParams(stats, observer);
16860        mHandler.sendMessage(msg);
16861    }
16862
16863    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16864        final PackageSetting ps;
16865        synchronized (mPackages) {
16866            ps = mSettings.mPackages.get(packageName);
16867            if (ps == null) {
16868                Slog.w(TAG, "Failed to find settings for " + packageName);
16869                return false;
16870            }
16871        }
16872
16873        final String[] packageNames = { packageName };
16874        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
16875        final String[] codePaths = { ps.codePathString };
16876
16877        try {
16878            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
16879                    ps.appId, ceDataInodes, codePaths, stats);
16880
16881            // For now, ignore code size of packages on system partition
16882            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16883                stats.codeSize = 0;
16884            }
16885
16886            // External clients expect these to be tracked separately
16887            stats.dataSize -= stats.cacheSize;
16888
16889        } catch (InstallerException e) {
16890            Slog.w(TAG, String.valueOf(e));
16891            return false;
16892        }
16893
16894        return true;
16895    }
16896
16897    private int getUidTargetSdkVersionLockedLPr(int uid) {
16898        Object obj = mSettings.getUserIdLPr(uid);
16899        if (obj instanceof SharedUserSetting) {
16900            final SharedUserSetting sus = (SharedUserSetting) obj;
16901            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16902            final Iterator<PackageSetting> it = sus.packages.iterator();
16903            while (it.hasNext()) {
16904                final PackageSetting ps = it.next();
16905                if (ps.pkg != null) {
16906                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16907                    if (v < vers) vers = v;
16908                }
16909            }
16910            return vers;
16911        } else if (obj instanceof PackageSetting) {
16912            final PackageSetting ps = (PackageSetting) obj;
16913            if (ps.pkg != null) {
16914                return ps.pkg.applicationInfo.targetSdkVersion;
16915            }
16916        }
16917        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16918    }
16919
16920    @Override
16921    public void addPreferredActivity(IntentFilter filter, int match,
16922            ComponentName[] set, ComponentName activity, int userId) {
16923        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16924                "Adding preferred");
16925    }
16926
16927    private void addPreferredActivityInternal(IntentFilter filter, int match,
16928            ComponentName[] set, ComponentName activity, boolean always, int userId,
16929            String opname) {
16930        // writer
16931        int callingUid = Binder.getCallingUid();
16932        enforceCrossUserPermission(callingUid, userId,
16933                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16934        if (filter.countActions() == 0) {
16935            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16936            return;
16937        }
16938        synchronized (mPackages) {
16939            if (mContext.checkCallingOrSelfPermission(
16940                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16941                    != PackageManager.PERMISSION_GRANTED) {
16942                if (getUidTargetSdkVersionLockedLPr(callingUid)
16943                        < Build.VERSION_CODES.FROYO) {
16944                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16945                            + callingUid);
16946                    return;
16947                }
16948                mContext.enforceCallingOrSelfPermission(
16949                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16950            }
16951
16952            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16953            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16954                    + userId + ":");
16955            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16956            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16957            scheduleWritePackageRestrictionsLocked(userId);
16958            postPreferredActivityChangedBroadcast(userId);
16959        }
16960    }
16961
16962    private void postPreferredActivityChangedBroadcast(int userId) {
16963        mHandler.post(() -> {
16964            final IActivityManager am = ActivityManagerNative.getDefault();
16965            if (am == null) {
16966                return;
16967            }
16968
16969            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
16970            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
16971            try {
16972                am.broadcastIntent(null, intent, null, null,
16973                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
16974                        null, false, false, userId);
16975            } catch (RemoteException e) {
16976            }
16977        });
16978    }
16979
16980    @Override
16981    public void replacePreferredActivity(IntentFilter filter, int match,
16982            ComponentName[] set, ComponentName activity, int userId) {
16983        if (filter.countActions() != 1) {
16984            throw new IllegalArgumentException(
16985                    "replacePreferredActivity expects filter to have only 1 action.");
16986        }
16987        if (filter.countDataAuthorities() != 0
16988                || filter.countDataPaths() != 0
16989                || filter.countDataSchemes() > 1
16990                || filter.countDataTypes() != 0) {
16991            throw new IllegalArgumentException(
16992                    "replacePreferredActivity expects filter to have no data authorities, " +
16993                    "paths, or types; and at most one scheme.");
16994        }
16995
16996        final int callingUid = Binder.getCallingUid();
16997        enforceCrossUserPermission(callingUid, userId,
16998                true /* requireFullPermission */, false /* checkShell */,
16999                "replace preferred activity");
17000        synchronized (mPackages) {
17001            if (mContext.checkCallingOrSelfPermission(
17002                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17003                    != PackageManager.PERMISSION_GRANTED) {
17004                if (getUidTargetSdkVersionLockedLPr(callingUid)
17005                        < Build.VERSION_CODES.FROYO) {
17006                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17007                            + Binder.getCallingUid());
17008                    return;
17009                }
17010                mContext.enforceCallingOrSelfPermission(
17011                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17012            }
17013
17014            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17015            if (pir != null) {
17016                // Get all of the existing entries that exactly match this filter.
17017                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17018                if (existing != null && existing.size() == 1) {
17019                    PreferredActivity cur = existing.get(0);
17020                    if (DEBUG_PREFERRED) {
17021                        Slog.i(TAG, "Checking replace of preferred:");
17022                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17023                        if (!cur.mPref.mAlways) {
17024                            Slog.i(TAG, "  -- CUR; not mAlways!");
17025                        } else {
17026                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
17027                            Slog.i(TAG, "  -- CUR: mSet="
17028                                    + Arrays.toString(cur.mPref.mSetComponents));
17029                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
17030                            Slog.i(TAG, "  -- NEW: mMatch="
17031                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
17032                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
17033                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
17034                        }
17035                    }
17036                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17037                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17038                            && cur.mPref.sameSet(set)) {
17039                        // Setting the preferred activity to what it happens to be already
17040                        if (DEBUG_PREFERRED) {
17041                            Slog.i(TAG, "Replacing with same preferred activity "
17042                                    + cur.mPref.mShortComponent + " for user "
17043                                    + userId + ":");
17044                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17045                        }
17046                        return;
17047                    }
17048                }
17049
17050                if (existing != null) {
17051                    if (DEBUG_PREFERRED) {
17052                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17053                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17054                    }
17055                    for (int i = 0; i < existing.size(); i++) {
17056                        PreferredActivity pa = existing.get(i);
17057                        if (DEBUG_PREFERRED) {
17058                            Slog.i(TAG, "Removing existing preferred activity "
17059                                    + pa.mPref.mComponent + ":");
17060                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17061                        }
17062                        pir.removeFilter(pa);
17063                    }
17064                }
17065            }
17066            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17067                    "Replacing preferred");
17068        }
17069    }
17070
17071    @Override
17072    public void clearPackagePreferredActivities(String packageName) {
17073        final int uid = Binder.getCallingUid();
17074        // writer
17075        synchronized (mPackages) {
17076            PackageParser.Package pkg = mPackages.get(packageName);
17077            if (pkg == null || pkg.applicationInfo.uid != uid) {
17078                if (mContext.checkCallingOrSelfPermission(
17079                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17080                        != PackageManager.PERMISSION_GRANTED) {
17081                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17082                            < Build.VERSION_CODES.FROYO) {
17083                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17084                                + Binder.getCallingUid());
17085                        return;
17086                    }
17087                    mContext.enforceCallingOrSelfPermission(
17088                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17089                }
17090            }
17091
17092            int user = UserHandle.getCallingUserId();
17093            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17094                scheduleWritePackageRestrictionsLocked(user);
17095            }
17096        }
17097    }
17098
17099    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17100    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17101        ArrayList<PreferredActivity> removed = null;
17102        boolean changed = false;
17103        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17104            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17105            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17106            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17107                continue;
17108            }
17109            Iterator<PreferredActivity> it = pir.filterIterator();
17110            while (it.hasNext()) {
17111                PreferredActivity pa = it.next();
17112                // Mark entry for removal only if it matches the package name
17113                // and the entry is of type "always".
17114                if (packageName == null ||
17115                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17116                                && pa.mPref.mAlways)) {
17117                    if (removed == null) {
17118                        removed = new ArrayList<PreferredActivity>();
17119                    }
17120                    removed.add(pa);
17121                }
17122            }
17123            if (removed != null) {
17124                for (int j=0; j<removed.size(); j++) {
17125                    PreferredActivity pa = removed.get(j);
17126                    pir.removeFilter(pa);
17127                }
17128                changed = true;
17129            }
17130        }
17131        if (changed) {
17132            postPreferredActivityChangedBroadcast(userId);
17133        }
17134        return changed;
17135    }
17136
17137    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17138    private void clearIntentFilterVerificationsLPw(int userId) {
17139        final int packageCount = mPackages.size();
17140        for (int i = 0; i < packageCount; i++) {
17141            PackageParser.Package pkg = mPackages.valueAt(i);
17142            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17143        }
17144    }
17145
17146    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17147    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17148        if (userId == UserHandle.USER_ALL) {
17149            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17150                    sUserManager.getUserIds())) {
17151                for (int oneUserId : sUserManager.getUserIds()) {
17152                    scheduleWritePackageRestrictionsLocked(oneUserId);
17153                }
17154            }
17155        } else {
17156            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17157                scheduleWritePackageRestrictionsLocked(userId);
17158            }
17159        }
17160    }
17161
17162    void clearDefaultBrowserIfNeeded(String packageName) {
17163        for (int oneUserId : sUserManager.getUserIds()) {
17164            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17165            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17166            if (packageName.equals(defaultBrowserPackageName)) {
17167                setDefaultBrowserPackageName(null, oneUserId);
17168            }
17169        }
17170    }
17171
17172    @Override
17173    public void resetApplicationPreferences(int userId) {
17174        mContext.enforceCallingOrSelfPermission(
17175                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17176        final long identity = Binder.clearCallingIdentity();
17177        // writer
17178        try {
17179            synchronized (mPackages) {
17180                clearPackagePreferredActivitiesLPw(null, userId);
17181                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17182                // TODO: We have to reset the default SMS and Phone. This requires
17183                // significant refactoring to keep all default apps in the package
17184                // manager (cleaner but more work) or have the services provide
17185                // callbacks to the package manager to request a default app reset.
17186                applyFactoryDefaultBrowserLPw(userId);
17187                clearIntentFilterVerificationsLPw(userId);
17188                primeDomainVerificationsLPw(userId);
17189                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17190                scheduleWritePackageRestrictionsLocked(userId);
17191            }
17192            resetNetworkPolicies(userId);
17193        } finally {
17194            Binder.restoreCallingIdentity(identity);
17195        }
17196    }
17197
17198    @Override
17199    public int getPreferredActivities(List<IntentFilter> outFilters,
17200            List<ComponentName> outActivities, String packageName) {
17201
17202        int num = 0;
17203        final int userId = UserHandle.getCallingUserId();
17204        // reader
17205        synchronized (mPackages) {
17206            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17207            if (pir != null) {
17208                final Iterator<PreferredActivity> it = pir.filterIterator();
17209                while (it.hasNext()) {
17210                    final PreferredActivity pa = it.next();
17211                    if (packageName == null
17212                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17213                                    && pa.mPref.mAlways)) {
17214                        if (outFilters != null) {
17215                            outFilters.add(new IntentFilter(pa));
17216                        }
17217                        if (outActivities != null) {
17218                            outActivities.add(pa.mPref.mComponent);
17219                        }
17220                    }
17221                }
17222            }
17223        }
17224
17225        return num;
17226    }
17227
17228    @Override
17229    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17230            int userId) {
17231        int callingUid = Binder.getCallingUid();
17232        if (callingUid != Process.SYSTEM_UID) {
17233            throw new SecurityException(
17234                    "addPersistentPreferredActivity can only be run by the system");
17235        }
17236        if (filter.countActions() == 0) {
17237            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17238            return;
17239        }
17240        synchronized (mPackages) {
17241            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17242                    ":");
17243            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17244            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17245                    new PersistentPreferredActivity(filter, activity));
17246            scheduleWritePackageRestrictionsLocked(userId);
17247            postPreferredActivityChangedBroadcast(userId);
17248        }
17249    }
17250
17251    @Override
17252    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17253        int callingUid = Binder.getCallingUid();
17254        if (callingUid != Process.SYSTEM_UID) {
17255            throw new SecurityException(
17256                    "clearPackagePersistentPreferredActivities can only be run by the system");
17257        }
17258        ArrayList<PersistentPreferredActivity> removed = null;
17259        boolean changed = false;
17260        synchronized (mPackages) {
17261            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17262                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17263                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17264                        .valueAt(i);
17265                if (userId != thisUserId) {
17266                    continue;
17267                }
17268                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17269                while (it.hasNext()) {
17270                    PersistentPreferredActivity ppa = it.next();
17271                    // Mark entry for removal only if it matches the package name.
17272                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17273                        if (removed == null) {
17274                            removed = new ArrayList<PersistentPreferredActivity>();
17275                        }
17276                        removed.add(ppa);
17277                    }
17278                }
17279                if (removed != null) {
17280                    for (int j=0; j<removed.size(); j++) {
17281                        PersistentPreferredActivity ppa = removed.get(j);
17282                        ppir.removeFilter(ppa);
17283                    }
17284                    changed = true;
17285                }
17286            }
17287
17288            if (changed) {
17289                scheduleWritePackageRestrictionsLocked(userId);
17290                postPreferredActivityChangedBroadcast(userId);
17291            }
17292        }
17293    }
17294
17295    /**
17296     * Common machinery for picking apart a restored XML blob and passing
17297     * it to a caller-supplied functor to be applied to the running system.
17298     */
17299    private void restoreFromXml(XmlPullParser parser, int userId,
17300            String expectedStartTag, BlobXmlRestorer functor)
17301            throws IOException, XmlPullParserException {
17302        int type;
17303        while ((type = parser.next()) != XmlPullParser.START_TAG
17304                && type != XmlPullParser.END_DOCUMENT) {
17305        }
17306        if (type != XmlPullParser.START_TAG) {
17307            // oops didn't find a start tag?!
17308            if (DEBUG_BACKUP) {
17309                Slog.e(TAG, "Didn't find start tag during restore");
17310            }
17311            return;
17312        }
17313Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17314        // this is supposed to be TAG_PREFERRED_BACKUP
17315        if (!expectedStartTag.equals(parser.getName())) {
17316            if (DEBUG_BACKUP) {
17317                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17318            }
17319            return;
17320        }
17321
17322        // skip interfering stuff, then we're aligned with the backing implementation
17323        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17324Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17325        functor.apply(parser, userId);
17326    }
17327
17328    private interface BlobXmlRestorer {
17329        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17330    }
17331
17332    /**
17333     * Non-Binder method, support for the backup/restore mechanism: write the
17334     * full set of preferred activities in its canonical XML format.  Returns the
17335     * XML output as a byte array, or null if there is none.
17336     */
17337    @Override
17338    public byte[] getPreferredActivityBackup(int userId) {
17339        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17340            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17341        }
17342
17343        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17344        try {
17345            final XmlSerializer serializer = new FastXmlSerializer();
17346            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17347            serializer.startDocument(null, true);
17348            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17349
17350            synchronized (mPackages) {
17351                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17352            }
17353
17354            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17355            serializer.endDocument();
17356            serializer.flush();
17357        } catch (Exception e) {
17358            if (DEBUG_BACKUP) {
17359                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17360            }
17361            return null;
17362        }
17363
17364        return dataStream.toByteArray();
17365    }
17366
17367    @Override
17368    public void restorePreferredActivities(byte[] backup, int userId) {
17369        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17370            throw new SecurityException("Only the system may call restorePreferredActivities()");
17371        }
17372
17373        try {
17374            final XmlPullParser parser = Xml.newPullParser();
17375            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17376            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17377                    new BlobXmlRestorer() {
17378                        @Override
17379                        public void apply(XmlPullParser parser, int userId)
17380                                throws XmlPullParserException, IOException {
17381                            synchronized (mPackages) {
17382                                mSettings.readPreferredActivitiesLPw(parser, userId);
17383                            }
17384                        }
17385                    } );
17386        } catch (Exception e) {
17387            if (DEBUG_BACKUP) {
17388                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17389            }
17390        }
17391    }
17392
17393    /**
17394     * Non-Binder method, support for the backup/restore mechanism: write the
17395     * default browser (etc) settings in its canonical XML format.  Returns the default
17396     * browser XML representation as a byte array, or null if there is none.
17397     */
17398    @Override
17399    public byte[] getDefaultAppsBackup(int userId) {
17400        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17401            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17402        }
17403
17404        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17405        try {
17406            final XmlSerializer serializer = new FastXmlSerializer();
17407            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17408            serializer.startDocument(null, true);
17409            serializer.startTag(null, TAG_DEFAULT_APPS);
17410
17411            synchronized (mPackages) {
17412                mSettings.writeDefaultAppsLPr(serializer, userId);
17413            }
17414
17415            serializer.endTag(null, TAG_DEFAULT_APPS);
17416            serializer.endDocument();
17417            serializer.flush();
17418        } catch (Exception e) {
17419            if (DEBUG_BACKUP) {
17420                Slog.e(TAG, "Unable to write default apps for backup", e);
17421            }
17422            return null;
17423        }
17424
17425        return dataStream.toByteArray();
17426    }
17427
17428    @Override
17429    public void restoreDefaultApps(byte[] backup, int userId) {
17430        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17431            throw new SecurityException("Only the system may call restoreDefaultApps()");
17432        }
17433
17434        try {
17435            final XmlPullParser parser = Xml.newPullParser();
17436            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17437            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17438                    new BlobXmlRestorer() {
17439                        @Override
17440                        public void apply(XmlPullParser parser, int userId)
17441                                throws XmlPullParserException, IOException {
17442                            synchronized (mPackages) {
17443                                mSettings.readDefaultAppsLPw(parser, userId);
17444                            }
17445                        }
17446                    } );
17447        } catch (Exception e) {
17448            if (DEBUG_BACKUP) {
17449                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17450            }
17451        }
17452    }
17453
17454    @Override
17455    public byte[] getIntentFilterVerificationBackup(int userId) {
17456        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17457            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17458        }
17459
17460        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17461        try {
17462            final XmlSerializer serializer = new FastXmlSerializer();
17463            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17464            serializer.startDocument(null, true);
17465            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17466
17467            synchronized (mPackages) {
17468                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17469            }
17470
17471            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17472            serializer.endDocument();
17473            serializer.flush();
17474        } catch (Exception e) {
17475            if (DEBUG_BACKUP) {
17476                Slog.e(TAG, "Unable to write default apps for backup", e);
17477            }
17478            return null;
17479        }
17480
17481        return dataStream.toByteArray();
17482    }
17483
17484    @Override
17485    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17486        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17487            throw new SecurityException("Only the system may call restorePreferredActivities()");
17488        }
17489
17490        try {
17491            final XmlPullParser parser = Xml.newPullParser();
17492            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17493            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17494                    new BlobXmlRestorer() {
17495                        @Override
17496                        public void apply(XmlPullParser parser, int userId)
17497                                throws XmlPullParserException, IOException {
17498                            synchronized (mPackages) {
17499                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17500                                mSettings.writeLPr();
17501                            }
17502                        }
17503                    } );
17504        } catch (Exception e) {
17505            if (DEBUG_BACKUP) {
17506                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17507            }
17508        }
17509    }
17510
17511    @Override
17512    public byte[] getPermissionGrantBackup(int userId) {
17513        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17514            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17515        }
17516
17517        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17518        try {
17519            final XmlSerializer serializer = new FastXmlSerializer();
17520            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17521            serializer.startDocument(null, true);
17522            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17523
17524            synchronized (mPackages) {
17525                serializeRuntimePermissionGrantsLPr(serializer, userId);
17526            }
17527
17528            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17529            serializer.endDocument();
17530            serializer.flush();
17531        } catch (Exception e) {
17532            if (DEBUG_BACKUP) {
17533                Slog.e(TAG, "Unable to write default apps for backup", e);
17534            }
17535            return null;
17536        }
17537
17538        return dataStream.toByteArray();
17539    }
17540
17541    @Override
17542    public void restorePermissionGrants(byte[] backup, int userId) {
17543        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17544            throw new SecurityException("Only the system may call restorePermissionGrants()");
17545        }
17546
17547        try {
17548            final XmlPullParser parser = Xml.newPullParser();
17549            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17550            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17551                    new BlobXmlRestorer() {
17552                        @Override
17553                        public void apply(XmlPullParser parser, int userId)
17554                                throws XmlPullParserException, IOException {
17555                            synchronized (mPackages) {
17556                                processRestoredPermissionGrantsLPr(parser, userId);
17557                            }
17558                        }
17559                    } );
17560        } catch (Exception e) {
17561            if (DEBUG_BACKUP) {
17562                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17563            }
17564        }
17565    }
17566
17567    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17568            throws IOException {
17569        serializer.startTag(null, TAG_ALL_GRANTS);
17570
17571        final int N = mSettings.mPackages.size();
17572        for (int i = 0; i < N; i++) {
17573            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17574            boolean pkgGrantsKnown = false;
17575
17576            PermissionsState packagePerms = ps.getPermissionsState();
17577
17578            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17579                final int grantFlags = state.getFlags();
17580                // only look at grants that are not system/policy fixed
17581                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17582                    final boolean isGranted = state.isGranted();
17583                    // And only back up the user-twiddled state bits
17584                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17585                        final String packageName = mSettings.mPackages.keyAt(i);
17586                        if (!pkgGrantsKnown) {
17587                            serializer.startTag(null, TAG_GRANT);
17588                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17589                            pkgGrantsKnown = true;
17590                        }
17591
17592                        final boolean userSet =
17593                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17594                        final boolean userFixed =
17595                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17596                        final boolean revoke =
17597                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17598
17599                        serializer.startTag(null, TAG_PERMISSION);
17600                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17601                        if (isGranted) {
17602                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17603                        }
17604                        if (userSet) {
17605                            serializer.attribute(null, ATTR_USER_SET, "true");
17606                        }
17607                        if (userFixed) {
17608                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17609                        }
17610                        if (revoke) {
17611                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17612                        }
17613                        serializer.endTag(null, TAG_PERMISSION);
17614                    }
17615                }
17616            }
17617
17618            if (pkgGrantsKnown) {
17619                serializer.endTag(null, TAG_GRANT);
17620            }
17621        }
17622
17623        serializer.endTag(null, TAG_ALL_GRANTS);
17624    }
17625
17626    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17627            throws XmlPullParserException, IOException {
17628        String pkgName = null;
17629        int outerDepth = parser.getDepth();
17630        int type;
17631        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17632                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17633            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17634                continue;
17635            }
17636
17637            final String tagName = parser.getName();
17638            if (tagName.equals(TAG_GRANT)) {
17639                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17640                if (DEBUG_BACKUP) {
17641                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17642                }
17643            } else if (tagName.equals(TAG_PERMISSION)) {
17644
17645                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17646                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17647
17648                int newFlagSet = 0;
17649                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17650                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17651                }
17652                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17653                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17654                }
17655                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17656                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17657                }
17658                if (DEBUG_BACKUP) {
17659                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17660                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17661                }
17662                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17663                if (ps != null) {
17664                    // Already installed so we apply the grant immediately
17665                    if (DEBUG_BACKUP) {
17666                        Slog.v(TAG, "        + already installed; applying");
17667                    }
17668                    PermissionsState perms = ps.getPermissionsState();
17669                    BasePermission bp = mSettings.mPermissions.get(permName);
17670                    if (bp != null) {
17671                        if (isGranted) {
17672                            perms.grantRuntimePermission(bp, userId);
17673                        }
17674                        if (newFlagSet != 0) {
17675                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17676                        }
17677                    }
17678                } else {
17679                    // Need to wait for post-restore install to apply the grant
17680                    if (DEBUG_BACKUP) {
17681                        Slog.v(TAG, "        - not yet installed; saving for later");
17682                    }
17683                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17684                            isGranted, newFlagSet, userId);
17685                }
17686            } else {
17687                PackageManagerService.reportSettingsProblem(Log.WARN,
17688                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17689                XmlUtils.skipCurrentTag(parser);
17690            }
17691        }
17692
17693        scheduleWriteSettingsLocked();
17694        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17695    }
17696
17697    @Override
17698    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17699            int sourceUserId, int targetUserId, int flags) {
17700        mContext.enforceCallingOrSelfPermission(
17701                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17702        int callingUid = Binder.getCallingUid();
17703        enforceOwnerRights(ownerPackage, callingUid);
17704        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17705        if (intentFilter.countActions() == 0) {
17706            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17707            return;
17708        }
17709        synchronized (mPackages) {
17710            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17711                    ownerPackage, targetUserId, flags);
17712            CrossProfileIntentResolver resolver =
17713                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17714            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17715            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17716            if (existing != null) {
17717                int size = existing.size();
17718                for (int i = 0; i < size; i++) {
17719                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17720                        return;
17721                    }
17722                }
17723            }
17724            resolver.addFilter(newFilter);
17725            scheduleWritePackageRestrictionsLocked(sourceUserId);
17726        }
17727    }
17728
17729    @Override
17730    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17731        mContext.enforceCallingOrSelfPermission(
17732                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17733        int callingUid = Binder.getCallingUid();
17734        enforceOwnerRights(ownerPackage, callingUid);
17735        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17736        synchronized (mPackages) {
17737            CrossProfileIntentResolver resolver =
17738                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17739            ArraySet<CrossProfileIntentFilter> set =
17740                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17741            for (CrossProfileIntentFilter filter : set) {
17742                if (filter.getOwnerPackage().equals(ownerPackage)) {
17743                    resolver.removeFilter(filter);
17744                }
17745            }
17746            scheduleWritePackageRestrictionsLocked(sourceUserId);
17747        }
17748    }
17749
17750    // Enforcing that callingUid is owning pkg on userId
17751    private void enforceOwnerRights(String pkg, int callingUid) {
17752        // The system owns everything.
17753        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17754            return;
17755        }
17756        int callingUserId = UserHandle.getUserId(callingUid);
17757        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17758        if (pi == null) {
17759            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17760                    + callingUserId);
17761        }
17762        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17763            throw new SecurityException("Calling uid " + callingUid
17764                    + " does not own package " + pkg);
17765        }
17766    }
17767
17768    @Override
17769    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17770        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17771    }
17772
17773    private Intent getHomeIntent() {
17774        Intent intent = new Intent(Intent.ACTION_MAIN);
17775        intent.addCategory(Intent.CATEGORY_HOME);
17776        intent.addCategory(Intent.CATEGORY_DEFAULT);
17777        return intent;
17778    }
17779
17780    private IntentFilter getHomeFilter() {
17781        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17782        filter.addCategory(Intent.CATEGORY_HOME);
17783        filter.addCategory(Intent.CATEGORY_DEFAULT);
17784        return filter;
17785    }
17786
17787    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17788            int userId) {
17789        Intent intent  = getHomeIntent();
17790        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17791                PackageManager.GET_META_DATA, userId);
17792        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17793                true, false, false, userId);
17794
17795        allHomeCandidates.clear();
17796        if (list != null) {
17797            for (ResolveInfo ri : list) {
17798                allHomeCandidates.add(ri);
17799            }
17800        }
17801        return (preferred == null || preferred.activityInfo == null)
17802                ? null
17803                : new ComponentName(preferred.activityInfo.packageName,
17804                        preferred.activityInfo.name);
17805    }
17806
17807    @Override
17808    public void setHomeActivity(ComponentName comp, int userId) {
17809        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17810        getHomeActivitiesAsUser(homeActivities, userId);
17811
17812        boolean found = false;
17813
17814        final int size = homeActivities.size();
17815        final ComponentName[] set = new ComponentName[size];
17816        for (int i = 0; i < size; i++) {
17817            final ResolveInfo candidate = homeActivities.get(i);
17818            final ActivityInfo info = candidate.activityInfo;
17819            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17820            set[i] = activityName;
17821            if (!found && activityName.equals(comp)) {
17822                found = true;
17823            }
17824        }
17825        if (!found) {
17826            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17827                    + userId);
17828        }
17829        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17830                set, comp, userId);
17831    }
17832
17833    private @Nullable String getSetupWizardPackageName() {
17834        final Intent intent = new Intent(Intent.ACTION_MAIN);
17835        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17836
17837        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17838                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17839                        | MATCH_DISABLED_COMPONENTS,
17840                UserHandle.myUserId());
17841        if (matches.size() == 1) {
17842            return matches.get(0).getComponentInfo().packageName;
17843        } else {
17844            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17845                    + ": matches=" + matches);
17846            return null;
17847        }
17848    }
17849
17850    private @Nullable String getStorageManagerPackageName() {
17851        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
17852
17853        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17854                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17855                        | MATCH_DISABLED_COMPONENTS,
17856                UserHandle.myUserId());
17857        if (matches.size() == 1) {
17858            return matches.get(0).getComponentInfo().packageName;
17859        } else {
17860            Slog.e(TAG, "There should probably be exactly one storage manager; found "
17861                    + matches.size() + ": matches=" + matches);
17862            return null;
17863        }
17864    }
17865
17866    @Override
17867    public void setApplicationEnabledSetting(String appPackageName,
17868            int newState, int flags, int userId, String callingPackage) {
17869        if (!sUserManager.exists(userId)) return;
17870        if (callingPackage == null) {
17871            callingPackage = Integer.toString(Binder.getCallingUid());
17872        }
17873        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17874    }
17875
17876    @Override
17877    public void setComponentEnabledSetting(ComponentName componentName,
17878            int newState, int flags, int userId) {
17879        if (!sUserManager.exists(userId)) return;
17880        setEnabledSetting(componentName.getPackageName(),
17881                componentName.getClassName(), newState, flags, userId, null);
17882    }
17883
17884    private void setEnabledSetting(final String packageName, String className, int newState,
17885            final int flags, int userId, String callingPackage) {
17886        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17887              || newState == COMPONENT_ENABLED_STATE_ENABLED
17888              || newState == COMPONENT_ENABLED_STATE_DISABLED
17889              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17890              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17891            throw new IllegalArgumentException("Invalid new component state: "
17892                    + newState);
17893        }
17894        PackageSetting pkgSetting;
17895        final int uid = Binder.getCallingUid();
17896        final int permission;
17897        if (uid == Process.SYSTEM_UID) {
17898            permission = PackageManager.PERMISSION_GRANTED;
17899        } else {
17900            permission = mContext.checkCallingOrSelfPermission(
17901                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17902        }
17903        enforceCrossUserPermission(uid, userId,
17904                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17905        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17906        boolean sendNow = false;
17907        boolean isApp = (className == null);
17908        String componentName = isApp ? packageName : className;
17909        int packageUid = -1;
17910        ArrayList<String> components;
17911
17912        // writer
17913        synchronized (mPackages) {
17914            pkgSetting = mSettings.mPackages.get(packageName);
17915            if (pkgSetting == null) {
17916                if (className == null) {
17917                    throw new IllegalArgumentException("Unknown package: " + packageName);
17918                }
17919                throw new IllegalArgumentException(
17920                        "Unknown component: " + packageName + "/" + className);
17921            }
17922        }
17923
17924        // Limit who can change which apps
17925        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17926            // Don't allow apps that don't have permission to modify other apps
17927            if (!allowedByPermission) {
17928                throw new SecurityException(
17929                        "Permission Denial: attempt to change component state from pid="
17930                        + Binder.getCallingPid()
17931                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17932            }
17933            // Don't allow changing protected packages.
17934            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17935                throw new SecurityException("Cannot disable a protected package: " + packageName);
17936            }
17937        }
17938
17939        synchronized (mPackages) {
17940            if (uid == Process.SHELL_UID) {
17941                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17942                int oldState = pkgSetting.getEnabled(userId);
17943                if (className == null
17944                    &&
17945                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17946                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17947                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17948                    &&
17949                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17950                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17951                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17952                    // ok
17953                } else {
17954                    throw new SecurityException(
17955                            "Shell cannot change component state for " + packageName + "/"
17956                            + className + " to " + newState);
17957                }
17958            }
17959            if (className == null) {
17960                // We're dealing with an application/package level state change
17961                if (pkgSetting.getEnabled(userId) == newState) {
17962                    // Nothing to do
17963                    return;
17964                }
17965                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17966                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17967                    // Don't care about who enables an app.
17968                    callingPackage = null;
17969                }
17970                pkgSetting.setEnabled(newState, userId, callingPackage);
17971                // pkgSetting.pkg.mSetEnabled = newState;
17972            } else {
17973                // We're dealing with a component level state change
17974                // First, verify that this is a valid class name.
17975                PackageParser.Package pkg = pkgSetting.pkg;
17976                if (pkg == null || !pkg.hasComponentClassName(className)) {
17977                    if (pkg != null &&
17978                            pkg.applicationInfo.targetSdkVersion >=
17979                                    Build.VERSION_CODES.JELLY_BEAN) {
17980                        throw new IllegalArgumentException("Component class " + className
17981                                + " does not exist in " + packageName);
17982                    } else {
17983                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17984                                + className + " does not exist in " + packageName);
17985                    }
17986                }
17987                switch (newState) {
17988                case COMPONENT_ENABLED_STATE_ENABLED:
17989                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17990                        return;
17991                    }
17992                    break;
17993                case COMPONENT_ENABLED_STATE_DISABLED:
17994                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17995                        return;
17996                    }
17997                    break;
17998                case COMPONENT_ENABLED_STATE_DEFAULT:
17999                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
18000                        return;
18001                    }
18002                    break;
18003                default:
18004                    Slog.e(TAG, "Invalid new component state: " + newState);
18005                    return;
18006                }
18007            }
18008            scheduleWritePackageRestrictionsLocked(userId);
18009            components = mPendingBroadcasts.get(userId, packageName);
18010            final boolean newPackage = components == null;
18011            if (newPackage) {
18012                components = new ArrayList<String>();
18013            }
18014            if (!components.contains(componentName)) {
18015                components.add(componentName);
18016            }
18017            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18018                sendNow = true;
18019                // Purge entry from pending broadcast list if another one exists already
18020                // since we are sending one right away.
18021                mPendingBroadcasts.remove(userId, packageName);
18022            } else {
18023                if (newPackage) {
18024                    mPendingBroadcasts.put(userId, packageName, components);
18025                }
18026                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18027                    // Schedule a message
18028                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18029                }
18030            }
18031        }
18032
18033        long callingId = Binder.clearCallingIdentity();
18034        try {
18035            if (sendNow) {
18036                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18037                sendPackageChangedBroadcast(packageName,
18038                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18039            }
18040        } finally {
18041            Binder.restoreCallingIdentity(callingId);
18042        }
18043    }
18044
18045    @Override
18046    public void flushPackageRestrictionsAsUser(int userId) {
18047        if (!sUserManager.exists(userId)) {
18048            return;
18049        }
18050        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18051                false /* checkShell */, "flushPackageRestrictions");
18052        synchronized (mPackages) {
18053            mSettings.writePackageRestrictionsLPr(userId);
18054            mDirtyUsers.remove(userId);
18055            if (mDirtyUsers.isEmpty()) {
18056                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18057            }
18058        }
18059    }
18060
18061    private void sendPackageChangedBroadcast(String packageName,
18062            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18063        if (DEBUG_INSTALL)
18064            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18065                    + componentNames);
18066        Bundle extras = new Bundle(4);
18067        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18068        String nameList[] = new String[componentNames.size()];
18069        componentNames.toArray(nameList);
18070        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18071        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18072        extras.putInt(Intent.EXTRA_UID, packageUid);
18073        // If this is not reporting a change of the overall package, then only send it
18074        // to registered receivers.  We don't want to launch a swath of apps for every
18075        // little component state change.
18076        final int flags = !componentNames.contains(packageName)
18077                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18078        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18079                new int[] {UserHandle.getUserId(packageUid)});
18080    }
18081
18082    @Override
18083    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18084        if (!sUserManager.exists(userId)) return;
18085        final int uid = Binder.getCallingUid();
18086        final int permission = mContext.checkCallingOrSelfPermission(
18087                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18088        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18089        enforceCrossUserPermission(uid, userId,
18090                true /* requireFullPermission */, true /* checkShell */, "stop package");
18091        // writer
18092        synchronized (mPackages) {
18093            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18094                    allowedByPermission, uid, userId)) {
18095                scheduleWritePackageRestrictionsLocked(userId);
18096            }
18097        }
18098    }
18099
18100    @Override
18101    public String getInstallerPackageName(String packageName) {
18102        // reader
18103        synchronized (mPackages) {
18104            return mSettings.getInstallerPackageNameLPr(packageName);
18105        }
18106    }
18107
18108    public boolean isOrphaned(String packageName) {
18109        // reader
18110        synchronized (mPackages) {
18111            return mSettings.isOrphaned(packageName);
18112        }
18113    }
18114
18115    @Override
18116    public int getApplicationEnabledSetting(String packageName, int userId) {
18117        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18118        int uid = Binder.getCallingUid();
18119        enforceCrossUserPermission(uid, userId,
18120                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18121        // reader
18122        synchronized (mPackages) {
18123            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18124        }
18125    }
18126
18127    @Override
18128    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18129        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18130        int uid = Binder.getCallingUid();
18131        enforceCrossUserPermission(uid, userId,
18132                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18133        // reader
18134        synchronized (mPackages) {
18135            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18136        }
18137    }
18138
18139    @Override
18140    public void enterSafeMode() {
18141        enforceSystemOrRoot("Only the system can request entering safe mode");
18142
18143        if (!mSystemReady) {
18144            mSafeMode = true;
18145        }
18146    }
18147
18148    @Override
18149    public void systemReady() {
18150        mSystemReady = true;
18151
18152        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18153        // disabled after already being started.
18154        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18155                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18156
18157        // Read the compatibilty setting when the system is ready.
18158        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18159                mContext.getContentResolver(),
18160                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18161        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18162        if (DEBUG_SETTINGS) {
18163            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18164        }
18165
18166        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18167
18168        synchronized (mPackages) {
18169            // Verify that all of the preferred activity components actually
18170            // exist.  It is possible for applications to be updated and at
18171            // that point remove a previously declared activity component that
18172            // had been set as a preferred activity.  We try to clean this up
18173            // the next time we encounter that preferred activity, but it is
18174            // possible for the user flow to never be able to return to that
18175            // situation so here we do a sanity check to make sure we haven't
18176            // left any junk around.
18177            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18178            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18179                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18180                removed.clear();
18181                for (PreferredActivity pa : pir.filterSet()) {
18182                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18183                        removed.add(pa);
18184                    }
18185                }
18186                if (removed.size() > 0) {
18187                    for (int r=0; r<removed.size(); r++) {
18188                        PreferredActivity pa = removed.get(r);
18189                        Slog.w(TAG, "Removing dangling preferred activity: "
18190                                + pa.mPref.mComponent);
18191                        pir.removeFilter(pa);
18192                    }
18193                    mSettings.writePackageRestrictionsLPr(
18194                            mSettings.mPreferredActivities.keyAt(i));
18195                }
18196            }
18197
18198            for (int userId : UserManagerService.getInstance().getUserIds()) {
18199                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18200                    grantPermissionsUserIds = ArrayUtils.appendInt(
18201                            grantPermissionsUserIds, userId);
18202                }
18203            }
18204        }
18205        sUserManager.systemReady();
18206
18207        // If we upgraded grant all default permissions before kicking off.
18208        for (int userId : grantPermissionsUserIds) {
18209            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18210        }
18211
18212        // If we did not grant default permissions, we preload from this the
18213        // default permission exceptions lazily to ensure we don't hit the
18214        // disk on a new user creation.
18215        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18216            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18217        }
18218
18219        // Kick off any messages waiting for system ready
18220        if (mPostSystemReadyMessages != null) {
18221            for (Message msg : mPostSystemReadyMessages) {
18222                msg.sendToTarget();
18223            }
18224            mPostSystemReadyMessages = null;
18225        }
18226
18227        // Watch for external volumes that come and go over time
18228        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18229        storage.registerListener(mStorageListener);
18230
18231        mInstallerService.systemReady();
18232        mPackageDexOptimizer.systemReady();
18233
18234        MountServiceInternal mountServiceInternal = LocalServices.getService(
18235                MountServiceInternal.class);
18236        mountServiceInternal.addExternalStoragePolicy(
18237                new MountServiceInternal.ExternalStorageMountPolicy() {
18238            @Override
18239            public int getMountMode(int uid, String packageName) {
18240                if (Process.isIsolated(uid)) {
18241                    return Zygote.MOUNT_EXTERNAL_NONE;
18242                }
18243                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18244                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18245                }
18246                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18247                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18248                }
18249                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18250                    return Zygote.MOUNT_EXTERNAL_READ;
18251                }
18252                return Zygote.MOUNT_EXTERNAL_WRITE;
18253            }
18254
18255            @Override
18256            public boolean hasExternalStorage(int uid, String packageName) {
18257                return true;
18258            }
18259        });
18260
18261        // Now that we're mostly running, clean up stale users and apps
18262        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18263        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18264    }
18265
18266    @Override
18267    public boolean isSafeMode() {
18268        return mSafeMode;
18269    }
18270
18271    @Override
18272    public boolean hasSystemUidErrors() {
18273        return mHasSystemUidErrors;
18274    }
18275
18276    static String arrayToString(int[] array) {
18277        StringBuffer buf = new StringBuffer(128);
18278        buf.append('[');
18279        if (array != null) {
18280            for (int i=0; i<array.length; i++) {
18281                if (i > 0) buf.append(", ");
18282                buf.append(array[i]);
18283            }
18284        }
18285        buf.append(']');
18286        return buf.toString();
18287    }
18288
18289    static class DumpState {
18290        public static final int DUMP_LIBS = 1 << 0;
18291        public static final int DUMP_FEATURES = 1 << 1;
18292        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18293        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18294        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18295        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18296        public static final int DUMP_PERMISSIONS = 1 << 6;
18297        public static final int DUMP_PACKAGES = 1 << 7;
18298        public static final int DUMP_SHARED_USERS = 1 << 8;
18299        public static final int DUMP_MESSAGES = 1 << 9;
18300        public static final int DUMP_PROVIDERS = 1 << 10;
18301        public static final int DUMP_VERIFIERS = 1 << 11;
18302        public static final int DUMP_PREFERRED = 1 << 12;
18303        public static final int DUMP_PREFERRED_XML = 1 << 13;
18304        public static final int DUMP_KEYSETS = 1 << 14;
18305        public static final int DUMP_VERSION = 1 << 15;
18306        public static final int DUMP_INSTALLS = 1 << 16;
18307        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18308        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18309        public static final int DUMP_FROZEN = 1 << 19;
18310        public static final int DUMP_DEXOPT = 1 << 20;
18311        public static final int DUMP_COMPILER_STATS = 1 << 21;
18312
18313        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18314
18315        private int mTypes;
18316
18317        private int mOptions;
18318
18319        private boolean mTitlePrinted;
18320
18321        private SharedUserSetting mSharedUser;
18322
18323        public boolean isDumping(int type) {
18324            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18325                return true;
18326            }
18327
18328            return (mTypes & type) != 0;
18329        }
18330
18331        public void setDump(int type) {
18332            mTypes |= type;
18333        }
18334
18335        public boolean isOptionEnabled(int option) {
18336            return (mOptions & option) != 0;
18337        }
18338
18339        public void setOptionEnabled(int option) {
18340            mOptions |= option;
18341        }
18342
18343        public boolean onTitlePrinted() {
18344            final boolean printed = mTitlePrinted;
18345            mTitlePrinted = true;
18346            return printed;
18347        }
18348
18349        public boolean getTitlePrinted() {
18350            return mTitlePrinted;
18351        }
18352
18353        public void setTitlePrinted(boolean enabled) {
18354            mTitlePrinted = enabled;
18355        }
18356
18357        public SharedUserSetting getSharedUser() {
18358            return mSharedUser;
18359        }
18360
18361        public void setSharedUser(SharedUserSetting user) {
18362            mSharedUser = user;
18363        }
18364    }
18365
18366    @Override
18367    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18368            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18369        (new PackageManagerShellCommand(this)).exec(
18370                this, in, out, err, args, resultReceiver);
18371    }
18372
18373    @Override
18374    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18375        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18376                != PackageManager.PERMISSION_GRANTED) {
18377            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18378                    + Binder.getCallingPid()
18379                    + ", uid=" + Binder.getCallingUid()
18380                    + " without permission "
18381                    + android.Manifest.permission.DUMP);
18382            return;
18383        }
18384
18385        DumpState dumpState = new DumpState();
18386        boolean fullPreferred = false;
18387        boolean checkin = false;
18388
18389        String packageName = null;
18390        ArraySet<String> permissionNames = null;
18391
18392        int opti = 0;
18393        while (opti < args.length) {
18394            String opt = args[opti];
18395            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18396                break;
18397            }
18398            opti++;
18399
18400            if ("-a".equals(opt)) {
18401                // Right now we only know how to print all.
18402            } else if ("-h".equals(opt)) {
18403                pw.println("Package manager dump options:");
18404                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18405                pw.println("    --checkin: dump for a checkin");
18406                pw.println("    -f: print details of intent filters");
18407                pw.println("    -h: print this help");
18408                pw.println("  cmd may be one of:");
18409                pw.println("    l[ibraries]: list known shared libraries");
18410                pw.println("    f[eatures]: list device features");
18411                pw.println("    k[eysets]: print known keysets");
18412                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18413                pw.println("    perm[issions]: dump permissions");
18414                pw.println("    permission [name ...]: dump declaration and use of given permission");
18415                pw.println("    pref[erred]: print preferred package settings");
18416                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18417                pw.println("    prov[iders]: dump content providers");
18418                pw.println("    p[ackages]: dump installed packages");
18419                pw.println("    s[hared-users]: dump shared user IDs");
18420                pw.println("    m[essages]: print collected runtime messages");
18421                pw.println("    v[erifiers]: print package verifier info");
18422                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18423                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18424                pw.println("    version: print database version info");
18425                pw.println("    write: write current settings now");
18426                pw.println("    installs: details about install sessions");
18427                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18428                pw.println("    dexopt: dump dexopt state");
18429                pw.println("    compiler-stats: dump compiler statistics");
18430                pw.println("    <package.name>: info about given package");
18431                return;
18432            } else if ("--checkin".equals(opt)) {
18433                checkin = true;
18434            } else if ("-f".equals(opt)) {
18435                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18436            } else {
18437                pw.println("Unknown argument: " + opt + "; use -h for help");
18438            }
18439        }
18440
18441        // Is the caller requesting to dump a particular piece of data?
18442        if (opti < args.length) {
18443            String cmd = args[opti];
18444            opti++;
18445            // Is this a package name?
18446            if ("android".equals(cmd) || cmd.contains(".")) {
18447                packageName = cmd;
18448                // When dumping a single package, we always dump all of its
18449                // filter information since the amount of data will be reasonable.
18450                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18451            } else if ("check-permission".equals(cmd)) {
18452                if (opti >= args.length) {
18453                    pw.println("Error: check-permission missing permission argument");
18454                    return;
18455                }
18456                String perm = args[opti];
18457                opti++;
18458                if (opti >= args.length) {
18459                    pw.println("Error: check-permission missing package argument");
18460                    return;
18461                }
18462                String pkg = args[opti];
18463                opti++;
18464                int user = UserHandle.getUserId(Binder.getCallingUid());
18465                if (opti < args.length) {
18466                    try {
18467                        user = Integer.parseInt(args[opti]);
18468                    } catch (NumberFormatException e) {
18469                        pw.println("Error: check-permission user argument is not a number: "
18470                                + args[opti]);
18471                        return;
18472                    }
18473                }
18474                pw.println(checkPermission(perm, pkg, user));
18475                return;
18476            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18477                dumpState.setDump(DumpState.DUMP_LIBS);
18478            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18479                dumpState.setDump(DumpState.DUMP_FEATURES);
18480            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18481                if (opti >= args.length) {
18482                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18483                            | DumpState.DUMP_SERVICE_RESOLVERS
18484                            | DumpState.DUMP_RECEIVER_RESOLVERS
18485                            | DumpState.DUMP_CONTENT_RESOLVERS);
18486                } else {
18487                    while (opti < args.length) {
18488                        String name = args[opti];
18489                        if ("a".equals(name) || "activity".equals(name)) {
18490                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18491                        } else if ("s".equals(name) || "service".equals(name)) {
18492                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18493                        } else if ("r".equals(name) || "receiver".equals(name)) {
18494                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18495                        } else if ("c".equals(name) || "content".equals(name)) {
18496                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18497                        } else {
18498                            pw.println("Error: unknown resolver table type: " + name);
18499                            return;
18500                        }
18501                        opti++;
18502                    }
18503                }
18504            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18505                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18506            } else if ("permission".equals(cmd)) {
18507                if (opti >= args.length) {
18508                    pw.println("Error: permission requires permission name");
18509                    return;
18510                }
18511                permissionNames = new ArraySet<>();
18512                while (opti < args.length) {
18513                    permissionNames.add(args[opti]);
18514                    opti++;
18515                }
18516                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18517                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18518            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18519                dumpState.setDump(DumpState.DUMP_PREFERRED);
18520            } else if ("preferred-xml".equals(cmd)) {
18521                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18522                if (opti < args.length && "--full".equals(args[opti])) {
18523                    fullPreferred = true;
18524                    opti++;
18525                }
18526            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18527                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18528            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18529                dumpState.setDump(DumpState.DUMP_PACKAGES);
18530            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18531                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18532            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18533                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18534            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18535                dumpState.setDump(DumpState.DUMP_MESSAGES);
18536            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18537                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18538            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18539                    || "intent-filter-verifiers".equals(cmd)) {
18540                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18541            } else if ("version".equals(cmd)) {
18542                dumpState.setDump(DumpState.DUMP_VERSION);
18543            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18544                dumpState.setDump(DumpState.DUMP_KEYSETS);
18545            } else if ("installs".equals(cmd)) {
18546                dumpState.setDump(DumpState.DUMP_INSTALLS);
18547            } else if ("frozen".equals(cmd)) {
18548                dumpState.setDump(DumpState.DUMP_FROZEN);
18549            } else if ("dexopt".equals(cmd)) {
18550                dumpState.setDump(DumpState.DUMP_DEXOPT);
18551            } else if ("compiler-stats".equals(cmd)) {
18552                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18553            } else if ("write".equals(cmd)) {
18554                synchronized (mPackages) {
18555                    mSettings.writeLPr();
18556                    pw.println("Settings written.");
18557                    return;
18558                }
18559            }
18560        }
18561
18562        if (checkin) {
18563            pw.println("vers,1");
18564        }
18565
18566        // reader
18567        synchronized (mPackages) {
18568            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18569                if (!checkin) {
18570                    if (dumpState.onTitlePrinted())
18571                        pw.println();
18572                    pw.println("Database versions:");
18573                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18574                }
18575            }
18576
18577            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18578                if (!checkin) {
18579                    if (dumpState.onTitlePrinted())
18580                        pw.println();
18581                    pw.println("Verifiers:");
18582                    pw.print("  Required: ");
18583                    pw.print(mRequiredVerifierPackage);
18584                    pw.print(" (uid=");
18585                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18586                            UserHandle.USER_SYSTEM));
18587                    pw.println(")");
18588                } else if (mRequiredVerifierPackage != null) {
18589                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18590                    pw.print(",");
18591                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18592                            UserHandle.USER_SYSTEM));
18593                }
18594            }
18595
18596            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18597                    packageName == null) {
18598                if (mIntentFilterVerifierComponent != null) {
18599                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18600                    if (!checkin) {
18601                        if (dumpState.onTitlePrinted())
18602                            pw.println();
18603                        pw.println("Intent Filter Verifier:");
18604                        pw.print("  Using: ");
18605                        pw.print(verifierPackageName);
18606                        pw.print(" (uid=");
18607                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18608                                UserHandle.USER_SYSTEM));
18609                        pw.println(")");
18610                    } else if (verifierPackageName != null) {
18611                        pw.print("ifv,"); pw.print(verifierPackageName);
18612                        pw.print(",");
18613                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18614                                UserHandle.USER_SYSTEM));
18615                    }
18616                } else {
18617                    pw.println();
18618                    pw.println("No Intent Filter Verifier available!");
18619                }
18620            }
18621
18622            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18623                boolean printedHeader = false;
18624                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18625                while (it.hasNext()) {
18626                    String name = it.next();
18627                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18628                    if (!checkin) {
18629                        if (!printedHeader) {
18630                            if (dumpState.onTitlePrinted())
18631                                pw.println();
18632                            pw.println("Libraries:");
18633                            printedHeader = true;
18634                        }
18635                        pw.print("  ");
18636                    } else {
18637                        pw.print("lib,");
18638                    }
18639                    pw.print(name);
18640                    if (!checkin) {
18641                        pw.print(" -> ");
18642                    }
18643                    if (ent.path != null) {
18644                        if (!checkin) {
18645                            pw.print("(jar) ");
18646                            pw.print(ent.path);
18647                        } else {
18648                            pw.print(",jar,");
18649                            pw.print(ent.path);
18650                        }
18651                    } else {
18652                        if (!checkin) {
18653                            pw.print("(apk) ");
18654                            pw.print(ent.apk);
18655                        } else {
18656                            pw.print(",apk,");
18657                            pw.print(ent.apk);
18658                        }
18659                    }
18660                    pw.println();
18661                }
18662            }
18663
18664            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18665                if (dumpState.onTitlePrinted())
18666                    pw.println();
18667                if (!checkin) {
18668                    pw.println("Features:");
18669                }
18670
18671                for (FeatureInfo feat : mAvailableFeatures.values()) {
18672                    if (checkin) {
18673                        pw.print("feat,");
18674                        pw.print(feat.name);
18675                        pw.print(",");
18676                        pw.println(feat.version);
18677                    } else {
18678                        pw.print("  ");
18679                        pw.print(feat.name);
18680                        if (feat.version > 0) {
18681                            pw.print(" version=");
18682                            pw.print(feat.version);
18683                        }
18684                        pw.println();
18685                    }
18686                }
18687            }
18688
18689            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18690                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18691                        : "Activity Resolver Table:", "  ", packageName,
18692                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18693                    dumpState.setTitlePrinted(true);
18694                }
18695            }
18696            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18697                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18698                        : "Receiver Resolver Table:", "  ", packageName,
18699                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18700                    dumpState.setTitlePrinted(true);
18701                }
18702            }
18703            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18704                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18705                        : "Service Resolver Table:", "  ", packageName,
18706                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18707                    dumpState.setTitlePrinted(true);
18708                }
18709            }
18710            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18711                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18712                        : "Provider Resolver Table:", "  ", packageName,
18713                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18714                    dumpState.setTitlePrinted(true);
18715                }
18716            }
18717
18718            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18719                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18720                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18721                    int user = mSettings.mPreferredActivities.keyAt(i);
18722                    if (pir.dump(pw,
18723                            dumpState.getTitlePrinted()
18724                                ? "\nPreferred Activities User " + user + ":"
18725                                : "Preferred Activities User " + user + ":", "  ",
18726                            packageName, true, false)) {
18727                        dumpState.setTitlePrinted(true);
18728                    }
18729                }
18730            }
18731
18732            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18733                pw.flush();
18734                FileOutputStream fout = new FileOutputStream(fd);
18735                BufferedOutputStream str = new BufferedOutputStream(fout);
18736                XmlSerializer serializer = new FastXmlSerializer();
18737                try {
18738                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18739                    serializer.startDocument(null, true);
18740                    serializer.setFeature(
18741                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18742                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18743                    serializer.endDocument();
18744                    serializer.flush();
18745                } catch (IllegalArgumentException e) {
18746                    pw.println("Failed writing: " + e);
18747                } catch (IllegalStateException e) {
18748                    pw.println("Failed writing: " + e);
18749                } catch (IOException e) {
18750                    pw.println("Failed writing: " + e);
18751                }
18752            }
18753
18754            if (!checkin
18755                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18756                    && packageName == null) {
18757                pw.println();
18758                int count = mSettings.mPackages.size();
18759                if (count == 0) {
18760                    pw.println("No applications!");
18761                    pw.println();
18762                } else {
18763                    final String prefix = "  ";
18764                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18765                    if (allPackageSettings.size() == 0) {
18766                        pw.println("No domain preferred apps!");
18767                        pw.println();
18768                    } else {
18769                        pw.println("App verification status:");
18770                        pw.println();
18771                        count = 0;
18772                        for (PackageSetting ps : allPackageSettings) {
18773                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18774                            if (ivi == null || ivi.getPackageName() == null) continue;
18775                            pw.println(prefix + "Package: " + ivi.getPackageName());
18776                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18777                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18778                            pw.println();
18779                            count++;
18780                        }
18781                        if (count == 0) {
18782                            pw.println(prefix + "No app verification established.");
18783                            pw.println();
18784                        }
18785                        for (int userId : sUserManager.getUserIds()) {
18786                            pw.println("App linkages for user " + userId + ":");
18787                            pw.println();
18788                            count = 0;
18789                            for (PackageSetting ps : allPackageSettings) {
18790                                final long status = ps.getDomainVerificationStatusForUser(userId);
18791                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18792                                    continue;
18793                                }
18794                                pw.println(prefix + "Package: " + ps.name);
18795                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18796                                String statusStr = IntentFilterVerificationInfo.
18797                                        getStatusStringFromValue(status);
18798                                pw.println(prefix + "Status:  " + statusStr);
18799                                pw.println();
18800                                count++;
18801                            }
18802                            if (count == 0) {
18803                                pw.println(prefix + "No configured app linkages.");
18804                                pw.println();
18805                            }
18806                        }
18807                    }
18808                }
18809            }
18810
18811            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18812                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18813                if (packageName == null && permissionNames == null) {
18814                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18815                        if (iperm == 0) {
18816                            if (dumpState.onTitlePrinted())
18817                                pw.println();
18818                            pw.println("AppOp Permissions:");
18819                        }
18820                        pw.print("  AppOp Permission ");
18821                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18822                        pw.println(":");
18823                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18824                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18825                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18826                        }
18827                    }
18828                }
18829            }
18830
18831            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18832                boolean printedSomething = false;
18833                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18834                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18835                        continue;
18836                    }
18837                    if (!printedSomething) {
18838                        if (dumpState.onTitlePrinted())
18839                            pw.println();
18840                        pw.println("Registered ContentProviders:");
18841                        printedSomething = true;
18842                    }
18843                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18844                    pw.print("    "); pw.println(p.toString());
18845                }
18846                printedSomething = false;
18847                for (Map.Entry<String, PackageParser.Provider> entry :
18848                        mProvidersByAuthority.entrySet()) {
18849                    PackageParser.Provider p = entry.getValue();
18850                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18851                        continue;
18852                    }
18853                    if (!printedSomething) {
18854                        if (dumpState.onTitlePrinted())
18855                            pw.println();
18856                        pw.println("ContentProvider Authorities:");
18857                        printedSomething = true;
18858                    }
18859                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18860                    pw.print("    "); pw.println(p.toString());
18861                    if (p.info != null && p.info.applicationInfo != null) {
18862                        final String appInfo = p.info.applicationInfo.toString();
18863                        pw.print("      applicationInfo="); pw.println(appInfo);
18864                    }
18865                }
18866            }
18867
18868            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18869                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18870            }
18871
18872            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18873                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18874            }
18875
18876            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18877                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18878            }
18879
18880            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18881                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18882            }
18883
18884            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18885                // XXX should handle packageName != null by dumping only install data that
18886                // the given package is involved with.
18887                if (dumpState.onTitlePrinted()) pw.println();
18888                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18889            }
18890
18891            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18892                // XXX should handle packageName != null by dumping only install data that
18893                // the given package is involved with.
18894                if (dumpState.onTitlePrinted()) pw.println();
18895
18896                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18897                ipw.println();
18898                ipw.println("Frozen packages:");
18899                ipw.increaseIndent();
18900                if (mFrozenPackages.size() == 0) {
18901                    ipw.println("(none)");
18902                } else {
18903                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18904                        ipw.println(mFrozenPackages.valueAt(i));
18905                    }
18906                }
18907                ipw.decreaseIndent();
18908            }
18909
18910            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18911                if (dumpState.onTitlePrinted()) pw.println();
18912                dumpDexoptStateLPr(pw, packageName);
18913            }
18914
18915            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
18916                if (dumpState.onTitlePrinted()) pw.println();
18917                dumpCompilerStatsLPr(pw, packageName);
18918            }
18919
18920            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18921                if (dumpState.onTitlePrinted()) pw.println();
18922                mSettings.dumpReadMessagesLPr(pw, dumpState);
18923
18924                pw.println();
18925                pw.println("Package warning messages:");
18926                BufferedReader in = null;
18927                String line = null;
18928                try {
18929                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18930                    while ((line = in.readLine()) != null) {
18931                        if (line.contains("ignored: updated version")) continue;
18932                        pw.println(line);
18933                    }
18934                } catch (IOException ignored) {
18935                } finally {
18936                    IoUtils.closeQuietly(in);
18937                }
18938            }
18939
18940            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18941                BufferedReader in = null;
18942                String line = null;
18943                try {
18944                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18945                    while ((line = in.readLine()) != null) {
18946                        if (line.contains("ignored: updated version")) continue;
18947                        pw.print("msg,");
18948                        pw.println(line);
18949                    }
18950                } catch (IOException ignored) {
18951                } finally {
18952                    IoUtils.closeQuietly(in);
18953                }
18954            }
18955        }
18956    }
18957
18958    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18959        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18960        ipw.println();
18961        ipw.println("Dexopt state:");
18962        ipw.increaseIndent();
18963        Collection<PackageParser.Package> packages = null;
18964        if (packageName != null) {
18965            PackageParser.Package targetPackage = mPackages.get(packageName);
18966            if (targetPackage != null) {
18967                packages = Collections.singletonList(targetPackage);
18968            } else {
18969                ipw.println("Unable to find package: " + packageName);
18970                return;
18971            }
18972        } else {
18973            packages = mPackages.values();
18974        }
18975
18976        for (PackageParser.Package pkg : packages) {
18977            ipw.println("[" + pkg.packageName + "]");
18978            ipw.increaseIndent();
18979            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18980            ipw.decreaseIndent();
18981        }
18982    }
18983
18984    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
18985        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18986        ipw.println();
18987        ipw.println("Compiler stats:");
18988        ipw.increaseIndent();
18989        Collection<PackageParser.Package> packages = null;
18990        if (packageName != null) {
18991            PackageParser.Package targetPackage = mPackages.get(packageName);
18992            if (targetPackage != null) {
18993                packages = Collections.singletonList(targetPackage);
18994            } else {
18995                ipw.println("Unable to find package: " + packageName);
18996                return;
18997            }
18998        } else {
18999            packages = mPackages.values();
19000        }
19001
19002        for (PackageParser.Package pkg : packages) {
19003            ipw.println("[" + pkg.packageName + "]");
19004            ipw.increaseIndent();
19005
19006            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19007            if (stats == null) {
19008                ipw.println("(No recorded stats)");
19009            } else {
19010                stats.dump(ipw);
19011            }
19012            ipw.decreaseIndent();
19013        }
19014    }
19015
19016    private String dumpDomainString(String packageName) {
19017        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19018                .getList();
19019        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19020
19021        ArraySet<String> result = new ArraySet<>();
19022        if (iviList.size() > 0) {
19023            for (IntentFilterVerificationInfo ivi : iviList) {
19024                for (String host : ivi.getDomains()) {
19025                    result.add(host);
19026                }
19027            }
19028        }
19029        if (filters != null && filters.size() > 0) {
19030            for (IntentFilter filter : filters) {
19031                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19032                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19033                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19034                    result.addAll(filter.getHostsList());
19035                }
19036            }
19037        }
19038
19039        StringBuilder sb = new StringBuilder(result.size() * 16);
19040        for (String domain : result) {
19041            if (sb.length() > 0) sb.append(" ");
19042            sb.append(domain);
19043        }
19044        return sb.toString();
19045    }
19046
19047    // ------- apps on sdcard specific code -------
19048    static final boolean DEBUG_SD_INSTALL = false;
19049
19050    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19051
19052    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19053
19054    private boolean mMediaMounted = false;
19055
19056    static String getEncryptKey() {
19057        try {
19058            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19059                    SD_ENCRYPTION_KEYSTORE_NAME);
19060            if (sdEncKey == null) {
19061                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19062                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19063                if (sdEncKey == null) {
19064                    Slog.e(TAG, "Failed to create encryption keys");
19065                    return null;
19066                }
19067            }
19068            return sdEncKey;
19069        } catch (NoSuchAlgorithmException nsae) {
19070            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19071            return null;
19072        } catch (IOException ioe) {
19073            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19074            return null;
19075        }
19076    }
19077
19078    /*
19079     * Update media status on PackageManager.
19080     */
19081    @Override
19082    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19083        int callingUid = Binder.getCallingUid();
19084        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19085            throw new SecurityException("Media status can only be updated by the system");
19086        }
19087        // reader; this apparently protects mMediaMounted, but should probably
19088        // be a different lock in that case.
19089        synchronized (mPackages) {
19090            Log.i(TAG, "Updating external media status from "
19091                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19092                    + (mediaStatus ? "mounted" : "unmounted"));
19093            if (DEBUG_SD_INSTALL)
19094                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19095                        + ", mMediaMounted=" + mMediaMounted);
19096            if (mediaStatus == mMediaMounted) {
19097                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19098                        : 0, -1);
19099                mHandler.sendMessage(msg);
19100                return;
19101            }
19102            mMediaMounted = mediaStatus;
19103        }
19104        // Queue up an async operation since the package installation may take a
19105        // little while.
19106        mHandler.post(new Runnable() {
19107            public void run() {
19108                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19109            }
19110        });
19111    }
19112
19113    /**
19114     * Called by MountService when the initial ASECs to scan are available.
19115     * Should block until all the ASEC containers are finished being scanned.
19116     */
19117    public void scanAvailableAsecs() {
19118        updateExternalMediaStatusInner(true, false, false);
19119    }
19120
19121    /*
19122     * Collect information of applications on external media, map them against
19123     * existing containers and update information based on current mount status.
19124     * Please note that we always have to report status if reportStatus has been
19125     * set to true especially when unloading packages.
19126     */
19127    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19128            boolean externalStorage) {
19129        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19130        int[] uidArr = EmptyArray.INT;
19131
19132        final String[] list = PackageHelper.getSecureContainerList();
19133        if (ArrayUtils.isEmpty(list)) {
19134            Log.i(TAG, "No secure containers found");
19135        } else {
19136            // Process list of secure containers and categorize them
19137            // as active or stale based on their package internal state.
19138
19139            // reader
19140            synchronized (mPackages) {
19141                for (String cid : list) {
19142                    // Leave stages untouched for now; installer service owns them
19143                    if (PackageInstallerService.isStageName(cid)) continue;
19144
19145                    if (DEBUG_SD_INSTALL)
19146                        Log.i(TAG, "Processing container " + cid);
19147                    String pkgName = getAsecPackageName(cid);
19148                    if (pkgName == null) {
19149                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19150                        continue;
19151                    }
19152                    if (DEBUG_SD_INSTALL)
19153                        Log.i(TAG, "Looking for pkg : " + pkgName);
19154
19155                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19156                    if (ps == null) {
19157                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19158                        continue;
19159                    }
19160
19161                    /*
19162                     * Skip packages that are not external if we're unmounting
19163                     * external storage.
19164                     */
19165                    if (externalStorage && !isMounted && !isExternal(ps)) {
19166                        continue;
19167                    }
19168
19169                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19170                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19171                    // The package status is changed only if the code path
19172                    // matches between settings and the container id.
19173                    if (ps.codePathString != null
19174                            && ps.codePathString.startsWith(args.getCodePath())) {
19175                        if (DEBUG_SD_INSTALL) {
19176                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19177                                    + " at code path: " + ps.codePathString);
19178                        }
19179
19180                        // We do have a valid package installed on sdcard
19181                        processCids.put(args, ps.codePathString);
19182                        final int uid = ps.appId;
19183                        if (uid != -1) {
19184                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19185                        }
19186                    } else {
19187                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19188                                + ps.codePathString);
19189                    }
19190                }
19191            }
19192
19193            Arrays.sort(uidArr);
19194        }
19195
19196        // Process packages with valid entries.
19197        if (isMounted) {
19198            if (DEBUG_SD_INSTALL)
19199                Log.i(TAG, "Loading packages");
19200            loadMediaPackages(processCids, uidArr, externalStorage);
19201            startCleaningPackages();
19202            mInstallerService.onSecureContainersAvailable();
19203        } else {
19204            if (DEBUG_SD_INSTALL)
19205                Log.i(TAG, "Unloading packages");
19206            unloadMediaPackages(processCids, uidArr, reportStatus);
19207        }
19208    }
19209
19210    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19211            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19212        final int size = infos.size();
19213        final String[] packageNames = new String[size];
19214        final int[] packageUids = new int[size];
19215        for (int i = 0; i < size; i++) {
19216            final ApplicationInfo info = infos.get(i);
19217            packageNames[i] = info.packageName;
19218            packageUids[i] = info.uid;
19219        }
19220        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19221                finishedReceiver);
19222    }
19223
19224    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19225            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19226        sendResourcesChangedBroadcast(mediaStatus, replacing,
19227                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19228    }
19229
19230    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19231            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19232        int size = pkgList.length;
19233        if (size > 0) {
19234            // Send broadcasts here
19235            Bundle extras = new Bundle();
19236            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19237            if (uidArr != null) {
19238                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19239            }
19240            if (replacing) {
19241                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19242            }
19243            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19244                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19245            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19246        }
19247    }
19248
19249   /*
19250     * Look at potentially valid container ids from processCids If package
19251     * information doesn't match the one on record or package scanning fails,
19252     * the cid is added to list of removeCids. We currently don't delete stale
19253     * containers.
19254     */
19255    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19256            boolean externalStorage) {
19257        ArrayList<String> pkgList = new ArrayList<String>();
19258        Set<AsecInstallArgs> keys = processCids.keySet();
19259
19260        for (AsecInstallArgs args : keys) {
19261            String codePath = processCids.get(args);
19262            if (DEBUG_SD_INSTALL)
19263                Log.i(TAG, "Loading container : " + args.cid);
19264            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19265            try {
19266                // Make sure there are no container errors first.
19267                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19268                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19269                            + " when installing from sdcard");
19270                    continue;
19271                }
19272                // Check code path here.
19273                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19274                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19275                            + " does not match one in settings " + codePath);
19276                    continue;
19277                }
19278                // Parse package
19279                int parseFlags = mDefParseFlags;
19280                if (args.isExternalAsec()) {
19281                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19282                }
19283                if (args.isFwdLocked()) {
19284                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19285                }
19286
19287                synchronized (mInstallLock) {
19288                    PackageParser.Package pkg = null;
19289                    try {
19290                        // Sadly we don't know the package name yet to freeze it
19291                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19292                                SCAN_IGNORE_FROZEN, 0, null);
19293                    } catch (PackageManagerException e) {
19294                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19295                    }
19296                    // Scan the package
19297                    if (pkg != null) {
19298                        /*
19299                         * TODO why is the lock being held? doPostInstall is
19300                         * called in other places without the lock. This needs
19301                         * to be straightened out.
19302                         */
19303                        // writer
19304                        synchronized (mPackages) {
19305                            retCode = PackageManager.INSTALL_SUCCEEDED;
19306                            pkgList.add(pkg.packageName);
19307                            // Post process args
19308                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19309                                    pkg.applicationInfo.uid);
19310                        }
19311                    } else {
19312                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19313                    }
19314                }
19315
19316            } finally {
19317                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19318                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19319                }
19320            }
19321        }
19322        // writer
19323        synchronized (mPackages) {
19324            // If the platform SDK has changed since the last time we booted,
19325            // we need to re-grant app permission to catch any new ones that
19326            // appear. This is really a hack, and means that apps can in some
19327            // cases get permissions that the user didn't initially explicitly
19328            // allow... it would be nice to have some better way to handle
19329            // this situation.
19330            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19331                    : mSettings.getInternalVersion();
19332            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19333                    : StorageManager.UUID_PRIVATE_INTERNAL;
19334
19335            int updateFlags = UPDATE_PERMISSIONS_ALL;
19336            if (ver.sdkVersion != mSdkVersion) {
19337                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19338                        + mSdkVersion + "; regranting permissions for external");
19339                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19340            }
19341            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19342
19343            // Yay, everything is now upgraded
19344            ver.forceCurrent();
19345
19346            // can downgrade to reader
19347            // Persist settings
19348            mSettings.writeLPr();
19349        }
19350        // Send a broadcast to let everyone know we are done processing
19351        if (pkgList.size() > 0) {
19352            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19353        }
19354    }
19355
19356   /*
19357     * Utility method to unload a list of specified containers
19358     */
19359    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19360        // Just unmount all valid containers.
19361        for (AsecInstallArgs arg : cidArgs) {
19362            synchronized (mInstallLock) {
19363                arg.doPostDeleteLI(false);
19364           }
19365       }
19366   }
19367
19368    /*
19369     * Unload packages mounted on external media. This involves deleting package
19370     * data from internal structures, sending broadcasts about disabled packages,
19371     * gc'ing to free up references, unmounting all secure containers
19372     * corresponding to packages on external media, and posting a
19373     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19374     * that we always have to post this message if status has been requested no
19375     * matter what.
19376     */
19377    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19378            final boolean reportStatus) {
19379        if (DEBUG_SD_INSTALL)
19380            Log.i(TAG, "unloading media packages");
19381        ArrayList<String> pkgList = new ArrayList<String>();
19382        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19383        final Set<AsecInstallArgs> keys = processCids.keySet();
19384        for (AsecInstallArgs args : keys) {
19385            String pkgName = args.getPackageName();
19386            if (DEBUG_SD_INSTALL)
19387                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19388            // Delete package internally
19389            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19390            synchronized (mInstallLock) {
19391                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19392                final boolean res;
19393                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19394                        "unloadMediaPackages")) {
19395                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19396                            null);
19397                }
19398                if (res) {
19399                    pkgList.add(pkgName);
19400                } else {
19401                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19402                    failedList.add(args);
19403                }
19404            }
19405        }
19406
19407        // reader
19408        synchronized (mPackages) {
19409            // We didn't update the settings after removing each package;
19410            // write them now for all packages.
19411            mSettings.writeLPr();
19412        }
19413
19414        // We have to absolutely send UPDATED_MEDIA_STATUS only
19415        // after confirming that all the receivers processed the ordered
19416        // broadcast when packages get disabled, force a gc to clean things up.
19417        // and unload all the containers.
19418        if (pkgList.size() > 0) {
19419            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19420                    new IIntentReceiver.Stub() {
19421                public void performReceive(Intent intent, int resultCode, String data,
19422                        Bundle extras, boolean ordered, boolean sticky,
19423                        int sendingUser) throws RemoteException {
19424                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19425                            reportStatus ? 1 : 0, 1, keys);
19426                    mHandler.sendMessage(msg);
19427                }
19428            });
19429        } else {
19430            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19431                    keys);
19432            mHandler.sendMessage(msg);
19433        }
19434    }
19435
19436    private void loadPrivatePackages(final VolumeInfo vol) {
19437        mHandler.post(new Runnable() {
19438            @Override
19439            public void run() {
19440                loadPrivatePackagesInner(vol);
19441            }
19442        });
19443    }
19444
19445    private void loadPrivatePackagesInner(VolumeInfo vol) {
19446        final String volumeUuid = vol.fsUuid;
19447        if (TextUtils.isEmpty(volumeUuid)) {
19448            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19449            return;
19450        }
19451
19452        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19453        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19454        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19455
19456        final VersionInfo ver;
19457        final List<PackageSetting> packages;
19458        synchronized (mPackages) {
19459            ver = mSettings.findOrCreateVersion(volumeUuid);
19460            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19461        }
19462
19463        for (PackageSetting ps : packages) {
19464            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19465            synchronized (mInstallLock) {
19466                final PackageParser.Package pkg;
19467                try {
19468                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19469                    loaded.add(pkg.applicationInfo);
19470
19471                } catch (PackageManagerException e) {
19472                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19473                }
19474
19475                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19476                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19477                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19478                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19479                }
19480            }
19481        }
19482
19483        // Reconcile app data for all started/unlocked users
19484        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19485        final UserManager um = mContext.getSystemService(UserManager.class);
19486        UserManagerInternal umInternal = getUserManagerInternal();
19487        for (UserInfo user : um.getUsers()) {
19488            final int flags;
19489            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19490                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19491            } else if (umInternal.isUserRunning(user.id)) {
19492                flags = StorageManager.FLAG_STORAGE_DE;
19493            } else {
19494                continue;
19495            }
19496
19497            try {
19498                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19499                synchronized (mInstallLock) {
19500                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19501                }
19502            } catch (IllegalStateException e) {
19503                // Device was probably ejected, and we'll process that event momentarily
19504                Slog.w(TAG, "Failed to prepare storage: " + e);
19505            }
19506        }
19507
19508        synchronized (mPackages) {
19509            int updateFlags = UPDATE_PERMISSIONS_ALL;
19510            if (ver.sdkVersion != mSdkVersion) {
19511                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19512                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19513                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19514            }
19515            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19516
19517            // Yay, everything is now upgraded
19518            ver.forceCurrent();
19519
19520            mSettings.writeLPr();
19521        }
19522
19523        for (PackageFreezer freezer : freezers) {
19524            freezer.close();
19525        }
19526
19527        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19528        sendResourcesChangedBroadcast(true, false, loaded, null);
19529    }
19530
19531    private void unloadPrivatePackages(final VolumeInfo vol) {
19532        mHandler.post(new Runnable() {
19533            @Override
19534            public void run() {
19535                unloadPrivatePackagesInner(vol);
19536            }
19537        });
19538    }
19539
19540    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19541        final String volumeUuid = vol.fsUuid;
19542        if (TextUtils.isEmpty(volumeUuid)) {
19543            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19544            return;
19545        }
19546
19547        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19548        synchronized (mInstallLock) {
19549        synchronized (mPackages) {
19550            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19551            for (PackageSetting ps : packages) {
19552                if (ps.pkg == null) continue;
19553
19554                final ApplicationInfo info = ps.pkg.applicationInfo;
19555                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19556                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19557
19558                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19559                        "unloadPrivatePackagesInner")) {
19560                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19561                            false, null)) {
19562                        unloaded.add(info);
19563                    } else {
19564                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19565                    }
19566                }
19567
19568                // Try very hard to release any references to this package
19569                // so we don't risk the system server being killed due to
19570                // open FDs
19571                AttributeCache.instance().removePackage(ps.name);
19572            }
19573
19574            mSettings.writeLPr();
19575        }
19576        }
19577
19578        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19579        sendResourcesChangedBroadcast(false, false, unloaded, null);
19580
19581        // Try very hard to release any references to this path so we don't risk
19582        // the system server being killed due to open FDs
19583        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19584
19585        for (int i = 0; i < 3; i++) {
19586            System.gc();
19587            System.runFinalization();
19588        }
19589    }
19590
19591    /**
19592     * Prepare storage areas for given user on all mounted devices.
19593     */
19594    void prepareUserData(int userId, int userSerial, int flags) {
19595        synchronized (mInstallLock) {
19596            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19597            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19598                final String volumeUuid = vol.getFsUuid();
19599                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19600            }
19601        }
19602    }
19603
19604    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19605            boolean allowRecover) {
19606        // Prepare storage and verify that serial numbers are consistent; if
19607        // there's a mismatch we need to destroy to avoid leaking data
19608        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19609        try {
19610            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19611
19612            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19613                UserManagerService.enforceSerialNumber(
19614                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19615                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19616                    UserManagerService.enforceSerialNumber(
19617                            Environment.getDataSystemDeDirectory(userId), userSerial);
19618                }
19619            }
19620            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19621                UserManagerService.enforceSerialNumber(
19622                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19623                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19624                    UserManagerService.enforceSerialNumber(
19625                            Environment.getDataSystemCeDirectory(userId), userSerial);
19626                }
19627            }
19628
19629            synchronized (mInstallLock) {
19630                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19631            }
19632        } catch (Exception e) {
19633            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19634                    + " because we failed to prepare: " + e);
19635            destroyUserDataLI(volumeUuid, userId,
19636                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19637
19638            if (allowRecover) {
19639                // Try one last time; if we fail again we're really in trouble
19640                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19641            }
19642        }
19643    }
19644
19645    /**
19646     * Destroy storage areas for given user on all mounted devices.
19647     */
19648    void destroyUserData(int userId, int flags) {
19649        synchronized (mInstallLock) {
19650            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19651            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19652                final String volumeUuid = vol.getFsUuid();
19653                destroyUserDataLI(volumeUuid, userId, flags);
19654            }
19655        }
19656    }
19657
19658    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19659        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19660        try {
19661            // Clean up app data, profile data, and media data
19662            mInstaller.destroyUserData(volumeUuid, userId, flags);
19663
19664            // Clean up system data
19665            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19666                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19667                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19668                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19669                }
19670                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19671                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19672                }
19673            }
19674
19675            // Data with special labels is now gone, so finish the job
19676            storage.destroyUserStorage(volumeUuid, userId, flags);
19677
19678        } catch (Exception e) {
19679            logCriticalInfo(Log.WARN,
19680                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19681        }
19682    }
19683
19684    /**
19685     * Examine all users present on given mounted volume, and destroy data
19686     * belonging to users that are no longer valid, or whose user ID has been
19687     * recycled.
19688     */
19689    private void reconcileUsers(String volumeUuid) {
19690        final List<File> files = new ArrayList<>();
19691        Collections.addAll(files, FileUtils
19692                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19693        Collections.addAll(files, FileUtils
19694                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19695        Collections.addAll(files, FileUtils
19696                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19697        Collections.addAll(files, FileUtils
19698                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19699        for (File file : files) {
19700            if (!file.isDirectory()) continue;
19701
19702            final int userId;
19703            final UserInfo info;
19704            try {
19705                userId = Integer.parseInt(file.getName());
19706                info = sUserManager.getUserInfo(userId);
19707            } catch (NumberFormatException e) {
19708                Slog.w(TAG, "Invalid user directory " + file);
19709                continue;
19710            }
19711
19712            boolean destroyUser = false;
19713            if (info == null) {
19714                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19715                        + " because no matching user was found");
19716                destroyUser = true;
19717            } else if (!mOnlyCore) {
19718                try {
19719                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19720                } catch (IOException e) {
19721                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19722                            + " because we failed to enforce serial number: " + e);
19723                    destroyUser = true;
19724                }
19725            }
19726
19727            if (destroyUser) {
19728                synchronized (mInstallLock) {
19729                    destroyUserDataLI(volumeUuid, userId,
19730                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19731                }
19732            }
19733        }
19734    }
19735
19736    private void assertPackageKnown(String volumeUuid, String packageName)
19737            throws PackageManagerException {
19738        synchronized (mPackages) {
19739            // Normalize package name to handle renamed packages
19740            packageName = normalizePackageNameLPr(packageName);
19741
19742            final PackageSetting ps = mSettings.mPackages.get(packageName);
19743            if (ps == null) {
19744                throw new PackageManagerException("Package " + packageName + " is unknown");
19745            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19746                throw new PackageManagerException(
19747                        "Package " + packageName + " found on unknown volume " + volumeUuid
19748                                + "; expected volume " + ps.volumeUuid);
19749            }
19750        }
19751    }
19752
19753    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19754            throws PackageManagerException {
19755        synchronized (mPackages) {
19756            // Normalize package name to handle renamed packages
19757            packageName = normalizePackageNameLPr(packageName);
19758
19759            final PackageSetting ps = mSettings.mPackages.get(packageName);
19760            if (ps == null) {
19761                throw new PackageManagerException("Package " + packageName + " is unknown");
19762            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19763                throw new PackageManagerException(
19764                        "Package " + packageName + " found on unknown volume " + volumeUuid
19765                                + "; expected volume " + ps.volumeUuid);
19766            } else if (!ps.getInstalled(userId)) {
19767                throw new PackageManagerException(
19768                        "Package " + packageName + " not installed for user " + userId);
19769            }
19770        }
19771    }
19772
19773    /**
19774     * Examine all apps present on given mounted volume, and destroy apps that
19775     * aren't expected, either due to uninstallation or reinstallation on
19776     * another volume.
19777     */
19778    private void reconcileApps(String volumeUuid) {
19779        final File[] files = FileUtils
19780                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19781        for (File file : files) {
19782            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19783                    && !PackageInstallerService.isStageName(file.getName());
19784            if (!isPackage) {
19785                // Ignore entries which are not packages
19786                continue;
19787            }
19788
19789            try {
19790                final PackageLite pkg = PackageParser.parsePackageLite(file,
19791                        PackageParser.PARSE_MUST_BE_APK);
19792                assertPackageKnown(volumeUuid, pkg.packageName);
19793
19794            } catch (PackageParserException | PackageManagerException e) {
19795                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19796                synchronized (mInstallLock) {
19797                    removeCodePathLI(file);
19798                }
19799            }
19800        }
19801    }
19802
19803    /**
19804     * Reconcile all app data for the given user.
19805     * <p>
19806     * Verifies that directories exist and that ownership and labeling is
19807     * correct for all installed apps on all mounted volumes.
19808     */
19809    void reconcileAppsData(int userId, int flags) {
19810        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19811        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19812            final String volumeUuid = vol.getFsUuid();
19813            synchronized (mInstallLock) {
19814                reconcileAppsDataLI(volumeUuid, userId, flags);
19815            }
19816        }
19817    }
19818
19819    /**
19820     * Reconcile all app data on given mounted volume.
19821     * <p>
19822     * Destroys app data that isn't expected, either due to uninstallation or
19823     * reinstallation on another volume.
19824     * <p>
19825     * Verifies that directories exist and that ownership and labeling is
19826     * correct for all installed apps.
19827     */
19828    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19829        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19830                + Integer.toHexString(flags));
19831
19832        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19833        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19834
19835        // First look for stale data that doesn't belong, and check if things
19836        // have changed since we did our last restorecon
19837        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19838            if (StorageManager.isFileEncryptedNativeOrEmulated()
19839                    && !StorageManager.isUserKeyUnlocked(userId)) {
19840                throw new RuntimeException(
19841                        "Yikes, someone asked us to reconcile CE storage while " + userId
19842                                + " was still locked; this would have caused massive data loss!");
19843            }
19844
19845            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19846            for (File file : files) {
19847                final String packageName = file.getName();
19848                try {
19849                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19850                } catch (PackageManagerException e) {
19851                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19852                    try {
19853                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19854                                StorageManager.FLAG_STORAGE_CE, 0);
19855                    } catch (InstallerException e2) {
19856                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19857                    }
19858                }
19859            }
19860        }
19861        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19862            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19863            for (File file : files) {
19864                final String packageName = file.getName();
19865                try {
19866                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19867                } catch (PackageManagerException e) {
19868                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19869                    try {
19870                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19871                                StorageManager.FLAG_STORAGE_DE, 0);
19872                    } catch (InstallerException e2) {
19873                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19874                    }
19875                }
19876            }
19877        }
19878
19879        // Ensure that data directories are ready to roll for all packages
19880        // installed for this volume and user
19881        final List<PackageSetting> packages;
19882        synchronized (mPackages) {
19883            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19884        }
19885        int preparedCount = 0;
19886        for (PackageSetting ps : packages) {
19887            final String packageName = ps.name;
19888            if (ps.pkg == null) {
19889                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19890                // TODO: might be due to legacy ASEC apps; we should circle back
19891                // and reconcile again once they're scanned
19892                continue;
19893            }
19894
19895            if (ps.getInstalled(userId)) {
19896                prepareAppDataLIF(ps.pkg, userId, flags);
19897
19898                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19899                    // We may have just shuffled around app data directories, so
19900                    // prepare them one more time
19901                    prepareAppDataLIF(ps.pkg, userId, flags);
19902                }
19903
19904                preparedCount++;
19905            }
19906        }
19907
19908        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
19909    }
19910
19911    /**
19912     * Prepare app data for the given app just after it was installed or
19913     * upgraded. This method carefully only touches users that it's installed
19914     * for, and it forces a restorecon to handle any seinfo changes.
19915     * <p>
19916     * Verifies that directories exist and that ownership and labeling is
19917     * correct for all installed apps. If there is an ownership mismatch, it
19918     * will try recovering system apps by wiping data; third-party app data is
19919     * left intact.
19920     * <p>
19921     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19922     */
19923    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19924        final PackageSetting ps;
19925        synchronized (mPackages) {
19926            ps = mSettings.mPackages.get(pkg.packageName);
19927            mSettings.writeKernelMappingLPr(ps);
19928        }
19929
19930        final UserManager um = mContext.getSystemService(UserManager.class);
19931        UserManagerInternal umInternal = getUserManagerInternal();
19932        for (UserInfo user : um.getUsers()) {
19933            final int flags;
19934            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19935                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19936            } else if (umInternal.isUserRunning(user.id)) {
19937                flags = StorageManager.FLAG_STORAGE_DE;
19938            } else {
19939                continue;
19940            }
19941
19942            if (ps.getInstalled(user.id)) {
19943                // TODO: when user data is locked, mark that we're still dirty
19944                prepareAppDataLIF(pkg, user.id, flags);
19945            }
19946        }
19947    }
19948
19949    /**
19950     * Prepare app data for the given app.
19951     * <p>
19952     * Verifies that directories exist and that ownership and labeling is
19953     * correct for all installed apps. If there is an ownership mismatch, this
19954     * will try recovering system apps by wiping data; third-party app data is
19955     * left intact.
19956     */
19957    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
19958        if (pkg == null) {
19959            Slog.wtf(TAG, "Package was null!", new Throwable());
19960            return;
19961        }
19962        prepareAppDataLeafLIF(pkg, userId, flags);
19963        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19964        for (int i = 0; i < childCount; i++) {
19965            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
19966        }
19967    }
19968
19969    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19970        if (DEBUG_APP_DATA) {
19971            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19972                    + Integer.toHexString(flags));
19973        }
19974
19975        final String volumeUuid = pkg.volumeUuid;
19976        final String packageName = pkg.packageName;
19977        final ApplicationInfo app = pkg.applicationInfo;
19978        final int appId = UserHandle.getAppId(app.uid);
19979
19980        Preconditions.checkNotNull(app.seinfo);
19981
19982        long ceDataInode = -1;
19983        try {
19984            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19985                    appId, app.seinfo, app.targetSdkVersion);
19986        } catch (InstallerException e) {
19987            if (app.isSystemApp()) {
19988                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19989                        + ", but trying to recover: " + e);
19990                destroyAppDataLeafLIF(pkg, userId, flags);
19991                try {
19992                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19993                            appId, app.seinfo, app.targetSdkVersion);
19994                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19995                } catch (InstallerException e2) {
19996                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19997                }
19998            } else {
19999                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20000            }
20001        }
20002
20003        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
20004            // TODO: mark this structure as dirty so we persist it!
20005            synchronized (mPackages) {
20006                final PackageSetting ps = mSettings.mPackages.get(packageName);
20007                if (ps != null) {
20008                    ps.setCeDataInode(ceDataInode, userId);
20009                }
20010            }
20011        }
20012
20013        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20014    }
20015
20016    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20017        if (pkg == null) {
20018            Slog.wtf(TAG, "Package was null!", new Throwable());
20019            return;
20020        }
20021        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20022        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20023        for (int i = 0; i < childCount; i++) {
20024            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20025        }
20026    }
20027
20028    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20029        final String volumeUuid = pkg.volumeUuid;
20030        final String packageName = pkg.packageName;
20031        final ApplicationInfo app = pkg.applicationInfo;
20032
20033        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20034            // Create a native library symlink only if we have native libraries
20035            // and if the native libraries are 32 bit libraries. We do not provide
20036            // this symlink for 64 bit libraries.
20037            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20038                final String nativeLibPath = app.nativeLibraryDir;
20039                try {
20040                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20041                            nativeLibPath, userId);
20042                } catch (InstallerException e) {
20043                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20044                }
20045            }
20046        }
20047    }
20048
20049    /**
20050     * For system apps on non-FBE devices, this method migrates any existing
20051     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20052     * requested by the app.
20053     */
20054    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20055        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20056                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20057            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20058                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20059            try {
20060                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20061                        storageTarget);
20062            } catch (InstallerException e) {
20063                logCriticalInfo(Log.WARN,
20064                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20065            }
20066            return true;
20067        } else {
20068            return false;
20069        }
20070    }
20071
20072    public PackageFreezer freezePackage(String packageName, String killReason) {
20073        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20074    }
20075
20076    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20077        return new PackageFreezer(packageName, userId, killReason);
20078    }
20079
20080    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20081            String killReason) {
20082        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20083    }
20084
20085    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20086            String killReason) {
20087        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20088            return new PackageFreezer();
20089        } else {
20090            return freezePackage(packageName, userId, killReason);
20091        }
20092    }
20093
20094    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20095            String killReason) {
20096        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20097    }
20098
20099    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20100            String killReason) {
20101        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20102            return new PackageFreezer();
20103        } else {
20104            return freezePackage(packageName, userId, killReason);
20105        }
20106    }
20107
20108    /**
20109     * Class that freezes and kills the given package upon creation, and
20110     * unfreezes it upon closing. This is typically used when doing surgery on
20111     * app code/data to prevent the app from running while you're working.
20112     */
20113    private class PackageFreezer implements AutoCloseable {
20114        private final String mPackageName;
20115        private final PackageFreezer[] mChildren;
20116
20117        private final boolean mWeFroze;
20118
20119        private final AtomicBoolean mClosed = new AtomicBoolean();
20120        private final CloseGuard mCloseGuard = CloseGuard.get();
20121
20122        /**
20123         * Create and return a stub freezer that doesn't actually do anything,
20124         * typically used when someone requested
20125         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20126         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20127         */
20128        public PackageFreezer() {
20129            mPackageName = null;
20130            mChildren = null;
20131            mWeFroze = false;
20132            mCloseGuard.open("close");
20133        }
20134
20135        public PackageFreezer(String packageName, int userId, String killReason) {
20136            synchronized (mPackages) {
20137                mPackageName = packageName;
20138                mWeFroze = mFrozenPackages.add(mPackageName);
20139
20140                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20141                if (ps != null) {
20142                    killApplication(ps.name, ps.appId, userId, killReason);
20143                }
20144
20145                final PackageParser.Package p = mPackages.get(packageName);
20146                if (p != null && p.childPackages != null) {
20147                    final int N = p.childPackages.size();
20148                    mChildren = new PackageFreezer[N];
20149                    for (int i = 0; i < N; i++) {
20150                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20151                                userId, killReason);
20152                    }
20153                } else {
20154                    mChildren = null;
20155                }
20156            }
20157            mCloseGuard.open("close");
20158        }
20159
20160        @Override
20161        protected void finalize() throws Throwable {
20162            try {
20163                mCloseGuard.warnIfOpen();
20164                close();
20165            } finally {
20166                super.finalize();
20167            }
20168        }
20169
20170        @Override
20171        public void close() {
20172            mCloseGuard.close();
20173            if (mClosed.compareAndSet(false, true)) {
20174                synchronized (mPackages) {
20175                    if (mWeFroze) {
20176                        mFrozenPackages.remove(mPackageName);
20177                    }
20178
20179                    if (mChildren != null) {
20180                        for (PackageFreezer freezer : mChildren) {
20181                            freezer.close();
20182                        }
20183                    }
20184                }
20185            }
20186        }
20187    }
20188
20189    /**
20190     * Verify that given package is currently frozen.
20191     */
20192    private void checkPackageFrozen(String packageName) {
20193        synchronized (mPackages) {
20194            if (!mFrozenPackages.contains(packageName)) {
20195                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20196            }
20197        }
20198    }
20199
20200    @Override
20201    public int movePackage(final String packageName, final String volumeUuid) {
20202        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20203
20204        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20205        final int moveId = mNextMoveId.getAndIncrement();
20206        mHandler.post(new Runnable() {
20207            @Override
20208            public void run() {
20209                try {
20210                    movePackageInternal(packageName, volumeUuid, moveId, user);
20211                } catch (PackageManagerException e) {
20212                    Slog.w(TAG, "Failed to move " + packageName, e);
20213                    mMoveCallbacks.notifyStatusChanged(moveId,
20214                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20215                }
20216            }
20217        });
20218        return moveId;
20219    }
20220
20221    private void movePackageInternal(final String packageName, final String volumeUuid,
20222            final int moveId, UserHandle user) throws PackageManagerException {
20223        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20224        final PackageManager pm = mContext.getPackageManager();
20225
20226        final boolean currentAsec;
20227        final String currentVolumeUuid;
20228        final File codeFile;
20229        final String installerPackageName;
20230        final String packageAbiOverride;
20231        final int appId;
20232        final String seinfo;
20233        final String label;
20234        final int targetSdkVersion;
20235        final PackageFreezer freezer;
20236        final int[] installedUserIds;
20237
20238        // reader
20239        synchronized (mPackages) {
20240            final PackageParser.Package pkg = mPackages.get(packageName);
20241            final PackageSetting ps = mSettings.mPackages.get(packageName);
20242            if (pkg == null || ps == null) {
20243                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20244            }
20245
20246            if (pkg.applicationInfo.isSystemApp()) {
20247                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20248                        "Cannot move system application");
20249            }
20250
20251            if (pkg.applicationInfo.isExternalAsec()) {
20252                currentAsec = true;
20253                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20254            } else if (pkg.applicationInfo.isForwardLocked()) {
20255                currentAsec = true;
20256                currentVolumeUuid = "forward_locked";
20257            } else {
20258                currentAsec = false;
20259                currentVolumeUuid = ps.volumeUuid;
20260
20261                final File probe = new File(pkg.codePath);
20262                final File probeOat = new File(probe, "oat");
20263                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20264                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20265                            "Move only supported for modern cluster style installs");
20266                }
20267            }
20268
20269            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20270                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20271                        "Package already moved to " + volumeUuid);
20272            }
20273            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20274                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20275                        "Device admin cannot be moved");
20276            }
20277
20278            if (mFrozenPackages.contains(packageName)) {
20279                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20280                        "Failed to move already frozen package");
20281            }
20282
20283            codeFile = new File(pkg.codePath);
20284            installerPackageName = ps.installerPackageName;
20285            packageAbiOverride = ps.cpuAbiOverrideString;
20286            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20287            seinfo = pkg.applicationInfo.seinfo;
20288            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20289            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20290            freezer = freezePackage(packageName, "movePackageInternal");
20291            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20292        }
20293
20294        final Bundle extras = new Bundle();
20295        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20296        extras.putString(Intent.EXTRA_TITLE, label);
20297        mMoveCallbacks.notifyCreated(moveId, extras);
20298
20299        int installFlags;
20300        final boolean moveCompleteApp;
20301        final File measurePath;
20302
20303        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20304            installFlags = INSTALL_INTERNAL;
20305            moveCompleteApp = !currentAsec;
20306            measurePath = Environment.getDataAppDirectory(volumeUuid);
20307        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20308            installFlags = INSTALL_EXTERNAL;
20309            moveCompleteApp = false;
20310            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20311        } else {
20312            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20313            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20314                    || !volume.isMountedWritable()) {
20315                freezer.close();
20316                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20317                        "Move location not mounted private volume");
20318            }
20319
20320            Preconditions.checkState(!currentAsec);
20321
20322            installFlags = INSTALL_INTERNAL;
20323            moveCompleteApp = true;
20324            measurePath = Environment.getDataAppDirectory(volumeUuid);
20325        }
20326
20327        final PackageStats stats = new PackageStats(null, -1);
20328        synchronized (mInstaller) {
20329            for (int userId : installedUserIds) {
20330                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20331                    freezer.close();
20332                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20333                            "Failed to measure package size");
20334                }
20335            }
20336        }
20337
20338        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20339                + stats.dataSize);
20340
20341        final long startFreeBytes = measurePath.getFreeSpace();
20342        final long sizeBytes;
20343        if (moveCompleteApp) {
20344            sizeBytes = stats.codeSize + stats.dataSize;
20345        } else {
20346            sizeBytes = stats.codeSize;
20347        }
20348
20349        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20350            freezer.close();
20351            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20352                    "Not enough free space to move");
20353        }
20354
20355        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20356
20357        final CountDownLatch installedLatch = new CountDownLatch(1);
20358        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20359            @Override
20360            public void onUserActionRequired(Intent intent) throws RemoteException {
20361                throw new IllegalStateException();
20362            }
20363
20364            @Override
20365            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20366                    Bundle extras) throws RemoteException {
20367                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20368                        + PackageManager.installStatusToString(returnCode, msg));
20369
20370                installedLatch.countDown();
20371                freezer.close();
20372
20373                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20374                switch (status) {
20375                    case PackageInstaller.STATUS_SUCCESS:
20376                        mMoveCallbacks.notifyStatusChanged(moveId,
20377                                PackageManager.MOVE_SUCCEEDED);
20378                        break;
20379                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20380                        mMoveCallbacks.notifyStatusChanged(moveId,
20381                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20382                        break;
20383                    default:
20384                        mMoveCallbacks.notifyStatusChanged(moveId,
20385                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20386                        break;
20387                }
20388            }
20389        };
20390
20391        final MoveInfo move;
20392        if (moveCompleteApp) {
20393            // Kick off a thread to report progress estimates
20394            new Thread() {
20395                @Override
20396                public void run() {
20397                    while (true) {
20398                        try {
20399                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20400                                break;
20401                            }
20402                        } catch (InterruptedException ignored) {
20403                        }
20404
20405                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20406                        final int progress = 10 + (int) MathUtils.constrain(
20407                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20408                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20409                    }
20410                }
20411            }.start();
20412
20413            final String dataAppName = codeFile.getName();
20414            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20415                    dataAppName, appId, seinfo, targetSdkVersion);
20416        } else {
20417            move = null;
20418        }
20419
20420        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20421
20422        final Message msg = mHandler.obtainMessage(INIT_COPY);
20423        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20424        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20425                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20426                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20427        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20428        msg.obj = params;
20429
20430        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20431                System.identityHashCode(msg.obj));
20432        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20433                System.identityHashCode(msg.obj));
20434
20435        mHandler.sendMessage(msg);
20436    }
20437
20438    @Override
20439    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20440        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20441
20442        final int realMoveId = mNextMoveId.getAndIncrement();
20443        final Bundle extras = new Bundle();
20444        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20445        mMoveCallbacks.notifyCreated(realMoveId, extras);
20446
20447        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20448            @Override
20449            public void onCreated(int moveId, Bundle extras) {
20450                // Ignored
20451            }
20452
20453            @Override
20454            public void onStatusChanged(int moveId, int status, long estMillis) {
20455                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20456            }
20457        };
20458
20459        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20460        storage.setPrimaryStorageUuid(volumeUuid, callback);
20461        return realMoveId;
20462    }
20463
20464    @Override
20465    public int getMoveStatus(int moveId) {
20466        mContext.enforceCallingOrSelfPermission(
20467                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20468        return mMoveCallbacks.mLastStatus.get(moveId);
20469    }
20470
20471    @Override
20472    public void registerMoveCallback(IPackageMoveObserver callback) {
20473        mContext.enforceCallingOrSelfPermission(
20474                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20475        mMoveCallbacks.register(callback);
20476    }
20477
20478    @Override
20479    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20480        mContext.enforceCallingOrSelfPermission(
20481                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20482        mMoveCallbacks.unregister(callback);
20483    }
20484
20485    @Override
20486    public boolean setInstallLocation(int loc) {
20487        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20488                null);
20489        if (getInstallLocation() == loc) {
20490            return true;
20491        }
20492        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20493                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20494            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20495                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20496            return true;
20497        }
20498        return false;
20499   }
20500
20501    @Override
20502    public int getInstallLocation() {
20503        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20504                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20505                PackageHelper.APP_INSTALL_AUTO);
20506    }
20507
20508    /** Called by UserManagerService */
20509    void cleanUpUser(UserManagerService userManager, int userHandle) {
20510        synchronized (mPackages) {
20511            mDirtyUsers.remove(userHandle);
20512            mUserNeedsBadging.delete(userHandle);
20513            mSettings.removeUserLPw(userHandle);
20514            mPendingBroadcasts.remove(userHandle);
20515            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20516            removeUnusedPackagesLPw(userManager, userHandle);
20517        }
20518    }
20519
20520    /**
20521     * We're removing userHandle and would like to remove any downloaded packages
20522     * that are no longer in use by any other user.
20523     * @param userHandle the user being removed
20524     */
20525    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20526        final boolean DEBUG_CLEAN_APKS = false;
20527        int [] users = userManager.getUserIds();
20528        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20529        while (psit.hasNext()) {
20530            PackageSetting ps = psit.next();
20531            if (ps.pkg == null) {
20532                continue;
20533            }
20534            final String packageName = ps.pkg.packageName;
20535            // Skip over if system app
20536            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20537                continue;
20538            }
20539            if (DEBUG_CLEAN_APKS) {
20540                Slog.i(TAG, "Checking package " + packageName);
20541            }
20542            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20543            if (keep) {
20544                if (DEBUG_CLEAN_APKS) {
20545                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20546                }
20547            } else {
20548                for (int i = 0; i < users.length; i++) {
20549                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20550                        keep = true;
20551                        if (DEBUG_CLEAN_APKS) {
20552                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20553                                    + users[i]);
20554                        }
20555                        break;
20556                    }
20557                }
20558            }
20559            if (!keep) {
20560                if (DEBUG_CLEAN_APKS) {
20561                    Slog.i(TAG, "  Removing package " + packageName);
20562                }
20563                mHandler.post(new Runnable() {
20564                    public void run() {
20565                        deletePackageX(packageName, userHandle, 0);
20566                    } //end run
20567                });
20568            }
20569        }
20570    }
20571
20572    /** Called by UserManagerService */
20573    void createNewUser(int userId) {
20574        synchronized (mInstallLock) {
20575            mSettings.createNewUserLI(this, mInstaller, userId);
20576        }
20577        synchronized (mPackages) {
20578            scheduleWritePackageRestrictionsLocked(userId);
20579            scheduleWritePackageListLocked(userId);
20580            applyFactoryDefaultBrowserLPw(userId);
20581            primeDomainVerificationsLPw(userId);
20582        }
20583    }
20584
20585    void onNewUserCreated(final int userId) {
20586        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20587        // If permission review for legacy apps is required, we represent
20588        // dagerous permissions for such apps as always granted runtime
20589        // permissions to keep per user flag state whether review is needed.
20590        // Hence, if a new user is added we have to propagate dangerous
20591        // permission grants for these legacy apps.
20592        if (mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) {
20593            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20594                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20595        }
20596    }
20597
20598    @Override
20599    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20600        mContext.enforceCallingOrSelfPermission(
20601                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20602                "Only package verification agents can read the verifier device identity");
20603
20604        synchronized (mPackages) {
20605            return mSettings.getVerifierDeviceIdentityLPw();
20606        }
20607    }
20608
20609    @Override
20610    public void setPermissionEnforced(String permission, boolean enforced) {
20611        // TODO: Now that we no longer change GID for storage, this should to away.
20612        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20613                "setPermissionEnforced");
20614        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20615            synchronized (mPackages) {
20616                if (mSettings.mReadExternalStorageEnforced == null
20617                        || mSettings.mReadExternalStorageEnforced != enforced) {
20618                    mSettings.mReadExternalStorageEnforced = enforced;
20619                    mSettings.writeLPr();
20620                }
20621            }
20622            // kill any non-foreground processes so we restart them and
20623            // grant/revoke the GID.
20624            final IActivityManager am = ActivityManagerNative.getDefault();
20625            if (am != null) {
20626                final long token = Binder.clearCallingIdentity();
20627                try {
20628                    am.killProcessesBelowForeground("setPermissionEnforcement");
20629                } catch (RemoteException e) {
20630                } finally {
20631                    Binder.restoreCallingIdentity(token);
20632                }
20633            }
20634        } else {
20635            throw new IllegalArgumentException("No selective enforcement for " + permission);
20636        }
20637    }
20638
20639    @Override
20640    @Deprecated
20641    public boolean isPermissionEnforced(String permission) {
20642        return true;
20643    }
20644
20645    @Override
20646    public boolean isStorageLow() {
20647        final long token = Binder.clearCallingIdentity();
20648        try {
20649            final DeviceStorageMonitorInternal
20650                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20651            if (dsm != null) {
20652                return dsm.isMemoryLow();
20653            } else {
20654                return false;
20655            }
20656        } finally {
20657            Binder.restoreCallingIdentity(token);
20658        }
20659    }
20660
20661    @Override
20662    public IPackageInstaller getPackageInstaller() {
20663        return mInstallerService;
20664    }
20665
20666    private boolean userNeedsBadging(int userId) {
20667        int index = mUserNeedsBadging.indexOfKey(userId);
20668        if (index < 0) {
20669            final UserInfo userInfo;
20670            final long token = Binder.clearCallingIdentity();
20671            try {
20672                userInfo = sUserManager.getUserInfo(userId);
20673            } finally {
20674                Binder.restoreCallingIdentity(token);
20675            }
20676            final boolean b;
20677            if (userInfo != null && userInfo.isManagedProfile()) {
20678                b = true;
20679            } else {
20680                b = false;
20681            }
20682            mUserNeedsBadging.put(userId, b);
20683            return b;
20684        }
20685        return mUserNeedsBadging.valueAt(index);
20686    }
20687
20688    @Override
20689    public KeySet getKeySetByAlias(String packageName, String alias) {
20690        if (packageName == null || alias == null) {
20691            return null;
20692        }
20693        synchronized(mPackages) {
20694            final PackageParser.Package pkg = mPackages.get(packageName);
20695            if (pkg == null) {
20696                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20697                throw new IllegalArgumentException("Unknown package: " + packageName);
20698            }
20699            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20700            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20701        }
20702    }
20703
20704    @Override
20705    public KeySet getSigningKeySet(String packageName) {
20706        if (packageName == null) {
20707            return null;
20708        }
20709        synchronized(mPackages) {
20710            final PackageParser.Package pkg = mPackages.get(packageName);
20711            if (pkg == null) {
20712                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20713                throw new IllegalArgumentException("Unknown package: " + packageName);
20714            }
20715            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20716                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20717                throw new SecurityException("May not access signing KeySet of other apps.");
20718            }
20719            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20720            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20721        }
20722    }
20723
20724    @Override
20725    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20726        if (packageName == null || ks == null) {
20727            return false;
20728        }
20729        synchronized(mPackages) {
20730            final PackageParser.Package pkg = mPackages.get(packageName);
20731            if (pkg == null) {
20732                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20733                throw new IllegalArgumentException("Unknown package: " + packageName);
20734            }
20735            IBinder ksh = ks.getToken();
20736            if (ksh instanceof KeySetHandle) {
20737                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20738                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20739            }
20740            return false;
20741        }
20742    }
20743
20744    @Override
20745    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20746        if (packageName == null || ks == null) {
20747            return false;
20748        }
20749        synchronized(mPackages) {
20750            final PackageParser.Package pkg = mPackages.get(packageName);
20751            if (pkg == null) {
20752                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20753                throw new IllegalArgumentException("Unknown package: " + packageName);
20754            }
20755            IBinder ksh = ks.getToken();
20756            if (ksh instanceof KeySetHandle) {
20757                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20758                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20759            }
20760            return false;
20761        }
20762    }
20763
20764    private void deletePackageIfUnusedLPr(final String packageName) {
20765        PackageSetting ps = mSettings.mPackages.get(packageName);
20766        if (ps == null) {
20767            return;
20768        }
20769        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20770            // TODO Implement atomic delete if package is unused
20771            // It is currently possible that the package will be deleted even if it is installed
20772            // after this method returns.
20773            mHandler.post(new Runnable() {
20774                public void run() {
20775                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20776                }
20777            });
20778        }
20779    }
20780
20781    /**
20782     * Check and throw if the given before/after packages would be considered a
20783     * downgrade.
20784     */
20785    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20786            throws PackageManagerException {
20787        if (after.versionCode < before.mVersionCode) {
20788            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20789                    "Update version code " + after.versionCode + " is older than current "
20790                    + before.mVersionCode);
20791        } else if (after.versionCode == before.mVersionCode) {
20792            if (after.baseRevisionCode < before.baseRevisionCode) {
20793                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20794                        "Update base revision code " + after.baseRevisionCode
20795                        + " is older than current " + before.baseRevisionCode);
20796            }
20797
20798            if (!ArrayUtils.isEmpty(after.splitNames)) {
20799                for (int i = 0; i < after.splitNames.length; i++) {
20800                    final String splitName = after.splitNames[i];
20801                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20802                    if (j != -1) {
20803                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20804                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20805                                    "Update split " + splitName + " revision code "
20806                                    + after.splitRevisionCodes[i] + " is older than current "
20807                                    + before.splitRevisionCodes[j]);
20808                        }
20809                    }
20810                }
20811            }
20812        }
20813    }
20814
20815    private static class MoveCallbacks extends Handler {
20816        private static final int MSG_CREATED = 1;
20817        private static final int MSG_STATUS_CHANGED = 2;
20818
20819        private final RemoteCallbackList<IPackageMoveObserver>
20820                mCallbacks = new RemoteCallbackList<>();
20821
20822        private final SparseIntArray mLastStatus = new SparseIntArray();
20823
20824        public MoveCallbacks(Looper looper) {
20825            super(looper);
20826        }
20827
20828        public void register(IPackageMoveObserver callback) {
20829            mCallbacks.register(callback);
20830        }
20831
20832        public void unregister(IPackageMoveObserver callback) {
20833            mCallbacks.unregister(callback);
20834        }
20835
20836        @Override
20837        public void handleMessage(Message msg) {
20838            final SomeArgs args = (SomeArgs) msg.obj;
20839            final int n = mCallbacks.beginBroadcast();
20840            for (int i = 0; i < n; i++) {
20841                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20842                try {
20843                    invokeCallback(callback, msg.what, args);
20844                } catch (RemoteException ignored) {
20845                }
20846            }
20847            mCallbacks.finishBroadcast();
20848            args.recycle();
20849        }
20850
20851        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20852                throws RemoteException {
20853            switch (what) {
20854                case MSG_CREATED: {
20855                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20856                    break;
20857                }
20858                case MSG_STATUS_CHANGED: {
20859                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20860                    break;
20861                }
20862            }
20863        }
20864
20865        private void notifyCreated(int moveId, Bundle extras) {
20866            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20867
20868            final SomeArgs args = SomeArgs.obtain();
20869            args.argi1 = moveId;
20870            args.arg2 = extras;
20871            obtainMessage(MSG_CREATED, args).sendToTarget();
20872        }
20873
20874        private void notifyStatusChanged(int moveId, int status) {
20875            notifyStatusChanged(moveId, status, -1);
20876        }
20877
20878        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20879            Slog.v(TAG, "Move " + moveId + " status " + status);
20880
20881            final SomeArgs args = SomeArgs.obtain();
20882            args.argi1 = moveId;
20883            args.argi2 = status;
20884            args.arg3 = estMillis;
20885            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20886
20887            synchronized (mLastStatus) {
20888                mLastStatus.put(moveId, status);
20889            }
20890        }
20891    }
20892
20893    private final static class OnPermissionChangeListeners extends Handler {
20894        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20895
20896        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20897                new RemoteCallbackList<>();
20898
20899        public OnPermissionChangeListeners(Looper looper) {
20900            super(looper);
20901        }
20902
20903        @Override
20904        public void handleMessage(Message msg) {
20905            switch (msg.what) {
20906                case MSG_ON_PERMISSIONS_CHANGED: {
20907                    final int uid = msg.arg1;
20908                    handleOnPermissionsChanged(uid);
20909                } break;
20910            }
20911        }
20912
20913        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20914            mPermissionListeners.register(listener);
20915
20916        }
20917
20918        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20919            mPermissionListeners.unregister(listener);
20920        }
20921
20922        public void onPermissionsChanged(int uid) {
20923            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20924                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20925            }
20926        }
20927
20928        private void handleOnPermissionsChanged(int uid) {
20929            final int count = mPermissionListeners.beginBroadcast();
20930            try {
20931                for (int i = 0; i < count; i++) {
20932                    IOnPermissionsChangeListener callback = mPermissionListeners
20933                            .getBroadcastItem(i);
20934                    try {
20935                        callback.onPermissionsChanged(uid);
20936                    } catch (RemoteException e) {
20937                        Log.e(TAG, "Permission listener is dead", e);
20938                    }
20939                }
20940            } finally {
20941                mPermissionListeners.finishBroadcast();
20942            }
20943        }
20944    }
20945
20946    private class PackageManagerInternalImpl extends PackageManagerInternal {
20947        @Override
20948        public void setLocationPackagesProvider(PackagesProvider provider) {
20949            synchronized (mPackages) {
20950                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20951            }
20952        }
20953
20954        @Override
20955        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20956            synchronized (mPackages) {
20957                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20958            }
20959        }
20960
20961        @Override
20962        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20963            synchronized (mPackages) {
20964                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20965            }
20966        }
20967
20968        @Override
20969        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20970            synchronized (mPackages) {
20971                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20972            }
20973        }
20974
20975        @Override
20976        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20977            synchronized (mPackages) {
20978                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20979            }
20980        }
20981
20982        @Override
20983        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20984            synchronized (mPackages) {
20985                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20986            }
20987        }
20988
20989        @Override
20990        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20991            synchronized (mPackages) {
20992                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20993                        packageName, userId);
20994            }
20995        }
20996
20997        @Override
20998        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20999            synchronized (mPackages) {
21000                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21001                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21002                        packageName, userId);
21003            }
21004        }
21005
21006        @Override
21007        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21008            synchronized (mPackages) {
21009                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21010                        packageName, userId);
21011            }
21012        }
21013
21014        @Override
21015        public void setKeepUninstalledPackages(final List<String> packageList) {
21016            Preconditions.checkNotNull(packageList);
21017            List<String> removedFromList = null;
21018            synchronized (mPackages) {
21019                if (mKeepUninstalledPackages != null) {
21020                    final int packagesCount = mKeepUninstalledPackages.size();
21021                    for (int i = 0; i < packagesCount; i++) {
21022                        String oldPackage = mKeepUninstalledPackages.get(i);
21023                        if (packageList != null && packageList.contains(oldPackage)) {
21024                            continue;
21025                        }
21026                        if (removedFromList == null) {
21027                            removedFromList = new ArrayList<>();
21028                        }
21029                        removedFromList.add(oldPackage);
21030                    }
21031                }
21032                mKeepUninstalledPackages = new ArrayList<>(packageList);
21033                if (removedFromList != null) {
21034                    final int removedCount = removedFromList.size();
21035                    for (int i = 0; i < removedCount; i++) {
21036                        deletePackageIfUnusedLPr(removedFromList.get(i));
21037                    }
21038                }
21039            }
21040        }
21041
21042        @Override
21043        public boolean isPermissionsReviewRequired(String packageName, int userId) {
21044            synchronized (mPackages) {
21045                // If we do not support permission review, done.
21046                if (!mPermissionReviewRequired && !Build.PERMISSIONS_REVIEW_REQUIRED) {
21047                    return false;
21048                }
21049
21050                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21051                if (packageSetting == null) {
21052                    return false;
21053                }
21054
21055                // Permission review applies only to apps not supporting the new permission model.
21056                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21057                    return false;
21058                }
21059
21060                // Legacy apps have the permission and get user consent on launch.
21061                PermissionsState permissionsState = packageSetting.getPermissionsState();
21062                return permissionsState.isPermissionReviewRequired(userId);
21063            }
21064        }
21065
21066        @Override
21067        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21068            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21069        }
21070
21071        @Override
21072        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21073                int userId) {
21074            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21075        }
21076
21077        @Override
21078        public void setDeviceAndProfileOwnerPackages(
21079                int deviceOwnerUserId, String deviceOwnerPackage,
21080                SparseArray<String> profileOwnerPackages) {
21081            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21082                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21083        }
21084
21085        @Override
21086        public boolean isPackageDataProtected(int userId, String packageName) {
21087            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21088        }
21089
21090        @Override
21091        public boolean wasPackageEverLaunched(String packageName, int userId) {
21092            synchronized (mPackages) {
21093                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21094            }
21095        }
21096
21097        @Override
21098        public String getNameForUid(int uid) {
21099            return PackageManagerService.this.getNameForUid(uid);
21100        }
21101    }
21102
21103    @Override
21104    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21105        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21106        synchronized (mPackages) {
21107            final long identity = Binder.clearCallingIdentity();
21108            try {
21109                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21110                        packageNames, userId);
21111            } finally {
21112                Binder.restoreCallingIdentity(identity);
21113            }
21114        }
21115    }
21116
21117    @Override
21118    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
21119        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
21120        synchronized (mPackages) {
21121            final long identity = Binder.clearCallingIdentity();
21122            try {
21123                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
21124                        packageNames, userId);
21125            } finally {
21126                Binder.restoreCallingIdentity(identity);
21127            }
21128        }
21129    }
21130
21131    private static void enforceSystemOrPhoneCaller(String tag) {
21132        int callingUid = Binder.getCallingUid();
21133        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21134            throw new SecurityException(
21135                    "Cannot call " + tag + " from UID " + callingUid);
21136        }
21137    }
21138
21139    boolean isHistoricalPackageUsageAvailable() {
21140        return mPackageUsage.isHistoricalPackageUsageAvailable();
21141    }
21142
21143    /**
21144     * Return a <b>copy</b> of the collection of packages known to the package manager.
21145     * @return A copy of the values of mPackages.
21146     */
21147    Collection<PackageParser.Package> getPackages() {
21148        synchronized (mPackages) {
21149            return new ArrayList<>(mPackages.values());
21150        }
21151    }
21152
21153    /**
21154     * Logs process start information (including base APK hash) to the security log.
21155     * @hide
21156     */
21157    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21158            String apkFile, int pid) {
21159        if (!SecurityLog.isLoggingEnabled()) {
21160            return;
21161        }
21162        Bundle data = new Bundle();
21163        data.putLong("startTimestamp", System.currentTimeMillis());
21164        data.putString("processName", processName);
21165        data.putInt("uid", uid);
21166        data.putString("seinfo", seinfo);
21167        data.putString("apkFile", apkFile);
21168        data.putInt("pid", pid);
21169        Message msg = mProcessLoggingHandler.obtainMessage(
21170                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21171        msg.setData(data);
21172        mProcessLoggingHandler.sendMessage(msg);
21173    }
21174
21175    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21176        return mCompilerStats.getPackageStats(pkgName);
21177    }
21178
21179    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21180        return getOrCreateCompilerPackageStats(pkg.packageName);
21181    }
21182
21183    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21184        return mCompilerStats.getOrCreatePackageStats(pkgName);
21185    }
21186
21187    public void deleteCompilerPackageStats(String pkgName) {
21188        mCompilerStats.deletePackageStats(pkgName);
21189    }
21190}
21191