PackageManagerService.java revision 36ba022316e61f28581c946fcbb9b7123a14da75
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_SKU_PROPERTY is set, search for runtime resource overlay APKs in
473     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_SKU_PROPERTY> rather than in
474     * VENDOR_OVERLAY_DIR.
475     */
476    private static final String VENDOR_OVERLAY_SKU_PROPERTY = "ro.boot.vendor.overlay.sku";
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    /** Special library name that skips shared libraries check during compilation. */
528    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
529
530    final ServiceThread mHandlerThread;
531
532    final PackageHandler mHandler;
533
534    private final ProcessLoggingHandler mProcessLoggingHandler;
535
536    /**
537     * Messages for {@link #mHandler} that need to wait for system ready before
538     * being dispatched.
539     */
540    private ArrayList<Message> mPostSystemReadyMessages;
541
542    final int mSdkVersion = Build.VERSION.SDK_INT;
543
544    final Context mContext;
545    final boolean mFactoryTest;
546    final boolean mOnlyCore;
547    final DisplayMetrics mMetrics;
548    final int mDefParseFlags;
549    final String[] mSeparateProcesses;
550    final boolean mIsUpgrade;
551    final boolean mIsPreNUpgrade;
552    final boolean mIsPreNMR1Upgrade;
553
554    @GuardedBy("mPackages")
555    private boolean mDexOptDialogShown;
556
557    /** The location for ASEC container files on internal storage. */
558    final String mAsecInternalPath;
559
560    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
561    // LOCK HELD.  Can be called with mInstallLock held.
562    @GuardedBy("mInstallLock")
563    final Installer mInstaller;
564
565    /** Directory where installed third-party apps stored */
566    final File mAppInstallDir;
567    final File mEphemeralInstallDir;
568
569    /**
570     * Directory to which applications installed internally have their
571     * 32 bit native libraries copied.
572     */
573    private File mAppLib32InstallDir;
574
575    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
576    // apps.
577    final File mDrmAppPrivateInstallDir;
578
579    // ----------------------------------------------------------------
580
581    // Lock for state used when installing and doing other long running
582    // operations.  Methods that must be called with this lock held have
583    // the suffix "LI".
584    final Object mInstallLock = new Object();
585
586    // ----------------------------------------------------------------
587
588    // Keys are String (package name), values are Package.  This also serves
589    // as the lock for the global state.  Methods that must be called with
590    // this lock held have the prefix "LP".
591    @GuardedBy("mPackages")
592    final ArrayMap<String, PackageParser.Package> mPackages =
593            new ArrayMap<String, PackageParser.Package>();
594
595    final ArrayMap<String, Set<String>> mKnownCodebase =
596            new ArrayMap<String, Set<String>>();
597
598    // Tracks available target package names -> overlay package paths.
599    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
600        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
601
602    /**
603     * Tracks new system packages [received in an OTA] that we expect to
604     * find updated user-installed versions. Keys are package name, values
605     * are package location.
606     */
607    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
608    /**
609     * Tracks high priority intent filters for protected actions. During boot, certain
610     * filter actions are protected and should never be allowed to have a high priority
611     * intent filter for them. However, there is one, and only one exception -- the
612     * setup wizard. It must be able to define a high priority intent filter for these
613     * actions to ensure there are no escapes from the wizard. We need to delay processing
614     * of these during boot as we need to look at all of the system packages in order
615     * to know which component is the setup wizard.
616     */
617    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
618    /**
619     * Whether or not processing protected filters should be deferred.
620     */
621    private boolean mDeferProtectedFilters = true;
622
623    /**
624     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
625     */
626    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
627    /**
628     * Whether or not system app permissions should be promoted from install to runtime.
629     */
630    boolean mPromoteSystemApps;
631
632    @GuardedBy("mPackages")
633    final Settings mSettings;
634
635    /**
636     * Set of package names that are currently "frozen", which means active
637     * surgery is being done on the code/data for that package. The platform
638     * will refuse to launch frozen packages to avoid race conditions.
639     *
640     * @see PackageFreezer
641     */
642    @GuardedBy("mPackages")
643    final ArraySet<String> mFrozenPackages = new ArraySet<>();
644
645    final ProtectedPackages mProtectedPackages;
646
647    boolean mFirstBoot;
648
649    // System configuration read by SystemConfig.
650    final int[] mGlobalGids;
651    final SparseArray<ArraySet<String>> mSystemPermissions;
652    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
653
654    // If mac_permissions.xml was found for seinfo labeling.
655    boolean mFoundPolicyFile;
656
657    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
658
659    public static final class SharedLibraryEntry {
660        public final String path;
661        public final String apk;
662
663        SharedLibraryEntry(String _path, String _apk) {
664            path = _path;
665            apk = _apk;
666        }
667    }
668
669    // Currently known shared libraries.
670    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
671            new ArrayMap<String, SharedLibraryEntry>();
672
673    // All available activities, for your resolving pleasure.
674    final ActivityIntentResolver mActivities =
675            new ActivityIntentResolver();
676
677    // All available receivers, for your resolving pleasure.
678    final ActivityIntentResolver mReceivers =
679            new ActivityIntentResolver();
680
681    // All available services, for your resolving pleasure.
682    final ServiceIntentResolver mServices = new ServiceIntentResolver();
683
684    // All available providers, for your resolving pleasure.
685    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
686
687    // Mapping from provider base names (first directory in content URI codePath)
688    // to the provider information.
689    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
690            new ArrayMap<String, PackageParser.Provider>();
691
692    // Mapping from instrumentation class names to info about them.
693    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
694            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
695
696    // Mapping from permission names to info about them.
697    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
698            new ArrayMap<String, PackageParser.PermissionGroup>();
699
700    // Packages whose data we have transfered into another package, thus
701    // should no longer exist.
702    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
703
704    // Broadcast actions that are only available to the system.
705    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
706
707    /** List of packages waiting for verification. */
708    final SparseArray<PackageVerificationState> mPendingVerification
709            = new SparseArray<PackageVerificationState>();
710
711    /** Set of packages associated with each app op permission. */
712    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
713
714    final PackageInstallerService mInstallerService;
715
716    private final PackageDexOptimizer mPackageDexOptimizer;
717    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
718    // is used by other apps).
719    private final DexManager mDexManager;
720
721    private AtomicInteger mNextMoveId = new AtomicInteger();
722    private final MoveCallbacks mMoveCallbacks;
723
724    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
725
726    // Cache of users who need badging.
727    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
728
729    /** Token for keys in mPendingVerification. */
730    private int mPendingVerificationToken = 0;
731
732    volatile boolean mSystemReady;
733    volatile boolean mSafeMode;
734    volatile boolean mHasSystemUidErrors;
735
736    ApplicationInfo mAndroidApplication;
737    final ActivityInfo mResolveActivity = new ActivityInfo();
738    final ResolveInfo mResolveInfo = new ResolveInfo();
739    ComponentName mResolveComponentName;
740    PackageParser.Package mPlatformPackage;
741    ComponentName mCustomResolverComponentName;
742
743    boolean mResolverReplaced = false;
744
745    private final @Nullable ComponentName mIntentFilterVerifierComponent;
746    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
747
748    private int mIntentFilterVerificationToken = 0;
749
750    /** Component that knows whether or not an ephemeral application exists */
751    final ComponentName mEphemeralResolverComponent;
752    /** The service connection to the ephemeral resolver */
753    final EphemeralResolverConnection mEphemeralResolverConnection;
754
755    /** Component used to install ephemeral applications */
756    final ComponentName mEphemeralInstallerComponent;
757    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
758    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
759
760    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
761            = new SparseArray<IntentFilterVerificationState>();
762
763    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
764
765    // List of packages names to keep cached, even if they are uninstalled for all users
766    private List<String> mKeepUninstalledPackages;
767
768    private UserManagerInternal mUserManagerInternal;
769
770    private static class IFVerificationParams {
771        PackageParser.Package pkg;
772        boolean replacing;
773        int userId;
774        int verifierUid;
775
776        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
777                int _userId, int _verifierUid) {
778            pkg = _pkg;
779            replacing = _replacing;
780            userId = _userId;
781            replacing = _replacing;
782            verifierUid = _verifierUid;
783        }
784    }
785
786    private interface IntentFilterVerifier<T extends IntentFilter> {
787        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
788                                               T filter, String packageName);
789        void startVerifications(int userId);
790        void receiveVerificationResponse(int verificationId);
791    }
792
793    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
794        private Context mContext;
795        private ComponentName mIntentFilterVerifierComponent;
796        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
797
798        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
799            mContext = context;
800            mIntentFilterVerifierComponent = verifierComponent;
801        }
802
803        private String getDefaultScheme() {
804            return IntentFilter.SCHEME_HTTPS;
805        }
806
807        @Override
808        public void startVerifications(int userId) {
809            // Launch verifications requests
810            int count = mCurrentIntentFilterVerifications.size();
811            for (int n=0; n<count; n++) {
812                int verificationId = mCurrentIntentFilterVerifications.get(n);
813                final IntentFilterVerificationState ivs =
814                        mIntentFilterVerificationStates.get(verificationId);
815
816                String packageName = ivs.getPackageName();
817
818                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
819                final int filterCount = filters.size();
820                ArraySet<String> domainsSet = new ArraySet<>();
821                for (int m=0; m<filterCount; m++) {
822                    PackageParser.ActivityIntentInfo filter = filters.get(m);
823                    domainsSet.addAll(filter.getHostsList());
824                }
825                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
826                synchronized (mPackages) {
827                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
828                            packageName, domainsList) != null) {
829                        scheduleWriteSettingsLocked();
830                    }
831                }
832                sendVerificationRequest(userId, verificationId, ivs);
833            }
834            mCurrentIntentFilterVerifications.clear();
835        }
836
837        private void sendVerificationRequest(int userId, int verificationId,
838                IntentFilterVerificationState ivs) {
839
840            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
841            verificationIntent.putExtra(
842                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
843                    verificationId);
844            verificationIntent.putExtra(
845                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
846                    getDefaultScheme());
847            verificationIntent.putExtra(
848                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
849                    ivs.getHostsString());
850            verificationIntent.putExtra(
851                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
852                    ivs.getPackageName());
853            verificationIntent.setComponent(mIntentFilterVerifierComponent);
854            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
855
856            UserHandle user = new UserHandle(userId);
857            mContext.sendBroadcastAsUser(verificationIntent, user);
858            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
859                    "Sending IntentFilter verification broadcast");
860        }
861
862        public void receiveVerificationResponse(int verificationId) {
863            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
864
865            final boolean verified = ivs.isVerified();
866
867            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
868            final int count = filters.size();
869            if (DEBUG_DOMAIN_VERIFICATION) {
870                Slog.i(TAG, "Received verification response " + verificationId
871                        + " for " + count + " filters, verified=" + verified);
872            }
873            for (int n=0; n<count; n++) {
874                PackageParser.ActivityIntentInfo filter = filters.get(n);
875                filter.setVerified(verified);
876
877                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
878                        + " verified with result:" + verified + " and hosts:"
879                        + ivs.getHostsString());
880            }
881
882            mIntentFilterVerificationStates.remove(verificationId);
883
884            final String packageName = ivs.getPackageName();
885            IntentFilterVerificationInfo ivi = null;
886
887            synchronized (mPackages) {
888                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
889            }
890            if (ivi == null) {
891                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
892                        + verificationId + " packageName:" + packageName);
893                return;
894            }
895            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
896                    "Updating IntentFilterVerificationInfo for package " + packageName
897                            +" verificationId:" + verificationId);
898
899            synchronized (mPackages) {
900                if (verified) {
901                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
902                } else {
903                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
904                }
905                scheduleWriteSettingsLocked();
906
907                final int userId = ivs.getUserId();
908                if (userId != UserHandle.USER_ALL) {
909                    final int userStatus =
910                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
911
912                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
913                    boolean needUpdate = false;
914
915                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
916                    // already been set by the User thru the Disambiguation dialog
917                    switch (userStatus) {
918                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
919                            if (verified) {
920                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
921                            } else {
922                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
923                            }
924                            needUpdate = true;
925                            break;
926
927                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
928                            if (verified) {
929                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
930                                needUpdate = true;
931                            }
932                            break;
933
934                        default:
935                            // Nothing to do
936                    }
937
938                    if (needUpdate) {
939                        mSettings.updateIntentFilterVerificationStatusLPw(
940                                packageName, updatedStatus, userId);
941                        scheduleWritePackageRestrictionsLocked(userId);
942                    }
943                }
944            }
945        }
946
947        @Override
948        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
949                    ActivityIntentInfo filter, String packageName) {
950            if (!hasValidDomains(filter)) {
951                return false;
952            }
953            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
954            if (ivs == null) {
955                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
956                        packageName);
957            }
958            if (DEBUG_DOMAIN_VERIFICATION) {
959                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
960            }
961            ivs.addFilter(filter);
962            return true;
963        }
964
965        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
966                int userId, int verificationId, String packageName) {
967            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
968                    verifierUid, userId, packageName);
969            ivs.setPendingState();
970            synchronized (mPackages) {
971                mIntentFilterVerificationStates.append(verificationId, ivs);
972                mCurrentIntentFilterVerifications.add(verificationId);
973            }
974            return ivs;
975        }
976    }
977
978    private static boolean hasValidDomains(ActivityIntentInfo filter) {
979        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
980                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
981                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
982    }
983
984    // Set of pending broadcasts for aggregating enable/disable of components.
985    static class PendingPackageBroadcasts {
986        // for each user id, a map of <package name -> components within that package>
987        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
988
989        public PendingPackageBroadcasts() {
990            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
991        }
992
993        public ArrayList<String> get(int userId, String packageName) {
994            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
995            return packages.get(packageName);
996        }
997
998        public void put(int userId, String packageName, ArrayList<String> components) {
999            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1000            packages.put(packageName, components);
1001        }
1002
1003        public void remove(int userId, String packageName) {
1004            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1005            if (packages != null) {
1006                packages.remove(packageName);
1007            }
1008        }
1009
1010        public void remove(int userId) {
1011            mUidMap.remove(userId);
1012        }
1013
1014        public int userIdCount() {
1015            return mUidMap.size();
1016        }
1017
1018        public int userIdAt(int n) {
1019            return mUidMap.keyAt(n);
1020        }
1021
1022        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1023            return mUidMap.get(userId);
1024        }
1025
1026        public int size() {
1027            // total number of pending broadcast entries across all userIds
1028            int num = 0;
1029            for (int i = 0; i< mUidMap.size(); i++) {
1030                num += mUidMap.valueAt(i).size();
1031            }
1032            return num;
1033        }
1034
1035        public void clear() {
1036            mUidMap.clear();
1037        }
1038
1039        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1040            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1041            if (map == null) {
1042                map = new ArrayMap<String, ArrayList<String>>();
1043                mUidMap.put(userId, map);
1044            }
1045            return map;
1046        }
1047    }
1048    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1049
1050    // Service Connection to remote media container service to copy
1051    // package uri's from external media onto secure containers
1052    // or internal storage.
1053    private IMediaContainerService mContainerService = null;
1054
1055    static final int SEND_PENDING_BROADCAST = 1;
1056    static final int MCS_BOUND = 3;
1057    static final int END_COPY = 4;
1058    static final int INIT_COPY = 5;
1059    static final int MCS_UNBIND = 6;
1060    static final int START_CLEANING_PACKAGE = 7;
1061    static final int FIND_INSTALL_LOC = 8;
1062    static final int POST_INSTALL = 9;
1063    static final int MCS_RECONNECT = 10;
1064    static final int MCS_GIVE_UP = 11;
1065    static final int UPDATED_MEDIA_STATUS = 12;
1066    static final int WRITE_SETTINGS = 13;
1067    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1068    static final int PACKAGE_VERIFIED = 15;
1069    static final int CHECK_PENDING_VERIFICATION = 16;
1070    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1071    static final int INTENT_FILTER_VERIFIED = 18;
1072    static final int WRITE_PACKAGE_LIST = 19;
1073
1074    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1075
1076    // Delay time in millisecs
1077    static final int BROADCAST_DELAY = 10 * 1000;
1078
1079    static UserManagerService sUserManager;
1080
1081    // Stores a list of users whose package restrictions file needs to be updated
1082    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1083
1084    final private DefaultContainerConnection mDefContainerConn =
1085            new DefaultContainerConnection();
1086    class DefaultContainerConnection implements ServiceConnection {
1087        public void onServiceConnected(ComponentName name, IBinder service) {
1088            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1089            IMediaContainerService imcs =
1090                IMediaContainerService.Stub.asInterface(service);
1091            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1092        }
1093
1094        public void onServiceDisconnected(ComponentName name) {
1095            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1096        }
1097    }
1098
1099    // Recordkeeping of restore-after-install operations that are currently in flight
1100    // between the Package Manager and the Backup Manager
1101    static class PostInstallData {
1102        public InstallArgs args;
1103        public PackageInstalledInfo res;
1104
1105        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1106            args = _a;
1107            res = _r;
1108        }
1109    }
1110
1111    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1112    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1113
1114    // XML tags for backup/restore of various bits of state
1115    private static final String TAG_PREFERRED_BACKUP = "pa";
1116    private static final String TAG_DEFAULT_APPS = "da";
1117    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1118
1119    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1120    private static final String TAG_ALL_GRANTS = "rt-grants";
1121    private static final String TAG_GRANT = "grant";
1122    private static final String ATTR_PACKAGE_NAME = "pkg";
1123
1124    private static final String TAG_PERMISSION = "perm";
1125    private static final String ATTR_PERMISSION_NAME = "name";
1126    private static final String ATTR_IS_GRANTED = "g";
1127    private static final String ATTR_USER_SET = "set";
1128    private static final String ATTR_USER_FIXED = "fixed";
1129    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1130
1131    // System/policy permission grants are not backed up
1132    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1133            FLAG_PERMISSION_POLICY_FIXED
1134            | FLAG_PERMISSION_SYSTEM_FIXED
1135            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1136
1137    // And we back up these user-adjusted states
1138    private static final int USER_RUNTIME_GRANT_MASK =
1139            FLAG_PERMISSION_USER_SET
1140            | FLAG_PERMISSION_USER_FIXED
1141            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1142
1143    final @Nullable String mRequiredVerifierPackage;
1144    final @NonNull String mRequiredInstallerPackage;
1145    final @NonNull String mRequiredUninstallerPackage;
1146    final @Nullable String mSetupWizardPackage;
1147    final @Nullable String mStorageManagerPackage;
1148    final @NonNull String mServicesSystemSharedLibraryPackageName;
1149    final @NonNull String mSharedSystemSharedLibraryPackageName;
1150
1151    final boolean mPermissionReviewRequired;
1152
1153    private final PackageUsage mPackageUsage = new PackageUsage();
1154    private final CompilerStats mCompilerStats = new CompilerStats();
1155
1156    class PackageHandler extends Handler {
1157        private boolean mBound = false;
1158        final ArrayList<HandlerParams> mPendingInstalls =
1159            new ArrayList<HandlerParams>();
1160
1161        private boolean connectToService() {
1162            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1163                    " DefaultContainerService");
1164            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1165            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1166            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1167                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1168                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1169                mBound = true;
1170                return true;
1171            }
1172            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1173            return false;
1174        }
1175
1176        private void disconnectService() {
1177            mContainerService = null;
1178            mBound = false;
1179            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1180            mContext.unbindService(mDefContainerConn);
1181            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1182        }
1183
1184        PackageHandler(Looper looper) {
1185            super(looper);
1186        }
1187
1188        public void handleMessage(Message msg) {
1189            try {
1190                doHandleMessage(msg);
1191            } finally {
1192                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1193            }
1194        }
1195
1196        void doHandleMessage(Message msg) {
1197            switch (msg.what) {
1198                case INIT_COPY: {
1199                    HandlerParams params = (HandlerParams) msg.obj;
1200                    int idx = mPendingInstalls.size();
1201                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1202                    // If a bind was already initiated we dont really
1203                    // need to do anything. The pending install
1204                    // will be processed later on.
1205                    if (!mBound) {
1206                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1207                                System.identityHashCode(mHandler));
1208                        // If this is the only one pending we might
1209                        // have to bind to the service again.
1210                        if (!connectToService()) {
1211                            Slog.e(TAG, "Failed to bind to media container service");
1212                            params.serviceError();
1213                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1214                                    System.identityHashCode(mHandler));
1215                            if (params.traceMethod != null) {
1216                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1217                                        params.traceCookie);
1218                            }
1219                            return;
1220                        } else {
1221                            // Once we bind to the service, the first
1222                            // pending request will be processed.
1223                            mPendingInstalls.add(idx, params);
1224                        }
1225                    } else {
1226                        mPendingInstalls.add(idx, params);
1227                        // Already bound to the service. Just make
1228                        // sure we trigger off processing the first request.
1229                        if (idx == 0) {
1230                            mHandler.sendEmptyMessage(MCS_BOUND);
1231                        }
1232                    }
1233                    break;
1234                }
1235                case MCS_BOUND: {
1236                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1237                    if (msg.obj != null) {
1238                        mContainerService = (IMediaContainerService) msg.obj;
1239                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1240                                System.identityHashCode(mHandler));
1241                    }
1242                    if (mContainerService == null) {
1243                        if (!mBound) {
1244                            // Something seriously wrong since we are not bound and we are not
1245                            // waiting for connection. Bail out.
1246                            Slog.e(TAG, "Cannot bind to media container service");
1247                            for (HandlerParams params : mPendingInstalls) {
1248                                // Indicate service bind error
1249                                params.serviceError();
1250                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1251                                        System.identityHashCode(params));
1252                                if (params.traceMethod != null) {
1253                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1254                                            params.traceMethod, params.traceCookie);
1255                                }
1256                                return;
1257                            }
1258                            mPendingInstalls.clear();
1259                        } else {
1260                            Slog.w(TAG, "Waiting to connect to media container service");
1261                        }
1262                    } else if (mPendingInstalls.size() > 0) {
1263                        HandlerParams params = mPendingInstalls.get(0);
1264                        if (params != null) {
1265                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1266                                    System.identityHashCode(params));
1267                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1268                            if (params.startCopy()) {
1269                                // We are done...  look for more work or to
1270                                // go idle.
1271                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1272                                        "Checking for more work or unbind...");
1273                                // Delete pending install
1274                                if (mPendingInstalls.size() > 0) {
1275                                    mPendingInstalls.remove(0);
1276                                }
1277                                if (mPendingInstalls.size() == 0) {
1278                                    if (mBound) {
1279                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1280                                                "Posting delayed MCS_UNBIND");
1281                                        removeMessages(MCS_UNBIND);
1282                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1283                                        // Unbind after a little delay, to avoid
1284                                        // continual thrashing.
1285                                        sendMessageDelayed(ubmsg, 10000);
1286                                    }
1287                                } else {
1288                                    // There are more pending requests in queue.
1289                                    // Just post MCS_BOUND message to trigger processing
1290                                    // of next pending install.
1291                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1292                                            "Posting MCS_BOUND for next work");
1293                                    mHandler.sendEmptyMessage(MCS_BOUND);
1294                                }
1295                            }
1296                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1297                        }
1298                    } else {
1299                        // Should never happen ideally.
1300                        Slog.w(TAG, "Empty queue");
1301                    }
1302                    break;
1303                }
1304                case MCS_RECONNECT: {
1305                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1306                    if (mPendingInstalls.size() > 0) {
1307                        if (mBound) {
1308                            disconnectService();
1309                        }
1310                        if (!connectToService()) {
1311                            Slog.e(TAG, "Failed to bind to media container service");
1312                            for (HandlerParams params : mPendingInstalls) {
1313                                // Indicate service bind error
1314                                params.serviceError();
1315                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1316                                        System.identityHashCode(params));
1317                            }
1318                            mPendingInstalls.clear();
1319                        }
1320                    }
1321                    break;
1322                }
1323                case MCS_UNBIND: {
1324                    // If there is no actual work left, then time to unbind.
1325                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1326
1327                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1328                        if (mBound) {
1329                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1330
1331                            disconnectService();
1332                        }
1333                    } else if (mPendingInstalls.size() > 0) {
1334                        // There are more pending requests in queue.
1335                        // Just post MCS_BOUND message to trigger processing
1336                        // of next pending install.
1337                        mHandler.sendEmptyMessage(MCS_BOUND);
1338                    }
1339
1340                    break;
1341                }
1342                case MCS_GIVE_UP: {
1343                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1344                    HandlerParams params = mPendingInstalls.remove(0);
1345                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1346                            System.identityHashCode(params));
1347                    break;
1348                }
1349                case SEND_PENDING_BROADCAST: {
1350                    String packages[];
1351                    ArrayList<String> components[];
1352                    int size = 0;
1353                    int uids[];
1354                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1355                    synchronized (mPackages) {
1356                        if (mPendingBroadcasts == null) {
1357                            return;
1358                        }
1359                        size = mPendingBroadcasts.size();
1360                        if (size <= 0) {
1361                            // Nothing to be done. Just return
1362                            return;
1363                        }
1364                        packages = new String[size];
1365                        components = new ArrayList[size];
1366                        uids = new int[size];
1367                        int i = 0;  // filling out the above arrays
1368
1369                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1370                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1371                            Iterator<Map.Entry<String, ArrayList<String>>> it
1372                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1373                                            .entrySet().iterator();
1374                            while (it.hasNext() && i < size) {
1375                                Map.Entry<String, ArrayList<String>> ent = it.next();
1376                                packages[i] = ent.getKey();
1377                                components[i] = ent.getValue();
1378                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1379                                uids[i] = (ps != null)
1380                                        ? UserHandle.getUid(packageUserId, ps.appId)
1381                                        : -1;
1382                                i++;
1383                            }
1384                        }
1385                        size = i;
1386                        mPendingBroadcasts.clear();
1387                    }
1388                    // Send broadcasts
1389                    for (int i = 0; i < size; i++) {
1390                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1391                    }
1392                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1393                    break;
1394                }
1395                case START_CLEANING_PACKAGE: {
1396                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1397                    final String packageName = (String)msg.obj;
1398                    final int userId = msg.arg1;
1399                    final boolean andCode = msg.arg2 != 0;
1400                    synchronized (mPackages) {
1401                        if (userId == UserHandle.USER_ALL) {
1402                            int[] users = sUserManager.getUserIds();
1403                            for (int user : users) {
1404                                mSettings.addPackageToCleanLPw(
1405                                        new PackageCleanItem(user, packageName, andCode));
1406                            }
1407                        } else {
1408                            mSettings.addPackageToCleanLPw(
1409                                    new PackageCleanItem(userId, packageName, andCode));
1410                        }
1411                    }
1412                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1413                    startCleaningPackages();
1414                } break;
1415                case POST_INSTALL: {
1416                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1417
1418                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1419                    final boolean didRestore = (msg.arg2 != 0);
1420                    mRunningInstalls.delete(msg.arg1);
1421
1422                    if (data != null) {
1423                        InstallArgs args = data.args;
1424                        PackageInstalledInfo parentRes = data.res;
1425
1426                        final boolean grantPermissions = (args.installFlags
1427                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1428                        final boolean killApp = (args.installFlags
1429                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1430                        final String[] grantedPermissions = args.installGrantPermissions;
1431
1432                        // Handle the parent package
1433                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1434                                grantedPermissions, didRestore, args.installerPackageName,
1435                                args.observer);
1436
1437                        // Handle the child packages
1438                        final int childCount = (parentRes.addedChildPackages != null)
1439                                ? parentRes.addedChildPackages.size() : 0;
1440                        for (int i = 0; i < childCount; i++) {
1441                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1442                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1443                                    grantedPermissions, false, args.installerPackageName,
1444                                    args.observer);
1445                        }
1446
1447                        // Log tracing if needed
1448                        if (args.traceMethod != null) {
1449                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1450                                    args.traceCookie);
1451                        }
1452                    } else {
1453                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1454                    }
1455
1456                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1457                } break;
1458                case UPDATED_MEDIA_STATUS: {
1459                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1460                    boolean reportStatus = msg.arg1 == 1;
1461                    boolean doGc = msg.arg2 == 1;
1462                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1463                    if (doGc) {
1464                        // Force a gc to clear up stale containers.
1465                        Runtime.getRuntime().gc();
1466                    }
1467                    if (msg.obj != null) {
1468                        @SuppressWarnings("unchecked")
1469                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1470                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1471                        // Unload containers
1472                        unloadAllContainers(args);
1473                    }
1474                    if (reportStatus) {
1475                        try {
1476                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1477                            PackageHelper.getMountService().finishMediaUpdate();
1478                        } catch (RemoteException e) {
1479                            Log.e(TAG, "MountService not running?");
1480                        }
1481                    }
1482                } break;
1483                case WRITE_SETTINGS: {
1484                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1485                    synchronized (mPackages) {
1486                        removeMessages(WRITE_SETTINGS);
1487                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1488                        mSettings.writeLPr();
1489                        mDirtyUsers.clear();
1490                    }
1491                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1492                } break;
1493                case WRITE_PACKAGE_RESTRICTIONS: {
1494                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1495                    synchronized (mPackages) {
1496                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1497                        for (int userId : mDirtyUsers) {
1498                            mSettings.writePackageRestrictionsLPr(userId);
1499                        }
1500                        mDirtyUsers.clear();
1501                    }
1502                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1503                } break;
1504                case WRITE_PACKAGE_LIST: {
1505                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1506                    synchronized (mPackages) {
1507                        removeMessages(WRITE_PACKAGE_LIST);
1508                        mSettings.writePackageListLPr(msg.arg1);
1509                    }
1510                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1511                } break;
1512                case CHECK_PENDING_VERIFICATION: {
1513                    final int verificationId = msg.arg1;
1514                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1515
1516                    if ((state != null) && !state.timeoutExtended()) {
1517                        final InstallArgs args = state.getInstallArgs();
1518                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1519
1520                        Slog.i(TAG, "Verification timed out for " + originUri);
1521                        mPendingVerification.remove(verificationId);
1522
1523                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1524
1525                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1526                            Slog.i(TAG, "Continuing with installation of " + originUri);
1527                            state.setVerifierResponse(Binder.getCallingUid(),
1528                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1529                            broadcastPackageVerified(verificationId, originUri,
1530                                    PackageManager.VERIFICATION_ALLOW,
1531                                    state.getInstallArgs().getUser());
1532                            try {
1533                                ret = args.copyApk(mContainerService, true);
1534                            } catch (RemoteException e) {
1535                                Slog.e(TAG, "Could not contact the ContainerService");
1536                            }
1537                        } else {
1538                            broadcastPackageVerified(verificationId, originUri,
1539                                    PackageManager.VERIFICATION_REJECT,
1540                                    state.getInstallArgs().getUser());
1541                        }
1542
1543                        Trace.asyncTraceEnd(
1544                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1545
1546                        processPendingInstall(args, ret);
1547                        mHandler.sendEmptyMessage(MCS_UNBIND);
1548                    }
1549                    break;
1550                }
1551                case PACKAGE_VERIFIED: {
1552                    final int verificationId = msg.arg1;
1553
1554                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1555                    if (state == null) {
1556                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1557                        break;
1558                    }
1559
1560                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1561
1562                    state.setVerifierResponse(response.callerUid, response.code);
1563
1564                    if (state.isVerificationComplete()) {
1565                        mPendingVerification.remove(verificationId);
1566
1567                        final InstallArgs args = state.getInstallArgs();
1568                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1569
1570                        int ret;
1571                        if (state.isInstallAllowed()) {
1572                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1573                            broadcastPackageVerified(verificationId, originUri,
1574                                    response.code, state.getInstallArgs().getUser());
1575                            try {
1576                                ret = args.copyApk(mContainerService, true);
1577                            } catch (RemoteException e) {
1578                                Slog.e(TAG, "Could not contact the ContainerService");
1579                            }
1580                        } else {
1581                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1582                        }
1583
1584                        Trace.asyncTraceEnd(
1585                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1586
1587                        processPendingInstall(args, ret);
1588                        mHandler.sendEmptyMessage(MCS_UNBIND);
1589                    }
1590
1591                    break;
1592                }
1593                case START_INTENT_FILTER_VERIFICATIONS: {
1594                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1595                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1596                            params.replacing, params.pkg);
1597                    break;
1598                }
1599                case INTENT_FILTER_VERIFIED: {
1600                    final int verificationId = msg.arg1;
1601
1602                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1603                            verificationId);
1604                    if (state == null) {
1605                        Slog.w(TAG, "Invalid IntentFilter verification token "
1606                                + verificationId + " received");
1607                        break;
1608                    }
1609
1610                    final int userId = state.getUserId();
1611
1612                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1613                            "Processing IntentFilter verification with token:"
1614                            + verificationId + " and userId:" + userId);
1615
1616                    final IntentFilterVerificationResponse response =
1617                            (IntentFilterVerificationResponse) msg.obj;
1618
1619                    state.setVerifierResponse(response.callerUid, response.code);
1620
1621                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1622                            "IntentFilter verification with token:" + verificationId
1623                            + " and userId:" + userId
1624                            + " is settings verifier response with response code:"
1625                            + response.code);
1626
1627                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1628                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1629                                + response.getFailedDomainsString());
1630                    }
1631
1632                    if (state.isVerificationComplete()) {
1633                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1634                    } else {
1635                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1636                                "IntentFilter verification with token:" + verificationId
1637                                + " was not said to be complete");
1638                    }
1639
1640                    break;
1641                }
1642            }
1643        }
1644    }
1645
1646    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1647            boolean killApp, String[] grantedPermissions,
1648            boolean launchedForRestore, String installerPackage,
1649            IPackageInstallObserver2 installObserver) {
1650        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1651            // Send the removed broadcasts
1652            if (res.removedInfo != null) {
1653                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1654            }
1655
1656            // Now that we successfully installed the package, grant runtime
1657            // permissions if requested before broadcasting the install.
1658            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1659                    >= Build.VERSION_CODES.M) {
1660                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1661            }
1662
1663            final boolean update = res.removedInfo != null
1664                    && res.removedInfo.removedPackage != null;
1665
1666            // If this is the first time we have child packages for a disabled privileged
1667            // app that had no children, we grant requested runtime permissions to the new
1668            // children if the parent on the system image had them already granted.
1669            if (res.pkg.parentPackage != null) {
1670                synchronized (mPackages) {
1671                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1672                }
1673            }
1674
1675            synchronized (mPackages) {
1676                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1677            }
1678
1679            final String packageName = res.pkg.applicationInfo.packageName;
1680            Bundle extras = new Bundle(1);
1681            extras.putInt(Intent.EXTRA_UID, res.uid);
1682
1683            // Determine the set of users who are adding this package for
1684            // the first time vs. those who are seeing an update.
1685            int[] firstUsers = EMPTY_INT_ARRAY;
1686            int[] updateUsers = EMPTY_INT_ARRAY;
1687            if (res.origUsers == null || res.origUsers.length == 0) {
1688                firstUsers = res.newUsers;
1689            } else {
1690                for (int newUser : res.newUsers) {
1691                    boolean isNew = true;
1692                    for (int origUser : res.origUsers) {
1693                        if (origUser == newUser) {
1694                            isNew = false;
1695                            break;
1696                        }
1697                    }
1698                    if (isNew) {
1699                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1700                    } else {
1701                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1702                    }
1703                }
1704            }
1705
1706            // Send installed broadcasts if the install/update is not ephemeral
1707            if (!isEphemeral(res.pkg)) {
1708                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1709
1710                // Send added for users that see the package for the first time
1711                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1712                        extras, 0 /*flags*/, null /*targetPackage*/,
1713                        null /*finishedReceiver*/, firstUsers);
1714
1715                // Send added for users that don't see the package for the first time
1716                if (update) {
1717                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1718                }
1719                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1720                        extras, 0 /*flags*/, null /*targetPackage*/,
1721                        null /*finishedReceiver*/, updateUsers);
1722
1723                // Send replaced for users that don't see the package for the first time
1724                if (update) {
1725                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1726                            packageName, extras, 0 /*flags*/,
1727                            null /*targetPackage*/, null /*finishedReceiver*/,
1728                            updateUsers);
1729                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1730                            null /*package*/, null /*extras*/, 0 /*flags*/,
1731                            packageName /*targetPackage*/,
1732                            null /*finishedReceiver*/, updateUsers);
1733                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1734                    // First-install and we did a restore, so we're responsible for the
1735                    // first-launch broadcast.
1736                    if (DEBUG_BACKUP) {
1737                        Slog.i(TAG, "Post-restore of " + packageName
1738                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1739                    }
1740                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1741                }
1742
1743                // Send broadcast package appeared if forward locked/external for all users
1744                // treat asec-hosted packages like removable media on upgrade
1745                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1746                    if (DEBUG_INSTALL) {
1747                        Slog.i(TAG, "upgrading pkg " + res.pkg
1748                                + " is ASEC-hosted -> AVAILABLE");
1749                    }
1750                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1751                    ArrayList<String> pkgList = new ArrayList<>(1);
1752                    pkgList.add(packageName);
1753                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1754                }
1755            }
1756
1757            // Work that needs to happen on first install within each user
1758            if (firstUsers != null && firstUsers.length > 0) {
1759                synchronized (mPackages) {
1760                    for (int userId : firstUsers) {
1761                        // If this app is a browser and it's newly-installed for some
1762                        // users, clear any default-browser state in those users. The
1763                        // app's nature doesn't depend on the user, so we can just check
1764                        // its browser nature in any user and generalize.
1765                        if (packageIsBrowser(packageName, userId)) {
1766                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1767                        }
1768
1769                        // We may also need to apply pending (restored) runtime
1770                        // permission grants within these users.
1771                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1772                    }
1773                }
1774            }
1775
1776            // Log current value of "unknown sources" setting
1777            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1778                    getUnknownSourcesSettings());
1779
1780            // Force a gc to clear up things
1781            Runtime.getRuntime().gc();
1782
1783            // Remove the replaced package's older resources safely now
1784            // We delete after a gc for applications  on sdcard.
1785            if (res.removedInfo != null && res.removedInfo.args != null) {
1786                synchronized (mInstallLock) {
1787                    res.removedInfo.args.doPostDeleteLI(true);
1788                }
1789            }
1790        }
1791
1792        // If someone is watching installs - notify them
1793        if (installObserver != null) {
1794            try {
1795                Bundle extras = extrasForInstallResult(res);
1796                installObserver.onPackageInstalled(res.name, res.returnCode,
1797                        res.returnMsg, extras);
1798            } catch (RemoteException e) {
1799                Slog.i(TAG, "Observer no longer exists.");
1800            }
1801        }
1802    }
1803
1804    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1805            PackageParser.Package pkg) {
1806        if (pkg.parentPackage == null) {
1807            return;
1808        }
1809        if (pkg.requestedPermissions == null) {
1810            return;
1811        }
1812        final PackageSetting disabledSysParentPs = mSettings
1813                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1814        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1815                || !disabledSysParentPs.isPrivileged()
1816                || (disabledSysParentPs.childPackageNames != null
1817                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1818            return;
1819        }
1820        final int[] allUserIds = sUserManager.getUserIds();
1821        final int permCount = pkg.requestedPermissions.size();
1822        for (int i = 0; i < permCount; i++) {
1823            String permission = pkg.requestedPermissions.get(i);
1824            BasePermission bp = mSettings.mPermissions.get(permission);
1825            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1826                continue;
1827            }
1828            for (int userId : allUserIds) {
1829                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1830                        permission, userId)) {
1831                    grantRuntimePermission(pkg.packageName, permission, userId);
1832                }
1833            }
1834        }
1835    }
1836
1837    private StorageEventListener mStorageListener = new StorageEventListener() {
1838        @Override
1839        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1840            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1841                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1842                    final String volumeUuid = vol.getFsUuid();
1843
1844                    // Clean up any users or apps that were removed or recreated
1845                    // while this volume was missing
1846                    reconcileUsers(volumeUuid);
1847                    reconcileApps(volumeUuid);
1848
1849                    // Clean up any install sessions that expired or were
1850                    // cancelled while this volume was missing
1851                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1852
1853                    loadPrivatePackages(vol);
1854
1855                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1856                    unloadPrivatePackages(vol);
1857                }
1858            }
1859
1860            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1861                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1862                    updateExternalMediaStatus(true, false);
1863                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1864                    updateExternalMediaStatus(false, false);
1865                }
1866            }
1867        }
1868
1869        @Override
1870        public void onVolumeForgotten(String fsUuid) {
1871            if (TextUtils.isEmpty(fsUuid)) {
1872                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1873                return;
1874            }
1875
1876            // Remove any apps installed on the forgotten volume
1877            synchronized (mPackages) {
1878                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1879                for (PackageSetting ps : packages) {
1880                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1881                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1882                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1883                }
1884
1885                mSettings.onVolumeForgotten(fsUuid);
1886                mSettings.writeLPr();
1887            }
1888        }
1889    };
1890
1891    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1892            String[] grantedPermissions) {
1893        for (int userId : userIds) {
1894            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1895        }
1896
1897        // We could have touched GID membership, so flush out packages.list
1898        synchronized (mPackages) {
1899            mSettings.writePackageListLPr();
1900        }
1901    }
1902
1903    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1904            String[] grantedPermissions) {
1905        SettingBase sb = (SettingBase) pkg.mExtras;
1906        if (sb == null) {
1907            return;
1908        }
1909
1910        PermissionsState permissionsState = sb.getPermissionsState();
1911
1912        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1913                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1914
1915        for (String permission : pkg.requestedPermissions) {
1916            final BasePermission bp;
1917            synchronized (mPackages) {
1918                bp = mSettings.mPermissions.get(permission);
1919            }
1920            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1921                    && (grantedPermissions == null
1922                           || ArrayUtils.contains(grantedPermissions, permission))) {
1923                final int flags = permissionsState.getPermissionFlags(permission, userId);
1924                // Installer cannot change immutable permissions.
1925                if ((flags & immutableFlags) == 0) {
1926                    grantRuntimePermission(pkg.packageName, permission, userId);
1927                }
1928            }
1929        }
1930    }
1931
1932    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1933        Bundle extras = null;
1934        switch (res.returnCode) {
1935            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1936                extras = new Bundle();
1937                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1938                        res.origPermission);
1939                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1940                        res.origPackage);
1941                break;
1942            }
1943            case PackageManager.INSTALL_SUCCEEDED: {
1944                extras = new Bundle();
1945                extras.putBoolean(Intent.EXTRA_REPLACING,
1946                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1947                break;
1948            }
1949        }
1950        return extras;
1951    }
1952
1953    void scheduleWriteSettingsLocked() {
1954        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1955            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1956        }
1957    }
1958
1959    void scheduleWritePackageListLocked(int userId) {
1960        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1961            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1962            msg.arg1 = userId;
1963            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1964        }
1965    }
1966
1967    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1968        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1969        scheduleWritePackageRestrictionsLocked(userId);
1970    }
1971
1972    void scheduleWritePackageRestrictionsLocked(int userId) {
1973        final int[] userIds = (userId == UserHandle.USER_ALL)
1974                ? sUserManager.getUserIds() : new int[]{userId};
1975        for (int nextUserId : userIds) {
1976            if (!sUserManager.exists(nextUserId)) return;
1977            mDirtyUsers.add(nextUserId);
1978            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1979                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1980            }
1981        }
1982    }
1983
1984    public static PackageManagerService main(Context context, Installer installer,
1985            boolean factoryTest, boolean onlyCore) {
1986        // Self-check for initial settings.
1987        PackageManagerServiceCompilerMapping.checkProperties();
1988
1989        PackageManagerService m = new PackageManagerService(context, installer,
1990                factoryTest, onlyCore);
1991        m.enableSystemUserPackages();
1992        ServiceManager.addService("package", m);
1993        return m;
1994    }
1995
1996    private void enableSystemUserPackages() {
1997        if (!UserManager.isSplitSystemUser()) {
1998            return;
1999        }
2000        // For system user, enable apps based on the following conditions:
2001        // - app is whitelisted or belong to one of these groups:
2002        //   -- system app which has no launcher icons
2003        //   -- system app which has INTERACT_ACROSS_USERS permission
2004        //   -- system IME app
2005        // - app is not in the blacklist
2006        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2007        Set<String> enableApps = new ArraySet<>();
2008        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2009                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2010                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2011        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2012        enableApps.addAll(wlApps);
2013        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2014                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2015        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2016        enableApps.removeAll(blApps);
2017        Log.i(TAG, "Applications installed for system user: " + enableApps);
2018        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2019                UserHandle.SYSTEM);
2020        final int allAppsSize = allAps.size();
2021        synchronized (mPackages) {
2022            for (int i = 0; i < allAppsSize; i++) {
2023                String pName = allAps.get(i);
2024                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2025                // Should not happen, but we shouldn't be failing if it does
2026                if (pkgSetting == null) {
2027                    continue;
2028                }
2029                boolean install = enableApps.contains(pName);
2030                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2031                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2032                            + " for system user");
2033                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2034                }
2035            }
2036        }
2037    }
2038
2039    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2040        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2041                Context.DISPLAY_SERVICE);
2042        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2043    }
2044
2045    /**
2046     * Requests that files preopted on a secondary system partition be copied to the data partition
2047     * if possible.  Note that the actual copying of the files is accomplished by init for security
2048     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2049     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2050     */
2051    private static void requestCopyPreoptedFiles() {
2052        final int WAIT_TIME_MS = 100;
2053        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2054        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2055            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2056            // We will wait for up to 100 seconds.
2057            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2058            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2059                try {
2060                    Thread.sleep(WAIT_TIME_MS);
2061                } catch (InterruptedException e) {
2062                    // Do nothing
2063                }
2064                if (SystemClock.uptimeMillis() > timeEnd) {
2065                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2066                    Slog.wtf(TAG, "cppreopt did not finish!");
2067                    break;
2068                }
2069            }
2070        }
2071    }
2072
2073    public PackageManagerService(Context context, Installer installer,
2074            boolean factoryTest, boolean onlyCore) {
2075        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2076                SystemClock.uptimeMillis());
2077
2078        if (mSdkVersion <= 0) {
2079            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2080        }
2081
2082        mContext = context;
2083
2084        mPermissionReviewRequired = context.getResources().getBoolean(
2085                R.bool.config_permissionReviewRequired);
2086
2087        mFactoryTest = factoryTest;
2088        mOnlyCore = onlyCore;
2089        mMetrics = new DisplayMetrics();
2090        mSettings = new Settings(mPackages);
2091        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2092                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2093        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2094                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2095        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2096                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2097        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2098                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2099        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2100                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2101        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2102                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2103
2104        String separateProcesses = SystemProperties.get("debug.separate_processes");
2105        if (separateProcesses != null && separateProcesses.length() > 0) {
2106            if ("*".equals(separateProcesses)) {
2107                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2108                mSeparateProcesses = null;
2109                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2110            } else {
2111                mDefParseFlags = 0;
2112                mSeparateProcesses = separateProcesses.split(",");
2113                Slog.w(TAG, "Running with debug.separate_processes: "
2114                        + separateProcesses);
2115            }
2116        } else {
2117            mDefParseFlags = 0;
2118            mSeparateProcesses = null;
2119        }
2120
2121        mInstaller = installer;
2122        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2123                "*dexopt*");
2124        mDexManager = new DexManager();
2125        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2126
2127        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2128                FgThread.get().getLooper());
2129
2130        getDefaultDisplayMetrics(context, mMetrics);
2131
2132        SystemConfig systemConfig = SystemConfig.getInstance();
2133        mGlobalGids = systemConfig.getGlobalGids();
2134        mSystemPermissions = systemConfig.getSystemPermissions();
2135        mAvailableFeatures = systemConfig.getAvailableFeatures();
2136
2137        mProtectedPackages = new ProtectedPackages(mContext);
2138
2139        synchronized (mInstallLock) {
2140        // writer
2141        synchronized (mPackages) {
2142            mHandlerThread = new ServiceThread(TAG,
2143                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2144            mHandlerThread.start();
2145            mHandler = new PackageHandler(mHandlerThread.getLooper());
2146            mProcessLoggingHandler = new ProcessLoggingHandler();
2147            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2148
2149            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2150
2151            File dataDir = Environment.getDataDirectory();
2152            mAppInstallDir = new File(dataDir, "app");
2153            mAppLib32InstallDir = new File(dataDir, "app-lib");
2154            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2155            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2156            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2157
2158            sUserManager = new UserManagerService(context, this, mPackages);
2159
2160            // Propagate permission configuration in to package manager.
2161            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2162                    = systemConfig.getPermissions();
2163            for (int i=0; i<permConfig.size(); i++) {
2164                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2165                BasePermission bp = mSettings.mPermissions.get(perm.name);
2166                if (bp == null) {
2167                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2168                    mSettings.mPermissions.put(perm.name, bp);
2169                }
2170                if (perm.gids != null) {
2171                    bp.setGids(perm.gids, perm.perUser);
2172                }
2173            }
2174
2175            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2176            for (int i=0; i<libConfig.size(); i++) {
2177                mSharedLibraries.put(libConfig.keyAt(i),
2178                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2179            }
2180
2181            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2182
2183            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2184
2185            if (mFirstBoot) {
2186                requestCopyPreoptedFiles();
2187            }
2188
2189            String customResolverActivity = Resources.getSystem().getString(
2190                    R.string.config_customResolverActivity);
2191            if (TextUtils.isEmpty(customResolverActivity)) {
2192                customResolverActivity = null;
2193            } else {
2194                mCustomResolverComponentName = ComponentName.unflattenFromString(
2195                        customResolverActivity);
2196            }
2197
2198            long startTime = SystemClock.uptimeMillis();
2199
2200            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2201                    startTime);
2202
2203            // Set flag to monitor and not change apk file paths when
2204            // scanning install directories.
2205            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2206
2207            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2208            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2209
2210            if (bootClassPath == null) {
2211                Slog.w(TAG, "No BOOTCLASSPATH found!");
2212            }
2213
2214            if (systemServerClassPath == null) {
2215                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2216            }
2217
2218            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2219            final String[] dexCodeInstructionSets =
2220                    getDexCodeInstructionSets(
2221                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2222
2223            /**
2224             * Ensure all external libraries have had dexopt run on them.
2225             */
2226            if (mSharedLibraries.size() > 0) {
2227                // NOTE: For now, we're compiling these system "shared libraries"
2228                // (and framework jars) into all available architectures. It's possible
2229                // to compile them only when we come across an app that uses them (there's
2230                // already logic for that in scanPackageLI) but that adds some complexity.
2231                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2232                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2233                        final String lib = libEntry.path;
2234                        if (lib == null) {
2235                            continue;
2236                        }
2237
2238                        try {
2239                            // Shared libraries do not have profiles so we perform a full
2240                            // AOT compilation (if needed).
2241                            int dexoptNeeded = DexFile.getDexOptNeeded(
2242                                    lib, dexCodeInstructionSet,
2243                                    getCompilerFilterForReason(REASON_SHARED_APK),
2244                                    false /* newProfile */);
2245                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2246                                mInstaller.dexopt(lib, Process.SYSTEM_UID, "*",
2247                                        dexCodeInstructionSet, dexoptNeeded, null,
2248                                        DEXOPT_PUBLIC,
2249                                        getCompilerFilterForReason(REASON_SHARED_APK),
2250                                        StorageManager.UUID_PRIVATE_INTERNAL,
2251                                        SKIP_SHARED_LIBRARY_CHECK);
2252                            }
2253                        } catch (FileNotFoundException e) {
2254                            Slog.w(TAG, "Library not found: " + lib);
2255                        } catch (IOException | InstallerException e) {
2256                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2257                                    + e.getMessage());
2258                        }
2259                    }
2260                }
2261            }
2262
2263            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2264
2265            final VersionInfo ver = mSettings.getInternalVersion();
2266            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2267
2268            // when upgrading from pre-M, promote system app permissions from install to runtime
2269            mPromoteSystemApps =
2270                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2271
2272            // When upgrading from pre-N, we need to handle package extraction like first boot,
2273            // as there is no profiling data available.
2274            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2275
2276            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2277
2278            // save off the names of pre-existing system packages prior to scanning; we don't
2279            // want to automatically grant runtime permissions for new system apps
2280            if (mPromoteSystemApps) {
2281                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2282                while (pkgSettingIter.hasNext()) {
2283                    PackageSetting ps = pkgSettingIter.next();
2284                    if (isSystemApp(ps)) {
2285                        mExistingSystemPackages.add(ps.name);
2286                    }
2287                }
2288            }
2289
2290            // Collect vendor overlay packages.
2291            // (Do this before scanning any apps.)
2292            // For security and version matching reason, only consider
2293            // overlay packages if they reside in the right directory.
2294            File vendorOverlayDir;
2295            String overlaySkuDir = SystemProperties.get(VENDOR_OVERLAY_SKU_PROPERTY);
2296            if (!overlaySkuDir.isEmpty()) {
2297                vendorOverlayDir = new File(VENDOR_OVERLAY_DIR, overlaySkuDir);
2298            } else {
2299                vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2300            }
2301            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2302                    | PackageParser.PARSE_IS_SYSTEM
2303                    | PackageParser.PARSE_IS_SYSTEM_DIR
2304                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2305
2306            // Find base frameworks (resource packages without code).
2307            scanDirTracedLI(frameworkDir, mDefParseFlags
2308                    | PackageParser.PARSE_IS_SYSTEM
2309                    | PackageParser.PARSE_IS_SYSTEM_DIR
2310                    | PackageParser.PARSE_IS_PRIVILEGED,
2311                    scanFlags | SCAN_NO_DEX, 0);
2312
2313            // Collected privileged system packages.
2314            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2315            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2316                    | PackageParser.PARSE_IS_SYSTEM
2317                    | PackageParser.PARSE_IS_SYSTEM_DIR
2318                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2319
2320            // Collect ordinary system packages.
2321            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2322            scanDirTracedLI(systemAppDir, mDefParseFlags
2323                    | PackageParser.PARSE_IS_SYSTEM
2324                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2325
2326            // Collect all vendor packages.
2327            File vendorAppDir = new File("/vendor/app");
2328            try {
2329                vendorAppDir = vendorAppDir.getCanonicalFile();
2330            } catch (IOException e) {
2331                // failed to look up canonical path, continue with original one
2332            }
2333            scanDirTracedLI(vendorAppDir, mDefParseFlags
2334                    | PackageParser.PARSE_IS_SYSTEM
2335                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2336
2337            // Collect all OEM packages.
2338            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2339            scanDirTracedLI(oemAppDir, mDefParseFlags
2340                    | PackageParser.PARSE_IS_SYSTEM
2341                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2342
2343            // Prune any system packages that no longer exist.
2344            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2345            if (!mOnlyCore) {
2346                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2347                while (psit.hasNext()) {
2348                    PackageSetting ps = psit.next();
2349
2350                    /*
2351                     * If this is not a system app, it can't be a
2352                     * disable system app.
2353                     */
2354                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2355                        continue;
2356                    }
2357
2358                    /*
2359                     * If the package is scanned, it's not erased.
2360                     */
2361                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2362                    if (scannedPkg != null) {
2363                        /*
2364                         * If the system app is both scanned and in the
2365                         * disabled packages list, then it must have been
2366                         * added via OTA. Remove it from the currently
2367                         * scanned package so the previously user-installed
2368                         * application can be scanned.
2369                         */
2370                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2371                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2372                                    + ps.name + "; removing system app.  Last known codePath="
2373                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2374                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2375                                    + scannedPkg.mVersionCode);
2376                            removePackageLI(scannedPkg, true);
2377                            mExpectingBetter.put(ps.name, ps.codePath);
2378                        }
2379
2380                        continue;
2381                    }
2382
2383                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2384                        psit.remove();
2385                        logCriticalInfo(Log.WARN, "System package " + ps.name
2386                                + " no longer exists; it's data will be wiped");
2387                        // Actual deletion of code and data will be handled by later
2388                        // reconciliation step
2389                    } else {
2390                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2391                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2392                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2393                        }
2394                    }
2395                }
2396            }
2397
2398            //look for any incomplete package installations
2399            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2400            for (int i = 0; i < deletePkgsList.size(); i++) {
2401                // Actual deletion of code and data will be handled by later
2402                // reconciliation step
2403                final String packageName = deletePkgsList.get(i).name;
2404                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2405                synchronized (mPackages) {
2406                    mSettings.removePackageLPw(packageName);
2407                }
2408            }
2409
2410            //delete tmp files
2411            deleteTempPackageFiles();
2412
2413            // Remove any shared userIDs that have no associated packages
2414            mSettings.pruneSharedUsersLPw();
2415
2416            if (!mOnlyCore) {
2417                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2418                        SystemClock.uptimeMillis());
2419                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2420
2421                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2422                        | PackageParser.PARSE_FORWARD_LOCK,
2423                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2424
2425                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2426                        | PackageParser.PARSE_IS_EPHEMERAL,
2427                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2428
2429                /**
2430                 * Remove disable package settings for any updated system
2431                 * apps that were removed via an OTA. If they're not a
2432                 * previously-updated app, remove them completely.
2433                 * Otherwise, just revoke their system-level permissions.
2434                 */
2435                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2436                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2437                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2438
2439                    String msg;
2440                    if (deletedPkg == null) {
2441                        msg = "Updated system package " + deletedAppName
2442                                + " no longer exists; it's data will be wiped";
2443                        // Actual deletion of code and data will be handled by later
2444                        // reconciliation step
2445                    } else {
2446                        msg = "Updated system app + " + deletedAppName
2447                                + " no longer present; removing system privileges for "
2448                                + deletedAppName;
2449
2450                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2451
2452                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2453                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2454                    }
2455                    logCriticalInfo(Log.WARN, msg);
2456                }
2457
2458                /**
2459                 * Make sure all system apps that we expected to appear on
2460                 * the userdata partition actually showed up. If they never
2461                 * appeared, crawl back and revive the system version.
2462                 */
2463                for (int i = 0; i < mExpectingBetter.size(); i++) {
2464                    final String packageName = mExpectingBetter.keyAt(i);
2465                    if (!mPackages.containsKey(packageName)) {
2466                        final File scanFile = mExpectingBetter.valueAt(i);
2467
2468                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2469                                + " but never showed up; reverting to system");
2470
2471                        int reparseFlags = mDefParseFlags;
2472                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2473                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2474                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2475                                    | PackageParser.PARSE_IS_PRIVILEGED;
2476                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2477                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2478                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2479                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2480                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2481                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2482                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2483                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2484                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2485                        } else {
2486                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2487                            continue;
2488                        }
2489
2490                        mSettings.enableSystemPackageLPw(packageName);
2491
2492                        try {
2493                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2494                        } catch (PackageManagerException e) {
2495                            Slog.e(TAG, "Failed to parse original system package: "
2496                                    + e.getMessage());
2497                        }
2498                    }
2499                }
2500            }
2501            mExpectingBetter.clear();
2502
2503            // Resolve the storage manager.
2504            mStorageManagerPackage = getStorageManagerPackageName();
2505
2506            // Resolve protected action filters. Only the setup wizard is allowed to
2507            // have a high priority filter for these actions.
2508            mSetupWizardPackage = getSetupWizardPackageName();
2509            if (mProtectedFilters.size() > 0) {
2510                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2511                    Slog.i(TAG, "No setup wizard;"
2512                        + " All protected intents capped to priority 0");
2513                }
2514                for (ActivityIntentInfo filter : mProtectedFilters) {
2515                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2516                        if (DEBUG_FILTERS) {
2517                            Slog.i(TAG, "Found setup wizard;"
2518                                + " allow priority " + filter.getPriority() + ";"
2519                                + " package: " + filter.activity.info.packageName
2520                                + " activity: " + filter.activity.className
2521                                + " priority: " + filter.getPriority());
2522                        }
2523                        // skip setup wizard; allow it to keep the high priority filter
2524                        continue;
2525                    }
2526                    Slog.w(TAG, "Protected action; cap priority to 0;"
2527                            + " package: " + filter.activity.info.packageName
2528                            + " activity: " + filter.activity.className
2529                            + " origPrio: " + filter.getPriority());
2530                    filter.setPriority(0);
2531                }
2532            }
2533            mDeferProtectedFilters = false;
2534            mProtectedFilters.clear();
2535
2536            // Now that we know all of the shared libraries, update all clients to have
2537            // the correct library paths.
2538            updateAllSharedLibrariesLPw();
2539
2540            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2541                // NOTE: We ignore potential failures here during a system scan (like
2542                // the rest of the commands above) because there's precious little we
2543                // can do about it. A settings error is reported, though.
2544                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2545                        false /* boot complete */);
2546            }
2547
2548            // Now that we know all the packages we are keeping,
2549            // read and update their last usage times.
2550            mPackageUsage.read(mPackages);
2551            mCompilerStats.read();
2552
2553            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2554                    SystemClock.uptimeMillis());
2555            Slog.i(TAG, "Time to scan packages: "
2556                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2557                    + " seconds");
2558
2559            // If the platform SDK has changed since the last time we booted,
2560            // we need to re-grant app permission to catch any new ones that
2561            // appear.  This is really a hack, and means that apps can in some
2562            // cases get permissions that the user didn't initially explicitly
2563            // allow...  it would be nice to have some better way to handle
2564            // this situation.
2565            int updateFlags = UPDATE_PERMISSIONS_ALL;
2566            if (ver.sdkVersion != mSdkVersion) {
2567                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2568                        + mSdkVersion + "; regranting permissions for internal storage");
2569                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2570            }
2571            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2572            ver.sdkVersion = mSdkVersion;
2573
2574            // If this is the first boot or an update from pre-M, and it is a normal
2575            // boot, then we need to initialize the default preferred apps across
2576            // all defined users.
2577            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2578                for (UserInfo user : sUserManager.getUsers(true)) {
2579                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2580                    applyFactoryDefaultBrowserLPw(user.id);
2581                    primeDomainVerificationsLPw(user.id);
2582                }
2583            }
2584
2585            // Prepare storage for system user really early during boot,
2586            // since core system apps like SettingsProvider and SystemUI
2587            // can't wait for user to start
2588            final int storageFlags;
2589            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2590                storageFlags = StorageManager.FLAG_STORAGE_DE;
2591            } else {
2592                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2593            }
2594            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2595                    storageFlags);
2596
2597            // If this is first boot after an OTA, and a normal boot, then
2598            // we need to clear code cache directories.
2599            // Note that we do *not* clear the application profiles. These remain valid
2600            // across OTAs and are used to drive profile verification (post OTA) and
2601            // profile compilation (without waiting to collect a fresh set of profiles).
2602            if (mIsUpgrade && !onlyCore) {
2603                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2604                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2605                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2606                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2607                        // No apps are running this early, so no need to freeze
2608                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2609                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2610                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2611                    }
2612                }
2613                ver.fingerprint = Build.FINGERPRINT;
2614            }
2615
2616            checkDefaultBrowser();
2617
2618            // clear only after permissions and other defaults have been updated
2619            mExistingSystemPackages.clear();
2620            mPromoteSystemApps = false;
2621
2622            // All the changes are done during package scanning.
2623            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2624
2625            // can downgrade to reader
2626            mSettings.writeLPr();
2627
2628            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2629            // early on (before the package manager declares itself as early) because other
2630            // components in the system server might ask for package contexts for these apps.
2631            //
2632            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2633            // (i.e, that the data partition is unavailable).
2634            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2635                long start = System.nanoTime();
2636                List<PackageParser.Package> coreApps = new ArrayList<>();
2637                for (PackageParser.Package pkg : mPackages.values()) {
2638                    if (pkg.coreApp) {
2639                        coreApps.add(pkg);
2640                    }
2641                }
2642
2643                int[] stats = performDexOptUpgrade(coreApps, false,
2644                        getCompilerFilterForReason(REASON_CORE_APP));
2645
2646                final int elapsedTimeSeconds =
2647                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2648                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2649
2650                if (DEBUG_DEXOPT) {
2651                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2652                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2653                }
2654
2655
2656                // TODO: Should we log these stats to tron too ?
2657                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2658                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2659                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2660                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2661            }
2662
2663            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2664                    SystemClock.uptimeMillis());
2665
2666            if (!mOnlyCore) {
2667                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2668                mRequiredInstallerPackage = getRequiredInstallerLPr();
2669                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2670                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2671                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2672                        mIntentFilterVerifierComponent);
2673                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2674                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2675                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2676                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2677            } else {
2678                mRequiredVerifierPackage = null;
2679                mRequiredInstallerPackage = null;
2680                mRequiredUninstallerPackage = null;
2681                mIntentFilterVerifierComponent = null;
2682                mIntentFilterVerifier = null;
2683                mServicesSystemSharedLibraryPackageName = null;
2684                mSharedSystemSharedLibraryPackageName = null;
2685            }
2686
2687            mInstallerService = new PackageInstallerService(context, this);
2688
2689            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2690            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2691            // both the installer and resolver must be present to enable ephemeral
2692            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2693                if (DEBUG_EPHEMERAL) {
2694                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2695                            + " installer:" + ephemeralInstallerComponent);
2696                }
2697                mEphemeralResolverComponent = ephemeralResolverComponent;
2698                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2699                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2700                mEphemeralResolverConnection =
2701                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2702            } else {
2703                if (DEBUG_EPHEMERAL) {
2704                    final String missingComponent =
2705                            (ephemeralResolverComponent == null)
2706                            ? (ephemeralInstallerComponent == null)
2707                                    ? "resolver and installer"
2708                                    : "resolver"
2709                            : "installer";
2710                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2711                }
2712                mEphemeralResolverComponent = null;
2713                mEphemeralInstallerComponent = null;
2714                mEphemeralResolverConnection = null;
2715            }
2716
2717            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2718
2719            // Read and update the usage of dex files.
2720            // Do this at the end of PM init so that all the packages have their
2721            // data directory reconciled.
2722            // At this point we know the code paths of the packages, so we can validate
2723            // the disk file and build the internal cache.
2724            // The usage file is expected to be small so loading and verifying it
2725            // should take a fairly small time compare to the other activities (e.g. package
2726            // scanning).
2727            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2728            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2729            for (int userId : currentUserIds) {
2730                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2731            }
2732            mDexManager.load(userPackages);
2733        } // synchronized (mPackages)
2734        } // synchronized (mInstallLock)
2735
2736        // Now after opening every single application zip, make sure they
2737        // are all flushed.  Not really needed, but keeps things nice and
2738        // tidy.
2739        Runtime.getRuntime().gc();
2740
2741        // The initial scanning above does many calls into installd while
2742        // holding the mPackages lock, but we're mostly interested in yelling
2743        // once we have a booted system.
2744        mInstaller.setWarnIfHeld(mPackages);
2745
2746        // Expose private service for system components to use.
2747        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2748    }
2749
2750    @Override
2751    public boolean isFirstBoot() {
2752        return mFirstBoot;
2753    }
2754
2755    @Override
2756    public boolean isOnlyCoreApps() {
2757        return mOnlyCore;
2758    }
2759
2760    @Override
2761    public boolean isUpgrade() {
2762        return mIsUpgrade;
2763    }
2764
2765    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2766        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2767
2768        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2769                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2770                UserHandle.USER_SYSTEM);
2771        if (matches.size() == 1) {
2772            return matches.get(0).getComponentInfo().packageName;
2773        } else if (matches.size() == 0) {
2774            Log.e(TAG, "There should probably be a verifier, but, none were found");
2775            return null;
2776        }
2777        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2778    }
2779
2780    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2781        synchronized (mPackages) {
2782            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2783            if (libraryEntry == null) {
2784                throw new IllegalStateException("Missing required shared library:" + libraryName);
2785            }
2786            return libraryEntry.apk;
2787        }
2788    }
2789
2790    private @NonNull String getRequiredInstallerLPr() {
2791        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2792        intent.addCategory(Intent.CATEGORY_DEFAULT);
2793        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2794
2795        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2796                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2797                UserHandle.USER_SYSTEM);
2798        if (matches.size() == 1) {
2799            ResolveInfo resolveInfo = matches.get(0);
2800            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2801                throw new RuntimeException("The installer must be a privileged app");
2802            }
2803            return matches.get(0).getComponentInfo().packageName;
2804        } else {
2805            throw new RuntimeException("There must be exactly one installer; found " + matches);
2806        }
2807    }
2808
2809    private @NonNull String getRequiredUninstallerLPr() {
2810        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2811        intent.addCategory(Intent.CATEGORY_DEFAULT);
2812        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2813
2814        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2815                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2816                UserHandle.USER_SYSTEM);
2817        if (resolveInfo == null ||
2818                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2819            throw new RuntimeException("There must be exactly one uninstaller; found "
2820                    + resolveInfo);
2821        }
2822        return resolveInfo.getComponentInfo().packageName;
2823    }
2824
2825    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2826        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2827
2828        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2829                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2830                UserHandle.USER_SYSTEM);
2831        ResolveInfo best = null;
2832        final int N = matches.size();
2833        for (int i = 0; i < N; i++) {
2834            final ResolveInfo cur = matches.get(i);
2835            final String packageName = cur.getComponentInfo().packageName;
2836            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2837                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2838                continue;
2839            }
2840
2841            if (best == null || cur.priority > best.priority) {
2842                best = cur;
2843            }
2844        }
2845
2846        if (best != null) {
2847            return best.getComponentInfo().getComponentName();
2848        } else {
2849            throw new RuntimeException("There must be at least one intent filter verifier");
2850        }
2851    }
2852
2853    private @Nullable ComponentName getEphemeralResolverLPr() {
2854        final String[] packageArray =
2855                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2856        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2857            if (DEBUG_EPHEMERAL) {
2858                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2859            }
2860            return null;
2861        }
2862
2863        final int resolveFlags =
2864                MATCH_DIRECT_BOOT_AWARE
2865                | MATCH_DIRECT_BOOT_UNAWARE
2866                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2867        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2868        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2869                resolveFlags, UserHandle.USER_SYSTEM);
2870
2871        final int N = resolvers.size();
2872        if (N == 0) {
2873            if (DEBUG_EPHEMERAL) {
2874                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2875            }
2876            return null;
2877        }
2878
2879        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2880        for (int i = 0; i < N; i++) {
2881            final ResolveInfo info = resolvers.get(i);
2882
2883            if (info.serviceInfo == null) {
2884                continue;
2885            }
2886
2887            final String packageName = info.serviceInfo.packageName;
2888            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2889                if (DEBUG_EPHEMERAL) {
2890                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2891                            + " pkg: " + packageName + ", info:" + info);
2892                }
2893                continue;
2894            }
2895
2896            if (DEBUG_EPHEMERAL) {
2897                Slog.v(TAG, "Ephemeral resolver found;"
2898                        + " pkg: " + packageName + ", info:" + info);
2899            }
2900            return new ComponentName(packageName, info.serviceInfo.name);
2901        }
2902        if (DEBUG_EPHEMERAL) {
2903            Slog.v(TAG, "Ephemeral resolver NOT found");
2904        }
2905        return null;
2906    }
2907
2908    private @Nullable ComponentName getEphemeralInstallerLPr() {
2909        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2910        intent.addCategory(Intent.CATEGORY_DEFAULT);
2911        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2912
2913        final int resolveFlags =
2914                MATCH_DIRECT_BOOT_AWARE
2915                | MATCH_DIRECT_BOOT_UNAWARE
2916                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2917        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2918                resolveFlags, UserHandle.USER_SYSTEM);
2919        if (matches.size() == 0) {
2920            return null;
2921        } else if (matches.size() == 1) {
2922            return matches.get(0).getComponentInfo().getComponentName();
2923        } else {
2924            throw new RuntimeException(
2925                    "There must be at most one ephemeral installer; found " + matches);
2926        }
2927    }
2928
2929    private void primeDomainVerificationsLPw(int userId) {
2930        if (DEBUG_DOMAIN_VERIFICATION) {
2931            Slog.d(TAG, "Priming domain verifications in user " + userId);
2932        }
2933
2934        SystemConfig systemConfig = SystemConfig.getInstance();
2935        ArraySet<String> packages = systemConfig.getLinkedApps();
2936        ArraySet<String> domains = new ArraySet<String>();
2937
2938        for (String packageName : packages) {
2939            PackageParser.Package pkg = mPackages.get(packageName);
2940            if (pkg != null) {
2941                if (!pkg.isSystemApp()) {
2942                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2943                    continue;
2944                }
2945
2946                domains.clear();
2947                for (PackageParser.Activity a : pkg.activities) {
2948                    for (ActivityIntentInfo filter : a.intents) {
2949                        if (hasValidDomains(filter)) {
2950                            domains.addAll(filter.getHostsList());
2951                        }
2952                    }
2953                }
2954
2955                if (domains.size() > 0) {
2956                    if (DEBUG_DOMAIN_VERIFICATION) {
2957                        Slog.v(TAG, "      + " + packageName);
2958                    }
2959                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2960                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2961                    // and then 'always' in the per-user state actually used for intent resolution.
2962                    final IntentFilterVerificationInfo ivi;
2963                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2964                            new ArrayList<String>(domains));
2965                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2966                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2967                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2968                } else {
2969                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2970                            + "' does not handle web links");
2971                }
2972            } else {
2973                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2974            }
2975        }
2976
2977        scheduleWritePackageRestrictionsLocked(userId);
2978        scheduleWriteSettingsLocked();
2979    }
2980
2981    private void applyFactoryDefaultBrowserLPw(int userId) {
2982        // The default browser app's package name is stored in a string resource,
2983        // with a product-specific overlay used for vendor customization.
2984        String browserPkg = mContext.getResources().getString(
2985                com.android.internal.R.string.default_browser);
2986        if (!TextUtils.isEmpty(browserPkg)) {
2987            // non-empty string => required to be a known package
2988            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2989            if (ps == null) {
2990                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2991                browserPkg = null;
2992            } else {
2993                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2994            }
2995        }
2996
2997        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2998        // default.  If there's more than one, just leave everything alone.
2999        if (browserPkg == null) {
3000            calculateDefaultBrowserLPw(userId);
3001        }
3002    }
3003
3004    private void calculateDefaultBrowserLPw(int userId) {
3005        List<String> allBrowsers = resolveAllBrowserApps(userId);
3006        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3007        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3008    }
3009
3010    private List<String> resolveAllBrowserApps(int userId) {
3011        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3012        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3013                PackageManager.MATCH_ALL, userId);
3014
3015        final int count = list.size();
3016        List<String> result = new ArrayList<String>(count);
3017        for (int i=0; i<count; i++) {
3018            ResolveInfo info = list.get(i);
3019            if (info.activityInfo == null
3020                    || !info.handleAllWebDataURI
3021                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3022                    || result.contains(info.activityInfo.packageName)) {
3023                continue;
3024            }
3025            result.add(info.activityInfo.packageName);
3026        }
3027
3028        return result;
3029    }
3030
3031    private boolean packageIsBrowser(String packageName, int userId) {
3032        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3033                PackageManager.MATCH_ALL, userId);
3034        final int N = list.size();
3035        for (int i = 0; i < N; i++) {
3036            ResolveInfo info = list.get(i);
3037            if (packageName.equals(info.activityInfo.packageName)) {
3038                return true;
3039            }
3040        }
3041        return false;
3042    }
3043
3044    private void checkDefaultBrowser() {
3045        final int myUserId = UserHandle.myUserId();
3046        final String packageName = getDefaultBrowserPackageName(myUserId);
3047        if (packageName != null) {
3048            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3049            if (info == null) {
3050                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3051                synchronized (mPackages) {
3052                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3053                }
3054            }
3055        }
3056    }
3057
3058    @Override
3059    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3060            throws RemoteException {
3061        try {
3062            return super.onTransact(code, data, reply, flags);
3063        } catch (RuntimeException e) {
3064            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3065                Slog.wtf(TAG, "Package Manager Crash", e);
3066            }
3067            throw e;
3068        }
3069    }
3070
3071    static int[] appendInts(int[] cur, int[] add) {
3072        if (add == null) return cur;
3073        if (cur == null) return add;
3074        final int N = add.length;
3075        for (int i=0; i<N; i++) {
3076            cur = appendInt(cur, add[i]);
3077        }
3078        return cur;
3079    }
3080
3081    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3082        if (!sUserManager.exists(userId)) return null;
3083        if (ps == null) {
3084            return null;
3085        }
3086        final PackageParser.Package p = ps.pkg;
3087        if (p == null) {
3088            return null;
3089        }
3090
3091        final PermissionsState permissionsState = ps.getPermissionsState();
3092
3093        // Compute GIDs only if requested
3094        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3095                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3096        // Compute granted permissions only if package has requested permissions
3097        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3098                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3099        final PackageUserState state = ps.readUserState(userId);
3100
3101        return PackageParser.generatePackageInfo(p, gids, flags,
3102                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3103    }
3104
3105    @Override
3106    public void checkPackageStartable(String packageName, int userId) {
3107        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3108
3109        synchronized (mPackages) {
3110            final PackageSetting ps = mSettings.mPackages.get(packageName);
3111            if (ps == null) {
3112                throw new SecurityException("Package " + packageName + " was not found!");
3113            }
3114
3115            if (!ps.getInstalled(userId)) {
3116                throw new SecurityException(
3117                        "Package " + packageName + " was not installed for user " + userId + "!");
3118            }
3119
3120            if (mSafeMode && !ps.isSystem()) {
3121                throw new SecurityException("Package " + packageName + " not a system app!");
3122            }
3123
3124            if (mFrozenPackages.contains(packageName)) {
3125                throw new SecurityException("Package " + packageName + " is currently frozen!");
3126            }
3127
3128            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3129                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3130                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3131            }
3132        }
3133    }
3134
3135    @Override
3136    public boolean isPackageAvailable(String packageName, int userId) {
3137        if (!sUserManager.exists(userId)) return false;
3138        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3139                false /* requireFullPermission */, false /* checkShell */, "is package available");
3140        synchronized (mPackages) {
3141            PackageParser.Package p = mPackages.get(packageName);
3142            if (p != null) {
3143                final PackageSetting ps = (PackageSetting) p.mExtras;
3144                if (ps != null) {
3145                    final PackageUserState state = ps.readUserState(userId);
3146                    if (state != null) {
3147                        return PackageParser.isAvailable(state);
3148                    }
3149                }
3150            }
3151        }
3152        return false;
3153    }
3154
3155    @Override
3156    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3157        if (!sUserManager.exists(userId)) return null;
3158        flags = updateFlagsForPackage(flags, userId, packageName);
3159        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3160                false /* requireFullPermission */, false /* checkShell */, "get package info");
3161        // reader
3162        synchronized (mPackages) {
3163            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3164            PackageParser.Package p = null;
3165            if (matchFactoryOnly) {
3166                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3167                if (ps != null) {
3168                    return generatePackageInfo(ps, flags, userId);
3169                }
3170            }
3171            if (p == null) {
3172                p = mPackages.get(packageName);
3173                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3174                    return null;
3175                }
3176            }
3177            if (DEBUG_PACKAGE_INFO)
3178                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3179            if (p != null) {
3180                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3181            }
3182            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3183                final PackageSetting ps = mSettings.mPackages.get(packageName);
3184                return generatePackageInfo(ps, flags, userId);
3185            }
3186        }
3187        return null;
3188    }
3189
3190    @Override
3191    public String[] currentToCanonicalPackageNames(String[] names) {
3192        String[] out = new String[names.length];
3193        // reader
3194        synchronized (mPackages) {
3195            for (int i=names.length-1; i>=0; i--) {
3196                PackageSetting ps = mSettings.mPackages.get(names[i]);
3197                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3198            }
3199        }
3200        return out;
3201    }
3202
3203    @Override
3204    public String[] canonicalToCurrentPackageNames(String[] names) {
3205        String[] out = new String[names.length];
3206        // reader
3207        synchronized (mPackages) {
3208            for (int i=names.length-1; i>=0; i--) {
3209                String cur = mSettings.mRenamedPackages.get(names[i]);
3210                out[i] = cur != null ? cur : names[i];
3211            }
3212        }
3213        return out;
3214    }
3215
3216    @Override
3217    public int getPackageUid(String packageName, int flags, int userId) {
3218        if (!sUserManager.exists(userId)) return -1;
3219        flags = updateFlagsForPackage(flags, userId, packageName);
3220        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3221                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3222
3223        // reader
3224        synchronized (mPackages) {
3225            final PackageParser.Package p = mPackages.get(packageName);
3226            if (p != null && p.isMatch(flags)) {
3227                return UserHandle.getUid(userId, p.applicationInfo.uid);
3228            }
3229            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3230                final PackageSetting ps = mSettings.mPackages.get(packageName);
3231                if (ps != null && ps.isMatch(flags)) {
3232                    return UserHandle.getUid(userId, ps.appId);
3233                }
3234            }
3235        }
3236
3237        return -1;
3238    }
3239
3240    @Override
3241    public int[] getPackageGids(String packageName, int flags, int userId) {
3242        if (!sUserManager.exists(userId)) return null;
3243        flags = updateFlagsForPackage(flags, userId, packageName);
3244        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3245                false /* requireFullPermission */, false /* checkShell */,
3246                "getPackageGids");
3247
3248        // reader
3249        synchronized (mPackages) {
3250            final PackageParser.Package p = mPackages.get(packageName);
3251            if (p != null && p.isMatch(flags)) {
3252                PackageSetting ps = (PackageSetting) p.mExtras;
3253                return ps.getPermissionsState().computeGids(userId);
3254            }
3255            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3256                final PackageSetting ps = mSettings.mPackages.get(packageName);
3257                if (ps != null && ps.isMatch(flags)) {
3258                    return ps.getPermissionsState().computeGids(userId);
3259                }
3260            }
3261        }
3262
3263        return null;
3264    }
3265
3266    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3267        if (bp.perm != null) {
3268            return PackageParser.generatePermissionInfo(bp.perm, flags);
3269        }
3270        PermissionInfo pi = new PermissionInfo();
3271        pi.name = bp.name;
3272        pi.packageName = bp.sourcePackage;
3273        pi.nonLocalizedLabel = bp.name;
3274        pi.protectionLevel = bp.protectionLevel;
3275        return pi;
3276    }
3277
3278    @Override
3279    public PermissionInfo getPermissionInfo(String name, int flags) {
3280        // reader
3281        synchronized (mPackages) {
3282            final BasePermission p = mSettings.mPermissions.get(name);
3283            if (p != null) {
3284                return generatePermissionInfo(p, flags);
3285            }
3286            return null;
3287        }
3288    }
3289
3290    @Override
3291    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3292            int flags) {
3293        // reader
3294        synchronized (mPackages) {
3295            if (group != null && !mPermissionGroups.containsKey(group)) {
3296                // This is thrown as NameNotFoundException
3297                return null;
3298            }
3299
3300            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3301            for (BasePermission p : mSettings.mPermissions.values()) {
3302                if (group == null) {
3303                    if (p.perm == null || p.perm.info.group == null) {
3304                        out.add(generatePermissionInfo(p, flags));
3305                    }
3306                } else {
3307                    if (p.perm != null && group.equals(p.perm.info.group)) {
3308                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3309                    }
3310                }
3311            }
3312            return new ParceledListSlice<>(out);
3313        }
3314    }
3315
3316    @Override
3317    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3318        // reader
3319        synchronized (mPackages) {
3320            return PackageParser.generatePermissionGroupInfo(
3321                    mPermissionGroups.get(name), flags);
3322        }
3323    }
3324
3325    @Override
3326    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3327        // reader
3328        synchronized (mPackages) {
3329            final int N = mPermissionGroups.size();
3330            ArrayList<PermissionGroupInfo> out
3331                    = new ArrayList<PermissionGroupInfo>(N);
3332            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3333                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3334            }
3335            return new ParceledListSlice<>(out);
3336        }
3337    }
3338
3339    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3340            int userId) {
3341        if (!sUserManager.exists(userId)) return null;
3342        PackageSetting ps = mSettings.mPackages.get(packageName);
3343        if (ps != null) {
3344            if (ps.pkg == null) {
3345                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3346                if (pInfo != null) {
3347                    return pInfo.applicationInfo;
3348                }
3349                return null;
3350            }
3351            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3352                    ps.readUserState(userId), userId);
3353        }
3354        return null;
3355    }
3356
3357    @Override
3358    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3359        if (!sUserManager.exists(userId)) return null;
3360        flags = updateFlagsForApplication(flags, userId, packageName);
3361        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3362                false /* requireFullPermission */, false /* checkShell */, "get application info");
3363        // writer
3364        synchronized (mPackages) {
3365            PackageParser.Package p = mPackages.get(packageName);
3366            if (DEBUG_PACKAGE_INFO) Log.v(
3367                    TAG, "getApplicationInfo " + packageName
3368                    + ": " + p);
3369            if (p != null) {
3370                PackageSetting ps = mSettings.mPackages.get(packageName);
3371                if (ps == null) return null;
3372                // Note: isEnabledLP() does not apply here - always return info
3373                return PackageParser.generateApplicationInfo(
3374                        p, flags, ps.readUserState(userId), userId);
3375            }
3376            if ("android".equals(packageName)||"system".equals(packageName)) {
3377                return mAndroidApplication;
3378            }
3379            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3380                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3381            }
3382        }
3383        return null;
3384    }
3385
3386    @Override
3387    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3388            final IPackageDataObserver observer) {
3389        mContext.enforceCallingOrSelfPermission(
3390                android.Manifest.permission.CLEAR_APP_CACHE, null);
3391        // Queue up an async operation since clearing cache may take a little while.
3392        mHandler.post(new Runnable() {
3393            public void run() {
3394                mHandler.removeCallbacks(this);
3395                boolean success = true;
3396                synchronized (mInstallLock) {
3397                    try {
3398                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3399                    } catch (InstallerException e) {
3400                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3401                        success = false;
3402                    }
3403                }
3404                if (observer != null) {
3405                    try {
3406                        observer.onRemoveCompleted(null, success);
3407                    } catch (RemoteException e) {
3408                        Slog.w(TAG, "RemoveException when invoking call back");
3409                    }
3410                }
3411            }
3412        });
3413    }
3414
3415    @Override
3416    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3417            final IntentSender pi) {
3418        mContext.enforceCallingOrSelfPermission(
3419                android.Manifest.permission.CLEAR_APP_CACHE, null);
3420        // Queue up an async operation since clearing cache may take a little while.
3421        mHandler.post(new Runnable() {
3422            public void run() {
3423                mHandler.removeCallbacks(this);
3424                boolean success = true;
3425                synchronized (mInstallLock) {
3426                    try {
3427                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3428                    } catch (InstallerException e) {
3429                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3430                        success = false;
3431                    }
3432                }
3433                if(pi != null) {
3434                    try {
3435                        // Callback via pending intent
3436                        int code = success ? 1 : 0;
3437                        pi.sendIntent(null, code, null,
3438                                null, null);
3439                    } catch (SendIntentException e1) {
3440                        Slog.i(TAG, "Failed to send pending intent");
3441                    }
3442                }
3443            }
3444        });
3445    }
3446
3447    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3448        synchronized (mInstallLock) {
3449            try {
3450                mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3451            } catch (InstallerException e) {
3452                throw new IOException("Failed to free enough space", e);
3453            }
3454        }
3455    }
3456
3457    /**
3458     * Update given flags based on encryption status of current user.
3459     */
3460    private int updateFlags(int flags, int userId) {
3461        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3462                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3463            // Caller expressed an explicit opinion about what encryption
3464            // aware/unaware components they want to see, so fall through and
3465            // give them what they want
3466        } else {
3467            // Caller expressed no opinion, so match based on user state
3468            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3469                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3470            } else {
3471                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3472            }
3473        }
3474        return flags;
3475    }
3476
3477    private UserManagerInternal getUserManagerInternal() {
3478        if (mUserManagerInternal == null) {
3479            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3480        }
3481        return mUserManagerInternal;
3482    }
3483
3484    /**
3485     * Update given flags when being used to request {@link PackageInfo}.
3486     */
3487    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3488        boolean triaged = true;
3489        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3490                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3491            // Caller is asking for component details, so they'd better be
3492            // asking for specific encryption matching behavior, or be triaged
3493            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3494                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3495                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3496                triaged = false;
3497            }
3498        }
3499        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3500                | PackageManager.MATCH_SYSTEM_ONLY
3501                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3502            triaged = false;
3503        }
3504        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3505            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3506                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3507        }
3508        return updateFlags(flags, userId);
3509    }
3510
3511    /**
3512     * Update given flags when being used to request {@link ApplicationInfo}.
3513     */
3514    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3515        return updateFlagsForPackage(flags, userId, cookie);
3516    }
3517
3518    /**
3519     * Update given flags when being used to request {@link ComponentInfo}.
3520     */
3521    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3522        if (cookie instanceof Intent) {
3523            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3524                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3525            }
3526        }
3527
3528        boolean triaged = true;
3529        // Caller is asking for component details, so they'd better be
3530        // asking for specific encryption matching behavior, or be triaged
3531        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3532                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3533                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3534            triaged = false;
3535        }
3536        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3537            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3538                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3539        }
3540
3541        return updateFlags(flags, userId);
3542    }
3543
3544    /**
3545     * Update given flags when being used to request {@link ResolveInfo}.
3546     */
3547    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3548        // Safe mode means we shouldn't match any third-party components
3549        if (mSafeMode) {
3550            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3551        }
3552
3553        return updateFlagsForComponent(flags, userId, cookie);
3554    }
3555
3556    @Override
3557    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3558        if (!sUserManager.exists(userId)) return null;
3559        flags = updateFlagsForComponent(flags, userId, component);
3560        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3561                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3562        synchronized (mPackages) {
3563            PackageParser.Activity a = mActivities.mActivities.get(component);
3564
3565            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3566            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3567                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3568                if (ps == null) return null;
3569                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3570                        userId);
3571            }
3572            if (mResolveComponentName.equals(component)) {
3573                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3574                        new PackageUserState(), userId);
3575            }
3576        }
3577        return null;
3578    }
3579
3580    @Override
3581    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3582            String resolvedType) {
3583        synchronized (mPackages) {
3584            if (component.equals(mResolveComponentName)) {
3585                // The resolver supports EVERYTHING!
3586                return true;
3587            }
3588            PackageParser.Activity a = mActivities.mActivities.get(component);
3589            if (a == null) {
3590                return false;
3591            }
3592            for (int i=0; i<a.intents.size(); i++) {
3593                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3594                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3595                    return true;
3596                }
3597            }
3598            return false;
3599        }
3600    }
3601
3602    @Override
3603    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3604        if (!sUserManager.exists(userId)) return null;
3605        flags = updateFlagsForComponent(flags, userId, component);
3606        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3607                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3608        synchronized (mPackages) {
3609            PackageParser.Activity a = mReceivers.mActivities.get(component);
3610            if (DEBUG_PACKAGE_INFO) Log.v(
3611                TAG, "getReceiverInfo " + component + ": " + a);
3612            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3613                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3614                if (ps == null) return null;
3615                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3616                        userId);
3617            }
3618        }
3619        return null;
3620    }
3621
3622    @Override
3623    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3624        if (!sUserManager.exists(userId)) return null;
3625        flags = updateFlagsForComponent(flags, userId, component);
3626        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3627                false /* requireFullPermission */, false /* checkShell */, "get service info");
3628        synchronized (mPackages) {
3629            PackageParser.Service s = mServices.mServices.get(component);
3630            if (DEBUG_PACKAGE_INFO) Log.v(
3631                TAG, "getServiceInfo " + component + ": " + s);
3632            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3633                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3634                if (ps == null) return null;
3635                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3636                        userId);
3637            }
3638        }
3639        return null;
3640    }
3641
3642    @Override
3643    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3644        if (!sUserManager.exists(userId)) return null;
3645        flags = updateFlagsForComponent(flags, userId, component);
3646        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3647                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3648        synchronized (mPackages) {
3649            PackageParser.Provider p = mProviders.mProviders.get(component);
3650            if (DEBUG_PACKAGE_INFO) Log.v(
3651                TAG, "getProviderInfo " + component + ": " + p);
3652            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3653                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3654                if (ps == null) return null;
3655                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3656                        userId);
3657            }
3658        }
3659        return null;
3660    }
3661
3662    @Override
3663    public String[] getSystemSharedLibraryNames() {
3664        Set<String> libSet;
3665        synchronized (mPackages) {
3666            libSet = mSharedLibraries.keySet();
3667            int size = libSet.size();
3668            if (size > 0) {
3669                String[] libs = new String[size];
3670                libSet.toArray(libs);
3671                return libs;
3672            }
3673        }
3674        return null;
3675    }
3676
3677    @Override
3678    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3679        synchronized (mPackages) {
3680            return mServicesSystemSharedLibraryPackageName;
3681        }
3682    }
3683
3684    @Override
3685    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3686        synchronized (mPackages) {
3687            return mSharedSystemSharedLibraryPackageName;
3688        }
3689    }
3690
3691    @Override
3692    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3693        synchronized (mPackages) {
3694            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3695
3696            final FeatureInfo fi = new FeatureInfo();
3697            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3698                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3699            res.add(fi);
3700
3701            return new ParceledListSlice<>(res);
3702        }
3703    }
3704
3705    @Override
3706    public boolean hasSystemFeature(String name, int version) {
3707        synchronized (mPackages) {
3708            final FeatureInfo feat = mAvailableFeatures.get(name);
3709            if (feat == null) {
3710                return false;
3711            } else {
3712                return feat.version >= version;
3713            }
3714        }
3715    }
3716
3717    @Override
3718    public int checkPermission(String permName, String pkgName, int userId) {
3719        if (!sUserManager.exists(userId)) {
3720            return PackageManager.PERMISSION_DENIED;
3721        }
3722
3723        synchronized (mPackages) {
3724            final PackageParser.Package p = mPackages.get(pkgName);
3725            if (p != null && p.mExtras != null) {
3726                final PackageSetting ps = (PackageSetting) p.mExtras;
3727                final PermissionsState permissionsState = ps.getPermissionsState();
3728                if (permissionsState.hasPermission(permName, userId)) {
3729                    return PackageManager.PERMISSION_GRANTED;
3730                }
3731                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3732                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3733                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3734                    return PackageManager.PERMISSION_GRANTED;
3735                }
3736            }
3737        }
3738
3739        return PackageManager.PERMISSION_DENIED;
3740    }
3741
3742    @Override
3743    public int checkUidPermission(String permName, int uid) {
3744        final int userId = UserHandle.getUserId(uid);
3745
3746        if (!sUserManager.exists(userId)) {
3747            return PackageManager.PERMISSION_DENIED;
3748        }
3749
3750        synchronized (mPackages) {
3751            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3752            if (obj != null) {
3753                final SettingBase ps = (SettingBase) obj;
3754                final PermissionsState permissionsState = ps.getPermissionsState();
3755                if (permissionsState.hasPermission(permName, userId)) {
3756                    return PackageManager.PERMISSION_GRANTED;
3757                }
3758                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3759                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3760                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3761                    return PackageManager.PERMISSION_GRANTED;
3762                }
3763            } else {
3764                ArraySet<String> perms = mSystemPermissions.get(uid);
3765                if (perms != null) {
3766                    if (perms.contains(permName)) {
3767                        return PackageManager.PERMISSION_GRANTED;
3768                    }
3769                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3770                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3771                        return PackageManager.PERMISSION_GRANTED;
3772                    }
3773                }
3774            }
3775        }
3776
3777        return PackageManager.PERMISSION_DENIED;
3778    }
3779
3780    @Override
3781    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3782        if (UserHandle.getCallingUserId() != userId) {
3783            mContext.enforceCallingPermission(
3784                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3785                    "isPermissionRevokedByPolicy for user " + userId);
3786        }
3787
3788        if (checkPermission(permission, packageName, userId)
3789                == PackageManager.PERMISSION_GRANTED) {
3790            return false;
3791        }
3792
3793        final long identity = Binder.clearCallingIdentity();
3794        try {
3795            final int flags = getPermissionFlags(permission, packageName, userId);
3796            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3797        } finally {
3798            Binder.restoreCallingIdentity(identity);
3799        }
3800    }
3801
3802    @Override
3803    public String getPermissionControllerPackageName() {
3804        synchronized (mPackages) {
3805            return mRequiredInstallerPackage;
3806        }
3807    }
3808
3809    /**
3810     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3811     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3812     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3813     * @param message the message to log on security exception
3814     */
3815    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3816            boolean checkShell, String message) {
3817        if (userId < 0) {
3818            throw new IllegalArgumentException("Invalid userId " + userId);
3819        }
3820        if (checkShell) {
3821            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3822        }
3823        if (userId == UserHandle.getUserId(callingUid)) return;
3824        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3825            if (requireFullPermission) {
3826                mContext.enforceCallingOrSelfPermission(
3827                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3828            } else {
3829                try {
3830                    mContext.enforceCallingOrSelfPermission(
3831                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3832                } catch (SecurityException se) {
3833                    mContext.enforceCallingOrSelfPermission(
3834                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3835                }
3836            }
3837        }
3838    }
3839
3840    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3841        if (callingUid == Process.SHELL_UID) {
3842            if (userHandle >= 0
3843                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3844                throw new SecurityException("Shell does not have permission to access user "
3845                        + userHandle);
3846            } else if (userHandle < 0) {
3847                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3848                        + Debug.getCallers(3));
3849            }
3850        }
3851    }
3852
3853    private BasePermission findPermissionTreeLP(String permName) {
3854        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3855            if (permName.startsWith(bp.name) &&
3856                    permName.length() > bp.name.length() &&
3857                    permName.charAt(bp.name.length()) == '.') {
3858                return bp;
3859            }
3860        }
3861        return null;
3862    }
3863
3864    private BasePermission checkPermissionTreeLP(String permName) {
3865        if (permName != null) {
3866            BasePermission bp = findPermissionTreeLP(permName);
3867            if (bp != null) {
3868                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3869                    return bp;
3870                }
3871                throw new SecurityException("Calling uid "
3872                        + Binder.getCallingUid()
3873                        + " is not allowed to add to permission tree "
3874                        + bp.name + " owned by uid " + bp.uid);
3875            }
3876        }
3877        throw new SecurityException("No permission tree found for " + permName);
3878    }
3879
3880    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3881        if (s1 == null) {
3882            return s2 == null;
3883        }
3884        if (s2 == null) {
3885            return false;
3886        }
3887        if (s1.getClass() != s2.getClass()) {
3888            return false;
3889        }
3890        return s1.equals(s2);
3891    }
3892
3893    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3894        if (pi1.icon != pi2.icon) return false;
3895        if (pi1.logo != pi2.logo) return false;
3896        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3897        if (!compareStrings(pi1.name, pi2.name)) return false;
3898        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3899        // We'll take care of setting this one.
3900        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3901        // These are not currently stored in settings.
3902        //if (!compareStrings(pi1.group, pi2.group)) return false;
3903        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3904        //if (pi1.labelRes != pi2.labelRes) return false;
3905        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3906        return true;
3907    }
3908
3909    int permissionInfoFootprint(PermissionInfo info) {
3910        int size = info.name.length();
3911        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3912        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3913        return size;
3914    }
3915
3916    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3917        int size = 0;
3918        for (BasePermission perm : mSettings.mPermissions.values()) {
3919            if (perm.uid == tree.uid) {
3920                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3921            }
3922        }
3923        return size;
3924    }
3925
3926    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3927        // We calculate the max size of permissions defined by this uid and throw
3928        // if that plus the size of 'info' would exceed our stated maximum.
3929        if (tree.uid != Process.SYSTEM_UID) {
3930            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3931            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3932                throw new SecurityException("Permission tree size cap exceeded");
3933            }
3934        }
3935    }
3936
3937    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3938        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3939            throw new SecurityException("Label must be specified in permission");
3940        }
3941        BasePermission tree = checkPermissionTreeLP(info.name);
3942        BasePermission bp = mSettings.mPermissions.get(info.name);
3943        boolean added = bp == null;
3944        boolean changed = true;
3945        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3946        if (added) {
3947            enforcePermissionCapLocked(info, tree);
3948            bp = new BasePermission(info.name, tree.sourcePackage,
3949                    BasePermission.TYPE_DYNAMIC);
3950        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3951            throw new SecurityException(
3952                    "Not allowed to modify non-dynamic permission "
3953                    + info.name);
3954        } else {
3955            if (bp.protectionLevel == fixedLevel
3956                    && bp.perm.owner.equals(tree.perm.owner)
3957                    && bp.uid == tree.uid
3958                    && comparePermissionInfos(bp.perm.info, info)) {
3959                changed = false;
3960            }
3961        }
3962        bp.protectionLevel = fixedLevel;
3963        info = new PermissionInfo(info);
3964        info.protectionLevel = fixedLevel;
3965        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3966        bp.perm.info.packageName = tree.perm.info.packageName;
3967        bp.uid = tree.uid;
3968        if (added) {
3969            mSettings.mPermissions.put(info.name, bp);
3970        }
3971        if (changed) {
3972            if (!async) {
3973                mSettings.writeLPr();
3974            } else {
3975                scheduleWriteSettingsLocked();
3976            }
3977        }
3978        return added;
3979    }
3980
3981    @Override
3982    public boolean addPermission(PermissionInfo info) {
3983        synchronized (mPackages) {
3984            return addPermissionLocked(info, false);
3985        }
3986    }
3987
3988    @Override
3989    public boolean addPermissionAsync(PermissionInfo info) {
3990        synchronized (mPackages) {
3991            return addPermissionLocked(info, true);
3992        }
3993    }
3994
3995    @Override
3996    public void removePermission(String name) {
3997        synchronized (mPackages) {
3998            checkPermissionTreeLP(name);
3999            BasePermission bp = mSettings.mPermissions.get(name);
4000            if (bp != null) {
4001                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4002                    throw new SecurityException(
4003                            "Not allowed to modify non-dynamic permission "
4004                            + name);
4005                }
4006                mSettings.mPermissions.remove(name);
4007                mSettings.writeLPr();
4008            }
4009        }
4010    }
4011
4012    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4013            BasePermission bp) {
4014        int index = pkg.requestedPermissions.indexOf(bp.name);
4015        if (index == -1) {
4016            throw new SecurityException("Package " + pkg.packageName
4017                    + " has not requested permission " + bp.name);
4018        }
4019        if (!bp.isRuntime() && !bp.isDevelopment()) {
4020            throw new SecurityException("Permission " + bp.name
4021                    + " is not a changeable permission type");
4022        }
4023    }
4024
4025    @Override
4026    public void grantRuntimePermission(String packageName, String name, final int userId) {
4027        if (!sUserManager.exists(userId)) {
4028            Log.e(TAG, "No such user:" + userId);
4029            return;
4030        }
4031
4032        mContext.enforceCallingOrSelfPermission(
4033                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4034                "grantRuntimePermission");
4035
4036        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4037                true /* requireFullPermission */, true /* checkShell */,
4038                "grantRuntimePermission");
4039
4040        final int uid;
4041        final SettingBase sb;
4042
4043        synchronized (mPackages) {
4044            final PackageParser.Package pkg = mPackages.get(packageName);
4045            if (pkg == null) {
4046                throw new IllegalArgumentException("Unknown package: " + packageName);
4047            }
4048
4049            final BasePermission bp = mSettings.mPermissions.get(name);
4050            if (bp == null) {
4051                throw new IllegalArgumentException("Unknown permission: " + name);
4052            }
4053
4054            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4055
4056            // If a permission review is required for legacy apps we represent
4057            // their permissions as always granted runtime ones since we need
4058            // to keep the review required permission flag per user while an
4059            // install permission's state is shared across all users.
4060            if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
4061                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4062                    && bp.isRuntime()) {
4063                return;
4064            }
4065
4066            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4067            sb = (SettingBase) pkg.mExtras;
4068            if (sb == null) {
4069                throw new IllegalArgumentException("Unknown package: " + packageName);
4070            }
4071
4072            final PermissionsState permissionsState = sb.getPermissionsState();
4073
4074            final int flags = permissionsState.getPermissionFlags(name, userId);
4075            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4076                throw new SecurityException("Cannot grant system fixed permission "
4077                        + name + " for package " + packageName);
4078            }
4079
4080            if (bp.isDevelopment()) {
4081                // Development permissions must be handled specially, since they are not
4082                // normal runtime permissions.  For now they apply to all users.
4083                if (permissionsState.grantInstallPermission(bp) !=
4084                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4085                    scheduleWriteSettingsLocked();
4086                }
4087                return;
4088            }
4089
4090            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4091                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4092                return;
4093            }
4094
4095            final int result = permissionsState.grantRuntimePermission(bp, userId);
4096            switch (result) {
4097                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4098                    return;
4099                }
4100
4101                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4102                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4103                    mHandler.post(new Runnable() {
4104                        @Override
4105                        public void run() {
4106                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4107                        }
4108                    });
4109                }
4110                break;
4111            }
4112
4113            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4114
4115            // Not critical if that is lost - app has to request again.
4116            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4117        }
4118
4119        // Only need to do this if user is initialized. Otherwise it's a new user
4120        // and there are no processes running as the user yet and there's no need
4121        // to make an expensive call to remount processes for the changed permissions.
4122        if (READ_EXTERNAL_STORAGE.equals(name)
4123                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4124            final long token = Binder.clearCallingIdentity();
4125            try {
4126                if (sUserManager.isInitialized(userId)) {
4127                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4128                            MountServiceInternal.class);
4129                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4130                }
4131            } finally {
4132                Binder.restoreCallingIdentity(token);
4133            }
4134        }
4135    }
4136
4137    @Override
4138    public void revokeRuntimePermission(String packageName, String name, int userId) {
4139        if (!sUserManager.exists(userId)) {
4140            Log.e(TAG, "No such user:" + userId);
4141            return;
4142        }
4143
4144        mContext.enforceCallingOrSelfPermission(
4145                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4146                "revokeRuntimePermission");
4147
4148        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4149                true /* requireFullPermission */, true /* checkShell */,
4150                "revokeRuntimePermission");
4151
4152        final int appId;
4153
4154        synchronized (mPackages) {
4155            final PackageParser.Package pkg = mPackages.get(packageName);
4156            if (pkg == null) {
4157                throw new IllegalArgumentException("Unknown package: " + packageName);
4158            }
4159
4160            final BasePermission bp = mSettings.mPermissions.get(name);
4161            if (bp == null) {
4162                throw new IllegalArgumentException("Unknown permission: " + name);
4163            }
4164
4165            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4166
4167            // If a permission review is required for legacy apps we represent
4168            // their permissions as always granted runtime ones since we need
4169            // to keep the review required permission flag per user while an
4170            // install permission's state is shared across all users.
4171            if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
4172                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4173                    && bp.isRuntime()) {
4174                return;
4175            }
4176
4177            SettingBase sb = (SettingBase) pkg.mExtras;
4178            if (sb == null) {
4179                throw new IllegalArgumentException("Unknown package: " + packageName);
4180            }
4181
4182            final PermissionsState permissionsState = sb.getPermissionsState();
4183
4184            final int flags = permissionsState.getPermissionFlags(name, userId);
4185            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4186                throw new SecurityException("Cannot revoke system fixed permission "
4187                        + name + " for package " + packageName);
4188            }
4189
4190            if (bp.isDevelopment()) {
4191                // Development permissions must be handled specially, since they are not
4192                // normal runtime permissions.  For now they apply to all users.
4193                if (permissionsState.revokeInstallPermission(bp) !=
4194                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4195                    scheduleWriteSettingsLocked();
4196                }
4197                return;
4198            }
4199
4200            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4201                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4202                return;
4203            }
4204
4205            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4206
4207            // Critical, after this call app should never have the permission.
4208            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4209
4210            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4211        }
4212
4213        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4214    }
4215
4216    @Override
4217    public void resetRuntimePermissions() {
4218        mContext.enforceCallingOrSelfPermission(
4219                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4220                "revokeRuntimePermission");
4221
4222        int callingUid = Binder.getCallingUid();
4223        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4224            mContext.enforceCallingOrSelfPermission(
4225                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4226                    "resetRuntimePermissions");
4227        }
4228
4229        synchronized (mPackages) {
4230            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4231            for (int userId : UserManagerService.getInstance().getUserIds()) {
4232                final int packageCount = mPackages.size();
4233                for (int i = 0; i < packageCount; i++) {
4234                    PackageParser.Package pkg = mPackages.valueAt(i);
4235                    if (!(pkg.mExtras instanceof PackageSetting)) {
4236                        continue;
4237                    }
4238                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4239                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4240                }
4241            }
4242        }
4243    }
4244
4245    @Override
4246    public int getPermissionFlags(String name, String packageName, int userId) {
4247        if (!sUserManager.exists(userId)) {
4248            return 0;
4249        }
4250
4251        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4252
4253        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4254                true /* requireFullPermission */, false /* checkShell */,
4255                "getPermissionFlags");
4256
4257        synchronized (mPackages) {
4258            final PackageParser.Package pkg = mPackages.get(packageName);
4259            if (pkg == null) {
4260                return 0;
4261            }
4262
4263            final BasePermission bp = mSettings.mPermissions.get(name);
4264            if (bp == null) {
4265                return 0;
4266            }
4267
4268            SettingBase sb = (SettingBase) pkg.mExtras;
4269            if (sb == null) {
4270                return 0;
4271            }
4272
4273            PermissionsState permissionsState = sb.getPermissionsState();
4274            return permissionsState.getPermissionFlags(name, userId);
4275        }
4276    }
4277
4278    @Override
4279    public void updatePermissionFlags(String name, String packageName, int flagMask,
4280            int flagValues, int userId) {
4281        if (!sUserManager.exists(userId)) {
4282            return;
4283        }
4284
4285        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4286
4287        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4288                true /* requireFullPermission */, true /* checkShell */,
4289                "updatePermissionFlags");
4290
4291        // Only the system can change these flags and nothing else.
4292        if (getCallingUid() != Process.SYSTEM_UID) {
4293            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4294            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4295            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4296            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4297            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4298        }
4299
4300        synchronized (mPackages) {
4301            final PackageParser.Package pkg = mPackages.get(packageName);
4302            if (pkg == null) {
4303                throw new IllegalArgumentException("Unknown package: " + packageName);
4304            }
4305
4306            final BasePermission bp = mSettings.mPermissions.get(name);
4307            if (bp == null) {
4308                throw new IllegalArgumentException("Unknown permission: " + name);
4309            }
4310
4311            SettingBase sb = (SettingBase) pkg.mExtras;
4312            if (sb == null) {
4313                throw new IllegalArgumentException("Unknown package: " + packageName);
4314            }
4315
4316            PermissionsState permissionsState = sb.getPermissionsState();
4317
4318            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4319
4320            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4321                // Install and runtime permissions are stored in different places,
4322                // so figure out what permission changed and persist the change.
4323                if (permissionsState.getInstallPermissionState(name) != null) {
4324                    scheduleWriteSettingsLocked();
4325                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4326                        || hadState) {
4327                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4328                }
4329            }
4330        }
4331    }
4332
4333    /**
4334     * Update the permission flags for all packages and runtime permissions of a user in order
4335     * to allow device or profile owner to remove POLICY_FIXED.
4336     */
4337    @Override
4338    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4339        if (!sUserManager.exists(userId)) {
4340            return;
4341        }
4342
4343        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4344
4345        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4346                true /* requireFullPermission */, true /* checkShell */,
4347                "updatePermissionFlagsForAllApps");
4348
4349        // Only the system can change system fixed flags.
4350        if (getCallingUid() != Process.SYSTEM_UID) {
4351            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4352            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4353        }
4354
4355        synchronized (mPackages) {
4356            boolean changed = false;
4357            final int packageCount = mPackages.size();
4358            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4359                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4360                SettingBase sb = (SettingBase) pkg.mExtras;
4361                if (sb == null) {
4362                    continue;
4363                }
4364                PermissionsState permissionsState = sb.getPermissionsState();
4365                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4366                        userId, flagMask, flagValues);
4367            }
4368            if (changed) {
4369                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4370            }
4371        }
4372    }
4373
4374    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4375        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4376                != PackageManager.PERMISSION_GRANTED
4377            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4378                != PackageManager.PERMISSION_GRANTED) {
4379            throw new SecurityException(message + " requires "
4380                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4381                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4382        }
4383    }
4384
4385    @Override
4386    public boolean shouldShowRequestPermissionRationale(String permissionName,
4387            String packageName, int userId) {
4388        if (UserHandle.getCallingUserId() != userId) {
4389            mContext.enforceCallingPermission(
4390                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4391                    "canShowRequestPermissionRationale for user " + userId);
4392        }
4393
4394        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4395        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4396            return false;
4397        }
4398
4399        if (checkPermission(permissionName, packageName, userId)
4400                == PackageManager.PERMISSION_GRANTED) {
4401            return false;
4402        }
4403
4404        final int flags;
4405
4406        final long identity = Binder.clearCallingIdentity();
4407        try {
4408            flags = getPermissionFlags(permissionName,
4409                    packageName, userId);
4410        } finally {
4411            Binder.restoreCallingIdentity(identity);
4412        }
4413
4414        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4415                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4416                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4417
4418        if ((flags & fixedFlags) != 0) {
4419            return false;
4420        }
4421
4422        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4423    }
4424
4425    @Override
4426    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4427        mContext.enforceCallingOrSelfPermission(
4428                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4429                "addOnPermissionsChangeListener");
4430
4431        synchronized (mPackages) {
4432            mOnPermissionChangeListeners.addListenerLocked(listener);
4433        }
4434    }
4435
4436    @Override
4437    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4438        synchronized (mPackages) {
4439            mOnPermissionChangeListeners.removeListenerLocked(listener);
4440        }
4441    }
4442
4443    @Override
4444    public boolean isProtectedBroadcast(String actionName) {
4445        synchronized (mPackages) {
4446            if (mProtectedBroadcasts.contains(actionName)) {
4447                return true;
4448            } else if (actionName != null) {
4449                // TODO: remove these terrible hacks
4450                if (actionName.startsWith("android.net.netmon.lingerExpired")
4451                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4452                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4453                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4454                    return true;
4455                }
4456            }
4457        }
4458        return false;
4459    }
4460
4461    @Override
4462    public int checkSignatures(String pkg1, String pkg2) {
4463        synchronized (mPackages) {
4464            final PackageParser.Package p1 = mPackages.get(pkg1);
4465            final PackageParser.Package p2 = mPackages.get(pkg2);
4466            if (p1 == null || p1.mExtras == null
4467                    || p2 == null || p2.mExtras == null) {
4468                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4469            }
4470            return compareSignatures(p1.mSignatures, p2.mSignatures);
4471        }
4472    }
4473
4474    @Override
4475    public int checkUidSignatures(int uid1, int uid2) {
4476        // Map to base uids.
4477        uid1 = UserHandle.getAppId(uid1);
4478        uid2 = UserHandle.getAppId(uid2);
4479        // reader
4480        synchronized (mPackages) {
4481            Signature[] s1;
4482            Signature[] s2;
4483            Object obj = mSettings.getUserIdLPr(uid1);
4484            if (obj != null) {
4485                if (obj instanceof SharedUserSetting) {
4486                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4487                } else if (obj instanceof PackageSetting) {
4488                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4489                } else {
4490                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4491                }
4492            } else {
4493                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4494            }
4495            obj = mSettings.getUserIdLPr(uid2);
4496            if (obj != null) {
4497                if (obj instanceof SharedUserSetting) {
4498                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4499                } else if (obj instanceof PackageSetting) {
4500                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4501                } else {
4502                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4503                }
4504            } else {
4505                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4506            }
4507            return compareSignatures(s1, s2);
4508        }
4509    }
4510
4511    /**
4512     * This method should typically only be used when granting or revoking
4513     * permissions, since the app may immediately restart after this call.
4514     * <p>
4515     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4516     * guard your work against the app being relaunched.
4517     */
4518    private void killUid(int appId, int userId, String reason) {
4519        final long identity = Binder.clearCallingIdentity();
4520        try {
4521            IActivityManager am = ActivityManagerNative.getDefault();
4522            if (am != null) {
4523                try {
4524                    am.killUid(appId, userId, reason);
4525                } catch (RemoteException e) {
4526                    /* ignore - same process */
4527                }
4528            }
4529        } finally {
4530            Binder.restoreCallingIdentity(identity);
4531        }
4532    }
4533
4534    /**
4535     * Compares two sets of signatures. Returns:
4536     * <br />
4537     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4538     * <br />
4539     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4540     * <br />
4541     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4542     * <br />
4543     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4544     * <br />
4545     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4546     */
4547    static int compareSignatures(Signature[] s1, Signature[] s2) {
4548        if (s1 == null) {
4549            return s2 == null
4550                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4551                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4552        }
4553
4554        if (s2 == null) {
4555            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4556        }
4557
4558        if (s1.length != s2.length) {
4559            return PackageManager.SIGNATURE_NO_MATCH;
4560        }
4561
4562        // Since both signature sets are of size 1, we can compare without HashSets.
4563        if (s1.length == 1) {
4564            return s1[0].equals(s2[0]) ?
4565                    PackageManager.SIGNATURE_MATCH :
4566                    PackageManager.SIGNATURE_NO_MATCH;
4567        }
4568
4569        ArraySet<Signature> set1 = new ArraySet<Signature>();
4570        for (Signature sig : s1) {
4571            set1.add(sig);
4572        }
4573        ArraySet<Signature> set2 = new ArraySet<Signature>();
4574        for (Signature sig : s2) {
4575            set2.add(sig);
4576        }
4577        // Make sure s2 contains all signatures in s1.
4578        if (set1.equals(set2)) {
4579            return PackageManager.SIGNATURE_MATCH;
4580        }
4581        return PackageManager.SIGNATURE_NO_MATCH;
4582    }
4583
4584    /**
4585     * If the database version for this type of package (internal storage or
4586     * external storage) is less than the version where package signatures
4587     * were updated, return true.
4588     */
4589    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4590        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4591        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4592    }
4593
4594    /**
4595     * Used for backward compatibility to make sure any packages with
4596     * certificate chains get upgraded to the new style. {@code existingSigs}
4597     * will be in the old format (since they were stored on disk from before the
4598     * system upgrade) and {@code scannedSigs} will be in the newer format.
4599     */
4600    private int compareSignaturesCompat(PackageSignatures existingSigs,
4601            PackageParser.Package scannedPkg) {
4602        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4603            return PackageManager.SIGNATURE_NO_MATCH;
4604        }
4605
4606        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4607        for (Signature sig : existingSigs.mSignatures) {
4608            existingSet.add(sig);
4609        }
4610        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4611        for (Signature sig : scannedPkg.mSignatures) {
4612            try {
4613                Signature[] chainSignatures = sig.getChainSignatures();
4614                for (Signature chainSig : chainSignatures) {
4615                    scannedCompatSet.add(chainSig);
4616                }
4617            } catch (CertificateEncodingException e) {
4618                scannedCompatSet.add(sig);
4619            }
4620        }
4621        /*
4622         * Make sure the expanded scanned set contains all signatures in the
4623         * existing one.
4624         */
4625        if (scannedCompatSet.equals(existingSet)) {
4626            // Migrate the old signatures to the new scheme.
4627            existingSigs.assignSignatures(scannedPkg.mSignatures);
4628            // The new KeySets will be re-added later in the scanning process.
4629            synchronized (mPackages) {
4630                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4631            }
4632            return PackageManager.SIGNATURE_MATCH;
4633        }
4634        return PackageManager.SIGNATURE_NO_MATCH;
4635    }
4636
4637    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4638        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4639        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4640    }
4641
4642    private int compareSignaturesRecover(PackageSignatures existingSigs,
4643            PackageParser.Package scannedPkg) {
4644        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4645            return PackageManager.SIGNATURE_NO_MATCH;
4646        }
4647
4648        String msg = null;
4649        try {
4650            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4651                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4652                        + scannedPkg.packageName);
4653                return PackageManager.SIGNATURE_MATCH;
4654            }
4655        } catch (CertificateException e) {
4656            msg = e.getMessage();
4657        }
4658
4659        logCriticalInfo(Log.INFO,
4660                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4661        return PackageManager.SIGNATURE_NO_MATCH;
4662    }
4663
4664    @Override
4665    public List<String> getAllPackages() {
4666        synchronized (mPackages) {
4667            return new ArrayList<String>(mPackages.keySet());
4668        }
4669    }
4670
4671    @Override
4672    public String[] getPackagesForUid(int uid) {
4673        final int userId = UserHandle.getUserId(uid);
4674        uid = UserHandle.getAppId(uid);
4675        // reader
4676        synchronized (mPackages) {
4677            Object obj = mSettings.getUserIdLPr(uid);
4678            if (obj instanceof SharedUserSetting) {
4679                final SharedUserSetting sus = (SharedUserSetting) obj;
4680                final int N = sus.packages.size();
4681                String[] res = new String[N];
4682                final Iterator<PackageSetting> it = sus.packages.iterator();
4683                int i = 0;
4684                while (it.hasNext()) {
4685                    PackageSetting ps = it.next();
4686                    if (ps.getInstalled(userId)) {
4687                        res[i++] = ps.name;
4688                    } else {
4689                        res = ArrayUtils.removeElement(String.class, res, res[i]);
4690                    }
4691                }
4692                return res;
4693            } else if (obj instanceof PackageSetting) {
4694                final PackageSetting ps = (PackageSetting) obj;
4695                return new String[] { ps.name };
4696            }
4697        }
4698        return null;
4699    }
4700
4701    @Override
4702    public String getNameForUid(int uid) {
4703        // reader
4704        synchronized (mPackages) {
4705            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4706            if (obj instanceof SharedUserSetting) {
4707                final SharedUserSetting sus = (SharedUserSetting) obj;
4708                return sus.name + ":" + sus.userId;
4709            } else if (obj instanceof PackageSetting) {
4710                final PackageSetting ps = (PackageSetting) obj;
4711                return ps.name;
4712            }
4713        }
4714        return null;
4715    }
4716
4717    @Override
4718    public int getUidForSharedUser(String sharedUserName) {
4719        if(sharedUserName == null) {
4720            return -1;
4721        }
4722        // reader
4723        synchronized (mPackages) {
4724            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4725            if (suid == null) {
4726                return -1;
4727            }
4728            return suid.userId;
4729        }
4730    }
4731
4732    @Override
4733    public int getFlagsForUid(int uid) {
4734        synchronized (mPackages) {
4735            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4736            if (obj instanceof SharedUserSetting) {
4737                final SharedUserSetting sus = (SharedUserSetting) obj;
4738                return sus.pkgFlags;
4739            } else if (obj instanceof PackageSetting) {
4740                final PackageSetting ps = (PackageSetting) obj;
4741                return ps.pkgFlags;
4742            }
4743        }
4744        return 0;
4745    }
4746
4747    @Override
4748    public int getPrivateFlagsForUid(int uid) {
4749        synchronized (mPackages) {
4750            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4751            if (obj instanceof SharedUserSetting) {
4752                final SharedUserSetting sus = (SharedUserSetting) obj;
4753                return sus.pkgPrivateFlags;
4754            } else if (obj instanceof PackageSetting) {
4755                final PackageSetting ps = (PackageSetting) obj;
4756                return ps.pkgPrivateFlags;
4757            }
4758        }
4759        return 0;
4760    }
4761
4762    @Override
4763    public boolean isUidPrivileged(int uid) {
4764        uid = UserHandle.getAppId(uid);
4765        // reader
4766        synchronized (mPackages) {
4767            Object obj = mSettings.getUserIdLPr(uid);
4768            if (obj instanceof SharedUserSetting) {
4769                final SharedUserSetting sus = (SharedUserSetting) obj;
4770                final Iterator<PackageSetting> it = sus.packages.iterator();
4771                while (it.hasNext()) {
4772                    if (it.next().isPrivileged()) {
4773                        return true;
4774                    }
4775                }
4776            } else if (obj instanceof PackageSetting) {
4777                final PackageSetting ps = (PackageSetting) obj;
4778                return ps.isPrivileged();
4779            }
4780        }
4781        return false;
4782    }
4783
4784    @Override
4785    public String[] getAppOpPermissionPackages(String permissionName) {
4786        synchronized (mPackages) {
4787            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4788            if (pkgs == null) {
4789                return null;
4790            }
4791            return pkgs.toArray(new String[pkgs.size()]);
4792        }
4793    }
4794
4795    @Override
4796    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4797            int flags, int userId) {
4798        try {
4799            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4800
4801            if (!sUserManager.exists(userId)) return null;
4802            flags = updateFlagsForResolve(flags, userId, intent);
4803            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4804                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4805
4806            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4807            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4808                    flags, userId);
4809            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4810
4811            final ResolveInfo bestChoice =
4812                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4813            return bestChoice;
4814        } finally {
4815            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4816        }
4817    }
4818
4819    @Override
4820    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4821            IntentFilter filter, int match, ComponentName activity) {
4822        final int userId = UserHandle.getCallingUserId();
4823        if (DEBUG_PREFERRED) {
4824            Log.v(TAG, "setLastChosenActivity intent=" + intent
4825                + " resolvedType=" + resolvedType
4826                + " flags=" + flags
4827                + " filter=" + filter
4828                + " match=" + match
4829                + " activity=" + activity);
4830            filter.dump(new PrintStreamPrinter(System.out), "    ");
4831        }
4832        intent.setComponent(null);
4833        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4834                userId);
4835        // Find any earlier preferred or last chosen entries and nuke them
4836        findPreferredActivity(intent, resolvedType,
4837                flags, query, 0, false, true, false, userId);
4838        // Add the new activity as the last chosen for this filter
4839        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4840                "Setting last chosen");
4841    }
4842
4843    @Override
4844    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4845        final int userId = UserHandle.getCallingUserId();
4846        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4847        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4848                userId);
4849        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4850                false, false, false, userId);
4851    }
4852
4853    private boolean isEphemeralDisabled() {
4854        // ephemeral apps have been disabled across the board
4855        if (DISABLE_EPHEMERAL_APPS) {
4856            return true;
4857        }
4858        // system isn't up yet; can't read settings, so, assume no ephemeral apps
4859        if (!mSystemReady) {
4860            return true;
4861        }
4862        // we can't get a content resolver until the system is ready; these checks must happen last
4863        final ContentResolver resolver = mContext.getContentResolver();
4864        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
4865            return true;
4866        }
4867        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
4868    }
4869
4870    private boolean isEphemeralAllowed(
4871            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4872            boolean skipPackageCheck) {
4873        // Short circuit and return early if possible.
4874        if (isEphemeralDisabled()) {
4875            return false;
4876        }
4877        final int callingUser = UserHandle.getCallingUserId();
4878        if (callingUser != UserHandle.USER_SYSTEM) {
4879            return false;
4880        }
4881        if (mEphemeralResolverConnection == null) {
4882            return false;
4883        }
4884        if (intent.getComponent() != null) {
4885            return false;
4886        }
4887        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4888            return false;
4889        }
4890        if (!skipPackageCheck && intent.getPackage() != null) {
4891            return false;
4892        }
4893        final boolean isWebUri = hasWebURI(intent);
4894        if (!isWebUri || intent.getData().getHost() == null) {
4895            return false;
4896        }
4897        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4898        synchronized (mPackages) {
4899            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4900            for (int n = 0; n < count; n++) {
4901                ResolveInfo info = resolvedActivities.get(n);
4902                String packageName = info.activityInfo.packageName;
4903                PackageSetting ps = mSettings.mPackages.get(packageName);
4904                if (ps != null) {
4905                    // Try to get the status from User settings first
4906                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4907                    int status = (int) (packedStatus >> 32);
4908                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4909                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4910                        if (DEBUG_EPHEMERAL) {
4911                            Slog.v(TAG, "DENY ephemeral apps;"
4912                                + " pkg: " + packageName + ", status: " + status);
4913                        }
4914                        return false;
4915                    }
4916                }
4917            }
4918        }
4919        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4920        return true;
4921    }
4922
4923    private static EphemeralResolveInfo getEphemeralResolveInfo(
4924            Context context, EphemeralResolverConnection resolverConnection, Intent intent,
4925            String resolvedType, int userId, String packageName) {
4926        final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(),
4927                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4928        final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(),
4929                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4930        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4931                ephemeralPrefixCount);
4932        final int[] shaPrefix = digest.getDigestPrefix();
4933        final byte[][] digestBytes = digest.getDigestBytes();
4934        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4935                resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask);
4936        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4937            // No hash prefix match; there are no ephemeral apps for this domain.
4938            return null;
4939        }
4940
4941        // Go in reverse order so we match the narrowest scope first.
4942        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4943            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4944                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4945                    continue;
4946                }
4947                final List<IntentFilter> filters = ephemeralApplication.getFilters();
4948                // No filters; this should never happen.
4949                if (filters.isEmpty()) {
4950                    continue;
4951                }
4952                if (packageName != null
4953                        && !packageName.equals(ephemeralApplication.getPackageName())) {
4954                    continue;
4955                }
4956                // We have a domain match; resolve the filters to see if anything matches.
4957                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4958                for (int j = filters.size() - 1; j >= 0; --j) {
4959                    final EphemeralResolveIntentInfo intentInfo =
4960                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4961                    ephemeralResolver.addFilter(intentInfo);
4962                }
4963                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4964                        intent, resolvedType, false /*defaultOnly*/, userId);
4965                if (!matchedResolveInfoList.isEmpty()) {
4966                    return matchedResolveInfoList.get(0);
4967                }
4968            }
4969        }
4970        // Hash or filter mis-match; no ephemeral apps for this domain.
4971        return null;
4972    }
4973
4974    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4975            int flags, List<ResolveInfo> query, int userId) {
4976        if (query != null) {
4977            final int N = query.size();
4978            if (N == 1) {
4979                return query.get(0);
4980            } else if (N > 1) {
4981                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4982                // If there is more than one activity with the same priority,
4983                // then let the user decide between them.
4984                ResolveInfo r0 = query.get(0);
4985                ResolveInfo r1 = query.get(1);
4986                if (DEBUG_INTENT_MATCHING || debug) {
4987                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4988                            + r1.activityInfo.name + "=" + r1.priority);
4989                }
4990                // If the first activity has a higher priority, or a different
4991                // default, then it is always desirable to pick it.
4992                if (r0.priority != r1.priority
4993                        || r0.preferredOrder != r1.preferredOrder
4994                        || r0.isDefault != r1.isDefault) {
4995                    return query.get(0);
4996                }
4997                // If we have saved a preference for a preferred activity for
4998                // this Intent, use that.
4999                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5000                        flags, query, r0.priority, true, false, debug, userId);
5001                if (ri != null) {
5002                    return ri;
5003                }
5004                ri = new ResolveInfo(mResolveInfo);
5005                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5006                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5007                // If all of the options come from the same package, show the application's
5008                // label and icon instead of the generic resolver's.
5009                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5010                // and then throw away the ResolveInfo itself, meaning that the caller loses
5011                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5012                // a fallback for this case; we only set the target package's resources on
5013                // the ResolveInfo, not the ActivityInfo.
5014                final String intentPackage = intent.getPackage();
5015                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5016                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5017                    ri.resolvePackageName = intentPackage;
5018                    if (userNeedsBadging(userId)) {
5019                        ri.noResourceId = true;
5020                    } else {
5021                        ri.icon = appi.icon;
5022                    }
5023                    ri.iconResourceId = appi.icon;
5024                    ri.labelRes = appi.labelRes;
5025                }
5026                ri.activityInfo.applicationInfo = new ApplicationInfo(
5027                        ri.activityInfo.applicationInfo);
5028                if (userId != 0) {
5029                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5030                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5031                }
5032                // Make sure that the resolver is displayable in car mode
5033                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5034                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5035                return ri;
5036            }
5037        }
5038        return null;
5039    }
5040
5041    /**
5042     * Return true if the given list is not empty and all of its contents have
5043     * an activityInfo with the given package name.
5044     */
5045    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5046        if (ArrayUtils.isEmpty(list)) {
5047            return false;
5048        }
5049        for (int i = 0, N = list.size(); i < N; i++) {
5050            final ResolveInfo ri = list.get(i);
5051            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5052            if (ai == null || !packageName.equals(ai.packageName)) {
5053                return false;
5054            }
5055        }
5056        return true;
5057    }
5058
5059    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5060            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5061        final int N = query.size();
5062        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5063                .get(userId);
5064        // Get the list of persistent preferred activities that handle the intent
5065        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5066        List<PersistentPreferredActivity> pprefs = ppir != null
5067                ? ppir.queryIntent(intent, resolvedType,
5068                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5069                : null;
5070        if (pprefs != null && pprefs.size() > 0) {
5071            final int M = pprefs.size();
5072            for (int i=0; i<M; i++) {
5073                final PersistentPreferredActivity ppa = pprefs.get(i);
5074                if (DEBUG_PREFERRED || debug) {
5075                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5076                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5077                            + "\n  component=" + ppa.mComponent);
5078                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5079                }
5080                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5081                        flags | MATCH_DISABLED_COMPONENTS, userId);
5082                if (DEBUG_PREFERRED || debug) {
5083                    Slog.v(TAG, "Found persistent preferred activity:");
5084                    if (ai != null) {
5085                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5086                    } else {
5087                        Slog.v(TAG, "  null");
5088                    }
5089                }
5090                if (ai == null) {
5091                    // This previously registered persistent preferred activity
5092                    // component is no longer known. Ignore it and do NOT remove it.
5093                    continue;
5094                }
5095                for (int j=0; j<N; j++) {
5096                    final ResolveInfo ri = query.get(j);
5097                    if (!ri.activityInfo.applicationInfo.packageName
5098                            .equals(ai.applicationInfo.packageName)) {
5099                        continue;
5100                    }
5101                    if (!ri.activityInfo.name.equals(ai.name)) {
5102                        continue;
5103                    }
5104                    //  Found a persistent preference that can handle the intent.
5105                    if (DEBUG_PREFERRED || debug) {
5106                        Slog.v(TAG, "Returning persistent preferred activity: " +
5107                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5108                    }
5109                    return ri;
5110                }
5111            }
5112        }
5113        return null;
5114    }
5115
5116    // TODO: handle preferred activities missing while user has amnesia
5117    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5118            List<ResolveInfo> query, int priority, boolean always,
5119            boolean removeMatches, boolean debug, int userId) {
5120        if (!sUserManager.exists(userId)) return null;
5121        flags = updateFlagsForResolve(flags, userId, intent);
5122        // writer
5123        synchronized (mPackages) {
5124            if (intent.getSelector() != null) {
5125                intent = intent.getSelector();
5126            }
5127            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5128
5129            // Try to find a matching persistent preferred activity.
5130            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5131                    debug, userId);
5132
5133            // If a persistent preferred activity matched, use it.
5134            if (pri != null) {
5135                return pri;
5136            }
5137
5138            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5139            // Get the list of preferred activities that handle the intent
5140            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5141            List<PreferredActivity> prefs = pir != null
5142                    ? pir.queryIntent(intent, resolvedType,
5143                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5144                    : null;
5145            if (prefs != null && prefs.size() > 0) {
5146                boolean changed = false;
5147                try {
5148                    // First figure out how good the original match set is.
5149                    // We will only allow preferred activities that came
5150                    // from the same match quality.
5151                    int match = 0;
5152
5153                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5154
5155                    final int N = query.size();
5156                    for (int j=0; j<N; j++) {
5157                        final ResolveInfo ri = query.get(j);
5158                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5159                                + ": 0x" + Integer.toHexString(match));
5160                        if (ri.match > match) {
5161                            match = ri.match;
5162                        }
5163                    }
5164
5165                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5166                            + Integer.toHexString(match));
5167
5168                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5169                    final int M = prefs.size();
5170                    for (int i=0; i<M; i++) {
5171                        final PreferredActivity pa = prefs.get(i);
5172                        if (DEBUG_PREFERRED || debug) {
5173                            Slog.v(TAG, "Checking PreferredActivity ds="
5174                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5175                                    + "\n  component=" + pa.mPref.mComponent);
5176                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5177                        }
5178                        if (pa.mPref.mMatch != match) {
5179                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5180                                    + Integer.toHexString(pa.mPref.mMatch));
5181                            continue;
5182                        }
5183                        // If it's not an "always" type preferred activity and that's what we're
5184                        // looking for, skip it.
5185                        if (always && !pa.mPref.mAlways) {
5186                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5187                            continue;
5188                        }
5189                        final ActivityInfo ai = getActivityInfo(
5190                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5191                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5192                                userId);
5193                        if (DEBUG_PREFERRED || debug) {
5194                            Slog.v(TAG, "Found preferred activity:");
5195                            if (ai != null) {
5196                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5197                            } else {
5198                                Slog.v(TAG, "  null");
5199                            }
5200                        }
5201                        if (ai == null) {
5202                            // This previously registered preferred activity
5203                            // component is no longer known.  Most likely an update
5204                            // to the app was installed and in the new version this
5205                            // component no longer exists.  Clean it up by removing
5206                            // it from the preferred activities list, and skip it.
5207                            Slog.w(TAG, "Removing dangling preferred activity: "
5208                                    + pa.mPref.mComponent);
5209                            pir.removeFilter(pa);
5210                            changed = true;
5211                            continue;
5212                        }
5213                        for (int j=0; j<N; j++) {
5214                            final ResolveInfo ri = query.get(j);
5215                            if (!ri.activityInfo.applicationInfo.packageName
5216                                    .equals(ai.applicationInfo.packageName)) {
5217                                continue;
5218                            }
5219                            if (!ri.activityInfo.name.equals(ai.name)) {
5220                                continue;
5221                            }
5222
5223                            if (removeMatches) {
5224                                pir.removeFilter(pa);
5225                                changed = true;
5226                                if (DEBUG_PREFERRED) {
5227                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5228                                }
5229                                break;
5230                            }
5231
5232                            // Okay we found a previously set preferred or last chosen app.
5233                            // If the result set is different from when this
5234                            // was created, we need to clear it and re-ask the
5235                            // user their preference, if we're looking for an "always" type entry.
5236                            if (always && !pa.mPref.sameSet(query)) {
5237                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5238                                        + intent + " type " + resolvedType);
5239                                if (DEBUG_PREFERRED) {
5240                                    Slog.v(TAG, "Removing preferred activity since set changed "
5241                                            + pa.mPref.mComponent);
5242                                }
5243                                pir.removeFilter(pa);
5244                                // Re-add the filter as a "last chosen" entry (!always)
5245                                PreferredActivity lastChosen = new PreferredActivity(
5246                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5247                                pir.addFilter(lastChosen);
5248                                changed = true;
5249                                return null;
5250                            }
5251
5252                            // Yay! Either the set matched or we're looking for the last chosen
5253                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5254                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5255                            return ri;
5256                        }
5257                    }
5258                } finally {
5259                    if (changed) {
5260                        if (DEBUG_PREFERRED) {
5261                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5262                        }
5263                        scheduleWritePackageRestrictionsLocked(userId);
5264                    }
5265                }
5266            }
5267        }
5268        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5269        return null;
5270    }
5271
5272    /*
5273     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5274     */
5275    @Override
5276    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5277            int targetUserId) {
5278        mContext.enforceCallingOrSelfPermission(
5279                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5280        List<CrossProfileIntentFilter> matches =
5281                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5282        if (matches != null) {
5283            int size = matches.size();
5284            for (int i = 0; i < size; i++) {
5285                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5286            }
5287        }
5288        if (hasWebURI(intent)) {
5289            // cross-profile app linking works only towards the parent.
5290            final UserInfo parent = getProfileParent(sourceUserId);
5291            synchronized(mPackages) {
5292                int flags = updateFlagsForResolve(0, parent.id, intent);
5293                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5294                        intent, resolvedType, flags, sourceUserId, parent.id);
5295                return xpDomainInfo != null;
5296            }
5297        }
5298        return false;
5299    }
5300
5301    private UserInfo getProfileParent(int userId) {
5302        final long identity = Binder.clearCallingIdentity();
5303        try {
5304            return sUserManager.getProfileParent(userId);
5305        } finally {
5306            Binder.restoreCallingIdentity(identity);
5307        }
5308    }
5309
5310    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5311            String resolvedType, int userId) {
5312        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5313        if (resolver != null) {
5314            return resolver.queryIntent(intent, resolvedType, false, userId);
5315        }
5316        return null;
5317    }
5318
5319    @Override
5320    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5321            String resolvedType, int flags, int userId) {
5322        try {
5323            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5324
5325            return new ParceledListSlice<>(
5326                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5327        } finally {
5328            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5329        }
5330    }
5331
5332    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5333            String resolvedType, int flags, int userId) {
5334        if (!sUserManager.exists(userId)) return Collections.emptyList();
5335        flags = updateFlagsForResolve(flags, userId, intent);
5336        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5337                false /* requireFullPermission */, false /* checkShell */,
5338                "query intent activities");
5339        ComponentName comp = intent.getComponent();
5340        if (comp == null) {
5341            if (intent.getSelector() != null) {
5342                intent = intent.getSelector();
5343                comp = intent.getComponent();
5344            }
5345        }
5346
5347        if (comp != null) {
5348            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5349            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5350            if (ai != null) {
5351                final ResolveInfo ri = new ResolveInfo();
5352                ri.activityInfo = ai;
5353                list.add(ri);
5354            }
5355            return list;
5356        }
5357
5358        // reader
5359        boolean sortResult = false;
5360        boolean addEphemeral = false;
5361        boolean matchEphemeralPackage = false;
5362        List<ResolveInfo> result;
5363        final String pkgName = intent.getPackage();
5364        synchronized (mPackages) {
5365            if (pkgName == null) {
5366                List<CrossProfileIntentFilter> matchingFilters =
5367                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5368                // Check for results that need to skip the current profile.
5369                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5370                        resolvedType, flags, userId);
5371                if (xpResolveInfo != null) {
5372                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5373                    xpResult.add(xpResolveInfo);
5374                    return filterIfNotSystemUser(xpResult, userId);
5375                }
5376
5377                // Check for results in the current profile.
5378                result = filterIfNotSystemUser(mActivities.queryIntent(
5379                        intent, resolvedType, flags, userId), userId);
5380                addEphemeral =
5381                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5382
5383                // Check for cross profile results.
5384                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5385                xpResolveInfo = queryCrossProfileIntents(
5386                        matchingFilters, intent, resolvedType, flags, userId,
5387                        hasNonNegativePriorityResult);
5388                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5389                    boolean isVisibleToUser = filterIfNotSystemUser(
5390                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5391                    if (isVisibleToUser) {
5392                        result.add(xpResolveInfo);
5393                        sortResult = true;
5394                    }
5395                }
5396                if (hasWebURI(intent)) {
5397                    CrossProfileDomainInfo xpDomainInfo = null;
5398                    final UserInfo parent = getProfileParent(userId);
5399                    if (parent != null) {
5400                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5401                                flags, userId, parent.id);
5402                    }
5403                    if (xpDomainInfo != null) {
5404                        if (xpResolveInfo != null) {
5405                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5406                            // in the result.
5407                            result.remove(xpResolveInfo);
5408                        }
5409                        if (result.size() == 0 && !addEphemeral) {
5410                            result.add(xpDomainInfo.resolveInfo);
5411                            return result;
5412                        }
5413                    }
5414                    if (result.size() > 1 || addEphemeral) {
5415                        result = filterCandidatesWithDomainPreferredActivitiesLPr(
5416                                intent, flags, result, xpDomainInfo, userId);
5417                        sortResult = true;
5418                    }
5419                }
5420            } else {
5421                final PackageParser.Package pkg = mPackages.get(pkgName);
5422                if (pkg != null) {
5423                    result = filterIfNotSystemUser(
5424                            mActivities.queryIntentForPackage(
5425                                    intent, resolvedType, flags, pkg.activities, userId),
5426                            userId);
5427                } else {
5428                    // the caller wants to resolve for a particular package; however, there
5429                    // were no installed results, so, try to find an ephemeral result
5430                    addEphemeral = isEphemeralAllowed(
5431                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5432                    matchEphemeralPackage = true;
5433                    result = new ArrayList<ResolveInfo>();
5434                }
5435            }
5436        }
5437        if (addEphemeral) {
5438            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5439            final EphemeralResolveInfo ai = getEphemeralResolveInfo(
5440                    mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5441                    matchEphemeralPackage ? pkgName : null);
5442            if (ai != null) {
5443                if (DEBUG_EPHEMERAL) {
5444                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5445                }
5446                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5447                ephemeralInstaller.ephemeralResolveInfo = ai;
5448                // make sure this resolver is the default
5449                ephemeralInstaller.isDefault = true;
5450                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5451                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5452                // add a non-generic filter
5453                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5454                ephemeralInstaller.filter.addDataPath(
5455                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5456                result.add(ephemeralInstaller);
5457            }
5458            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5459        }
5460        if (sortResult) {
5461            Collections.sort(result, mResolvePrioritySorter);
5462        }
5463        return result;
5464    }
5465
5466    private static class CrossProfileDomainInfo {
5467        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5468        ResolveInfo resolveInfo;
5469        /* Best domain verification status of the activities found in the other profile */
5470        int bestDomainVerificationStatus;
5471    }
5472
5473    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5474            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5475        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5476                sourceUserId)) {
5477            return null;
5478        }
5479        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5480                resolvedType, flags, parentUserId);
5481
5482        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5483            return null;
5484        }
5485        CrossProfileDomainInfo result = null;
5486        int size = resultTargetUser.size();
5487        for (int i = 0; i < size; i++) {
5488            ResolveInfo riTargetUser = resultTargetUser.get(i);
5489            // Intent filter verification is only for filters that specify a host. So don't return
5490            // those that handle all web uris.
5491            if (riTargetUser.handleAllWebDataURI) {
5492                continue;
5493            }
5494            String packageName = riTargetUser.activityInfo.packageName;
5495            PackageSetting ps = mSettings.mPackages.get(packageName);
5496            if (ps == null) {
5497                continue;
5498            }
5499            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5500            int status = (int)(verificationState >> 32);
5501            if (result == null) {
5502                result = new CrossProfileDomainInfo();
5503                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5504                        sourceUserId, parentUserId);
5505                result.bestDomainVerificationStatus = status;
5506            } else {
5507                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5508                        result.bestDomainVerificationStatus);
5509            }
5510        }
5511        // Don't consider matches with status NEVER across profiles.
5512        if (result != null && result.bestDomainVerificationStatus
5513                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5514            return null;
5515        }
5516        return result;
5517    }
5518
5519    /**
5520     * Verification statuses are ordered from the worse to the best, except for
5521     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5522     */
5523    private int bestDomainVerificationStatus(int status1, int status2) {
5524        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5525            return status2;
5526        }
5527        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5528            return status1;
5529        }
5530        return (int) MathUtils.max(status1, status2);
5531    }
5532
5533    private boolean isUserEnabled(int userId) {
5534        long callingId = Binder.clearCallingIdentity();
5535        try {
5536            UserInfo userInfo = sUserManager.getUserInfo(userId);
5537            return userInfo != null && userInfo.isEnabled();
5538        } finally {
5539            Binder.restoreCallingIdentity(callingId);
5540        }
5541    }
5542
5543    /**
5544     * Filter out activities with systemUserOnly flag set, when current user is not System.
5545     *
5546     * @return filtered list
5547     */
5548    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5549        if (userId == UserHandle.USER_SYSTEM) {
5550            return resolveInfos;
5551        }
5552        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5553            ResolveInfo info = resolveInfos.get(i);
5554            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5555                resolveInfos.remove(i);
5556            }
5557        }
5558        return resolveInfos;
5559    }
5560
5561    /**
5562     * @param resolveInfos list of resolve infos in descending priority order
5563     * @return if the list contains a resolve info with non-negative priority
5564     */
5565    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5566        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5567    }
5568
5569    private static boolean hasWebURI(Intent intent) {
5570        if (intent.getData() == null) {
5571            return false;
5572        }
5573        final String scheme = intent.getScheme();
5574        if (TextUtils.isEmpty(scheme)) {
5575            return false;
5576        }
5577        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5578    }
5579
5580    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5581            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5582            int userId) {
5583        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5584
5585        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5586            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5587                    candidates.size());
5588        }
5589
5590        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5591        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5592        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5593        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5594        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5595        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5596
5597        synchronized (mPackages) {
5598            final int count = candidates.size();
5599            // First, try to use linked apps. Partition the candidates into four lists:
5600            // one for the final results, one for the "do not use ever", one for "undefined status"
5601            // and finally one for "browser app type".
5602            for (int n=0; n<count; n++) {
5603                ResolveInfo info = candidates.get(n);
5604                String packageName = info.activityInfo.packageName;
5605                PackageSetting ps = mSettings.mPackages.get(packageName);
5606                if (ps != null) {
5607                    // Add to the special match all list (Browser use case)
5608                    if (info.handleAllWebDataURI) {
5609                        matchAllList.add(info);
5610                        continue;
5611                    }
5612                    // Try to get the status from User settings first
5613                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5614                    int status = (int)(packedStatus >> 32);
5615                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5616                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5617                        if (DEBUG_DOMAIN_VERIFICATION) {
5618                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5619                                    + " : linkgen=" + linkGeneration);
5620                        }
5621                        // Use link-enabled generation as preferredOrder, i.e.
5622                        // prefer newly-enabled over earlier-enabled.
5623                        info.preferredOrder = linkGeneration;
5624                        alwaysList.add(info);
5625                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5626                        if (DEBUG_DOMAIN_VERIFICATION) {
5627                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5628                        }
5629                        neverList.add(info);
5630                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5631                        if (DEBUG_DOMAIN_VERIFICATION) {
5632                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5633                        }
5634                        alwaysAskList.add(info);
5635                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5636                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5637                        if (DEBUG_DOMAIN_VERIFICATION) {
5638                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5639                        }
5640                        undefinedList.add(info);
5641                    }
5642                }
5643            }
5644
5645            // We'll want to include browser possibilities in a few cases
5646            boolean includeBrowser = false;
5647
5648            // First try to add the "always" resolution(s) for the current user, if any
5649            if (alwaysList.size() > 0) {
5650                result.addAll(alwaysList);
5651            } else {
5652                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5653                result.addAll(undefinedList);
5654                // Maybe add one for the other profile.
5655                if (xpDomainInfo != null && (
5656                        xpDomainInfo.bestDomainVerificationStatus
5657                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5658                    result.add(xpDomainInfo.resolveInfo);
5659                }
5660                includeBrowser = true;
5661            }
5662
5663            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5664            // If there were 'always' entries their preferred order has been set, so we also
5665            // back that off to make the alternatives equivalent
5666            if (alwaysAskList.size() > 0) {
5667                for (ResolveInfo i : result) {
5668                    i.preferredOrder = 0;
5669                }
5670                result.addAll(alwaysAskList);
5671                includeBrowser = true;
5672            }
5673
5674            if (includeBrowser) {
5675                // Also add browsers (all of them or only the default one)
5676                if (DEBUG_DOMAIN_VERIFICATION) {
5677                    Slog.v(TAG, "   ...including browsers in candidate set");
5678                }
5679                if ((matchFlags & MATCH_ALL) != 0) {
5680                    result.addAll(matchAllList);
5681                } else {
5682                    // Browser/generic handling case.  If there's a default browser, go straight
5683                    // to that (but only if there is no other higher-priority match).
5684                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5685                    int maxMatchPrio = 0;
5686                    ResolveInfo defaultBrowserMatch = null;
5687                    final int numCandidates = matchAllList.size();
5688                    for (int n = 0; n < numCandidates; n++) {
5689                        ResolveInfo info = matchAllList.get(n);
5690                        // track the highest overall match priority...
5691                        if (info.priority > maxMatchPrio) {
5692                            maxMatchPrio = info.priority;
5693                        }
5694                        // ...and the highest-priority default browser match
5695                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5696                            if (defaultBrowserMatch == null
5697                                    || (defaultBrowserMatch.priority < info.priority)) {
5698                                if (debug) {
5699                                    Slog.v(TAG, "Considering default browser match " + info);
5700                                }
5701                                defaultBrowserMatch = info;
5702                            }
5703                        }
5704                    }
5705                    if (defaultBrowserMatch != null
5706                            && defaultBrowserMatch.priority >= maxMatchPrio
5707                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5708                    {
5709                        if (debug) {
5710                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5711                        }
5712                        result.add(defaultBrowserMatch);
5713                    } else {
5714                        result.addAll(matchAllList);
5715                    }
5716                }
5717
5718                // If there is nothing selected, add all candidates and remove the ones that the user
5719                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5720                if (result.size() == 0) {
5721                    result.addAll(candidates);
5722                    result.removeAll(neverList);
5723                }
5724            }
5725        }
5726        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5727            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5728                    result.size());
5729            for (ResolveInfo info : result) {
5730                Slog.v(TAG, "  + " + info.activityInfo);
5731            }
5732        }
5733        return result;
5734    }
5735
5736    // Returns a packed value as a long:
5737    //
5738    // high 'int'-sized word: link status: undefined/ask/never/always.
5739    // low 'int'-sized word: relative priority among 'always' results.
5740    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5741        long result = ps.getDomainVerificationStatusForUser(userId);
5742        // if none available, get the master status
5743        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5744            if (ps.getIntentFilterVerificationInfo() != null) {
5745                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5746            }
5747        }
5748        return result;
5749    }
5750
5751    private ResolveInfo querySkipCurrentProfileIntents(
5752            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5753            int flags, int sourceUserId) {
5754        if (matchingFilters != null) {
5755            int size = matchingFilters.size();
5756            for (int i = 0; i < size; i ++) {
5757                CrossProfileIntentFilter filter = matchingFilters.get(i);
5758                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5759                    // Checking if there are activities in the target user that can handle the
5760                    // intent.
5761                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5762                            resolvedType, flags, sourceUserId);
5763                    if (resolveInfo != null) {
5764                        return resolveInfo;
5765                    }
5766                }
5767            }
5768        }
5769        return null;
5770    }
5771
5772    // Return matching ResolveInfo in target user if any.
5773    private ResolveInfo queryCrossProfileIntents(
5774            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5775            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5776        if (matchingFilters != null) {
5777            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5778            // match the same intent. For performance reasons, it is better not to
5779            // run queryIntent twice for the same userId
5780            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5781            int size = matchingFilters.size();
5782            for (int i = 0; i < size; i++) {
5783                CrossProfileIntentFilter filter = matchingFilters.get(i);
5784                int targetUserId = filter.getTargetUserId();
5785                boolean skipCurrentProfile =
5786                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5787                boolean skipCurrentProfileIfNoMatchFound =
5788                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5789                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5790                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5791                    // Checking if there are activities in the target user that can handle the
5792                    // intent.
5793                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5794                            resolvedType, flags, sourceUserId);
5795                    if (resolveInfo != null) return resolveInfo;
5796                    alreadyTriedUserIds.put(targetUserId, true);
5797                }
5798            }
5799        }
5800        return null;
5801    }
5802
5803    /**
5804     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5805     * will forward the intent to the filter's target user.
5806     * Otherwise, returns null.
5807     */
5808    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5809            String resolvedType, int flags, int sourceUserId) {
5810        int targetUserId = filter.getTargetUserId();
5811        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5812                resolvedType, flags, targetUserId);
5813        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5814            // If all the matches in the target profile are suspended, return null.
5815            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5816                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5817                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5818                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5819                            targetUserId);
5820                }
5821            }
5822        }
5823        return null;
5824    }
5825
5826    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5827            int sourceUserId, int targetUserId) {
5828        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5829        long ident = Binder.clearCallingIdentity();
5830        boolean targetIsProfile;
5831        try {
5832            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5833        } finally {
5834            Binder.restoreCallingIdentity(ident);
5835        }
5836        String className;
5837        if (targetIsProfile) {
5838            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5839        } else {
5840            className = FORWARD_INTENT_TO_PARENT;
5841        }
5842        ComponentName forwardingActivityComponentName = new ComponentName(
5843                mAndroidApplication.packageName, className);
5844        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5845                sourceUserId);
5846        if (!targetIsProfile) {
5847            forwardingActivityInfo.showUserIcon = targetUserId;
5848            forwardingResolveInfo.noResourceId = true;
5849        }
5850        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5851        forwardingResolveInfo.priority = 0;
5852        forwardingResolveInfo.preferredOrder = 0;
5853        forwardingResolveInfo.match = 0;
5854        forwardingResolveInfo.isDefault = true;
5855        forwardingResolveInfo.filter = filter;
5856        forwardingResolveInfo.targetUserId = targetUserId;
5857        return forwardingResolveInfo;
5858    }
5859
5860    @Override
5861    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5862            Intent[] specifics, String[] specificTypes, Intent intent,
5863            String resolvedType, int flags, int userId) {
5864        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5865                specificTypes, intent, resolvedType, flags, userId));
5866    }
5867
5868    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5869            Intent[] specifics, String[] specificTypes, Intent intent,
5870            String resolvedType, int flags, int userId) {
5871        if (!sUserManager.exists(userId)) return Collections.emptyList();
5872        flags = updateFlagsForResolve(flags, userId, intent);
5873        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5874                false /* requireFullPermission */, false /* checkShell */,
5875                "query intent activity options");
5876        final String resultsAction = intent.getAction();
5877
5878        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5879                | PackageManager.GET_RESOLVED_FILTER, userId);
5880
5881        if (DEBUG_INTENT_MATCHING) {
5882            Log.v(TAG, "Query " + intent + ": " + results);
5883        }
5884
5885        int specificsPos = 0;
5886        int N;
5887
5888        // todo: note that the algorithm used here is O(N^2).  This
5889        // isn't a problem in our current environment, but if we start running
5890        // into situations where we have more than 5 or 10 matches then this
5891        // should probably be changed to something smarter...
5892
5893        // First we go through and resolve each of the specific items
5894        // that were supplied, taking care of removing any corresponding
5895        // duplicate items in the generic resolve list.
5896        if (specifics != null) {
5897            for (int i=0; i<specifics.length; i++) {
5898                final Intent sintent = specifics[i];
5899                if (sintent == null) {
5900                    continue;
5901                }
5902
5903                if (DEBUG_INTENT_MATCHING) {
5904                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5905                }
5906
5907                String action = sintent.getAction();
5908                if (resultsAction != null && resultsAction.equals(action)) {
5909                    // If this action was explicitly requested, then don't
5910                    // remove things that have it.
5911                    action = null;
5912                }
5913
5914                ResolveInfo ri = null;
5915                ActivityInfo ai = null;
5916
5917                ComponentName comp = sintent.getComponent();
5918                if (comp == null) {
5919                    ri = resolveIntent(
5920                        sintent,
5921                        specificTypes != null ? specificTypes[i] : null,
5922                            flags, userId);
5923                    if (ri == null) {
5924                        continue;
5925                    }
5926                    if (ri == mResolveInfo) {
5927                        // ACK!  Must do something better with this.
5928                    }
5929                    ai = ri.activityInfo;
5930                    comp = new ComponentName(ai.applicationInfo.packageName,
5931                            ai.name);
5932                } else {
5933                    ai = getActivityInfo(comp, flags, userId);
5934                    if (ai == null) {
5935                        continue;
5936                    }
5937                }
5938
5939                // Look for any generic query activities that are duplicates
5940                // of this specific one, and remove them from the results.
5941                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5942                N = results.size();
5943                int j;
5944                for (j=specificsPos; j<N; j++) {
5945                    ResolveInfo sri = results.get(j);
5946                    if ((sri.activityInfo.name.equals(comp.getClassName())
5947                            && sri.activityInfo.applicationInfo.packageName.equals(
5948                                    comp.getPackageName()))
5949                        || (action != null && sri.filter.matchAction(action))) {
5950                        results.remove(j);
5951                        if (DEBUG_INTENT_MATCHING) Log.v(
5952                            TAG, "Removing duplicate item from " + j
5953                            + " due to specific " + specificsPos);
5954                        if (ri == null) {
5955                            ri = sri;
5956                        }
5957                        j--;
5958                        N--;
5959                    }
5960                }
5961
5962                // Add this specific item to its proper place.
5963                if (ri == null) {
5964                    ri = new ResolveInfo();
5965                    ri.activityInfo = ai;
5966                }
5967                results.add(specificsPos, ri);
5968                ri.specificIndex = i;
5969                specificsPos++;
5970            }
5971        }
5972
5973        // Now we go through the remaining generic results and remove any
5974        // duplicate actions that are found here.
5975        N = results.size();
5976        for (int i=specificsPos; i<N-1; i++) {
5977            final ResolveInfo rii = results.get(i);
5978            if (rii.filter == null) {
5979                continue;
5980            }
5981
5982            // Iterate over all of the actions of this result's intent
5983            // filter...  typically this should be just one.
5984            final Iterator<String> it = rii.filter.actionsIterator();
5985            if (it == null) {
5986                continue;
5987            }
5988            while (it.hasNext()) {
5989                final String action = it.next();
5990                if (resultsAction != null && resultsAction.equals(action)) {
5991                    // If this action was explicitly requested, then don't
5992                    // remove things that have it.
5993                    continue;
5994                }
5995                for (int j=i+1; j<N; j++) {
5996                    final ResolveInfo rij = results.get(j);
5997                    if (rij.filter != null && rij.filter.hasAction(action)) {
5998                        results.remove(j);
5999                        if (DEBUG_INTENT_MATCHING) Log.v(
6000                            TAG, "Removing duplicate item from " + j
6001                            + " due to action " + action + " at " + i);
6002                        j--;
6003                        N--;
6004                    }
6005                }
6006            }
6007
6008            // If the caller didn't request filter information, drop it now
6009            // so we don't have to marshall/unmarshall it.
6010            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6011                rii.filter = null;
6012            }
6013        }
6014
6015        // Filter out the caller activity if so requested.
6016        if (caller != null) {
6017            N = results.size();
6018            for (int i=0; i<N; i++) {
6019                ActivityInfo ainfo = results.get(i).activityInfo;
6020                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6021                        && caller.getClassName().equals(ainfo.name)) {
6022                    results.remove(i);
6023                    break;
6024                }
6025            }
6026        }
6027
6028        // If the caller didn't request filter information,
6029        // drop them now so we don't have to
6030        // marshall/unmarshall it.
6031        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6032            N = results.size();
6033            for (int i=0; i<N; i++) {
6034                results.get(i).filter = null;
6035            }
6036        }
6037
6038        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6039        return results;
6040    }
6041
6042    @Override
6043    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6044            String resolvedType, int flags, int userId) {
6045        return new ParceledListSlice<>(
6046                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6047    }
6048
6049    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6050            String resolvedType, int flags, int userId) {
6051        if (!sUserManager.exists(userId)) return Collections.emptyList();
6052        flags = updateFlagsForResolve(flags, userId, intent);
6053        ComponentName comp = intent.getComponent();
6054        if (comp == null) {
6055            if (intent.getSelector() != null) {
6056                intent = intent.getSelector();
6057                comp = intent.getComponent();
6058            }
6059        }
6060        if (comp != null) {
6061            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6062            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6063            if (ai != null) {
6064                ResolveInfo ri = new ResolveInfo();
6065                ri.activityInfo = ai;
6066                list.add(ri);
6067            }
6068            return list;
6069        }
6070
6071        // reader
6072        synchronized (mPackages) {
6073            String pkgName = intent.getPackage();
6074            if (pkgName == null) {
6075                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6076            }
6077            final PackageParser.Package pkg = mPackages.get(pkgName);
6078            if (pkg != null) {
6079                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6080                        userId);
6081            }
6082            return Collections.emptyList();
6083        }
6084    }
6085
6086    @Override
6087    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6088        if (!sUserManager.exists(userId)) return null;
6089        flags = updateFlagsForResolve(flags, userId, intent);
6090        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6091        if (query != null) {
6092            if (query.size() >= 1) {
6093                // If there is more than one service with the same priority,
6094                // just arbitrarily pick the first one.
6095                return query.get(0);
6096            }
6097        }
6098        return null;
6099    }
6100
6101    @Override
6102    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6103            String resolvedType, int flags, int userId) {
6104        return new ParceledListSlice<>(
6105                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6106    }
6107
6108    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6109            String resolvedType, int flags, int userId) {
6110        if (!sUserManager.exists(userId)) return Collections.emptyList();
6111        flags = updateFlagsForResolve(flags, userId, intent);
6112        ComponentName comp = intent.getComponent();
6113        if (comp == null) {
6114            if (intent.getSelector() != null) {
6115                intent = intent.getSelector();
6116                comp = intent.getComponent();
6117            }
6118        }
6119        if (comp != null) {
6120            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6121            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6122            if (si != null) {
6123                final ResolveInfo ri = new ResolveInfo();
6124                ri.serviceInfo = si;
6125                list.add(ri);
6126            }
6127            return list;
6128        }
6129
6130        // reader
6131        synchronized (mPackages) {
6132            String pkgName = intent.getPackage();
6133            if (pkgName == null) {
6134                return mServices.queryIntent(intent, resolvedType, flags, userId);
6135            }
6136            final PackageParser.Package pkg = mPackages.get(pkgName);
6137            if (pkg != null) {
6138                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6139                        userId);
6140            }
6141            return Collections.emptyList();
6142        }
6143    }
6144
6145    @Override
6146    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6147            String resolvedType, int flags, int userId) {
6148        return new ParceledListSlice<>(
6149                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6150    }
6151
6152    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6153            Intent intent, String resolvedType, int flags, int userId) {
6154        if (!sUserManager.exists(userId)) return Collections.emptyList();
6155        flags = updateFlagsForResolve(flags, userId, intent);
6156        ComponentName comp = intent.getComponent();
6157        if (comp == null) {
6158            if (intent.getSelector() != null) {
6159                intent = intent.getSelector();
6160                comp = intent.getComponent();
6161            }
6162        }
6163        if (comp != null) {
6164            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6165            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6166            if (pi != null) {
6167                final ResolveInfo ri = new ResolveInfo();
6168                ri.providerInfo = pi;
6169                list.add(ri);
6170            }
6171            return list;
6172        }
6173
6174        // reader
6175        synchronized (mPackages) {
6176            String pkgName = intent.getPackage();
6177            if (pkgName == null) {
6178                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6179            }
6180            final PackageParser.Package pkg = mPackages.get(pkgName);
6181            if (pkg != null) {
6182                return mProviders.queryIntentForPackage(
6183                        intent, resolvedType, flags, pkg.providers, userId);
6184            }
6185            return Collections.emptyList();
6186        }
6187    }
6188
6189    @Override
6190    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6191        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6192        flags = updateFlagsForPackage(flags, userId, null);
6193        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6194        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6195                true /* requireFullPermission */, false /* checkShell */,
6196                "get installed packages");
6197
6198        // writer
6199        synchronized (mPackages) {
6200            ArrayList<PackageInfo> list;
6201            if (listUninstalled) {
6202                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6203                for (PackageSetting ps : mSettings.mPackages.values()) {
6204                    final PackageInfo pi;
6205                    if (ps.pkg != null) {
6206                        pi = generatePackageInfo(ps, flags, userId);
6207                    } else {
6208                        pi = generatePackageInfo(ps, flags, userId);
6209                    }
6210                    if (pi != null) {
6211                        list.add(pi);
6212                    }
6213                }
6214            } else {
6215                list = new ArrayList<PackageInfo>(mPackages.size());
6216                for (PackageParser.Package p : mPackages.values()) {
6217                    final PackageInfo pi =
6218                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6219                    if (pi != null) {
6220                        list.add(pi);
6221                    }
6222                }
6223            }
6224
6225            return new ParceledListSlice<PackageInfo>(list);
6226        }
6227    }
6228
6229    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6230            String[] permissions, boolean[] tmp, int flags, int userId) {
6231        int numMatch = 0;
6232        final PermissionsState permissionsState = ps.getPermissionsState();
6233        for (int i=0; i<permissions.length; i++) {
6234            final String permission = permissions[i];
6235            if (permissionsState.hasPermission(permission, userId)) {
6236                tmp[i] = true;
6237                numMatch++;
6238            } else {
6239                tmp[i] = false;
6240            }
6241        }
6242        if (numMatch == 0) {
6243            return;
6244        }
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        // The above might return null in cases of uninstalled apps or install-state
6252        // skew across users/profiles.
6253        if (pi != null) {
6254            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6255                if (numMatch == permissions.length) {
6256                    pi.requestedPermissions = permissions;
6257                } else {
6258                    pi.requestedPermissions = new String[numMatch];
6259                    numMatch = 0;
6260                    for (int i=0; i<permissions.length; i++) {
6261                        if (tmp[i]) {
6262                            pi.requestedPermissions[numMatch] = permissions[i];
6263                            numMatch++;
6264                        }
6265                    }
6266                }
6267            }
6268            list.add(pi);
6269        }
6270    }
6271
6272    @Override
6273    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6274            String[] permissions, int flags, int userId) {
6275        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6276        flags = updateFlagsForPackage(flags, userId, permissions);
6277        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6278
6279        // writer
6280        synchronized (mPackages) {
6281            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6282            boolean[] tmpBools = new boolean[permissions.length];
6283            if (listUninstalled) {
6284                for (PackageSetting ps : mSettings.mPackages.values()) {
6285                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6286                }
6287            } else {
6288                for (PackageParser.Package pkg : mPackages.values()) {
6289                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6290                    if (ps != null) {
6291                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6292                                userId);
6293                    }
6294                }
6295            }
6296
6297            return new ParceledListSlice<PackageInfo>(list);
6298        }
6299    }
6300
6301    @Override
6302    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6303        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6304        flags = updateFlagsForApplication(flags, userId, null);
6305        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6306
6307        // writer
6308        synchronized (mPackages) {
6309            ArrayList<ApplicationInfo> list;
6310            if (listUninstalled) {
6311                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6312                for (PackageSetting ps : mSettings.mPackages.values()) {
6313                    ApplicationInfo ai;
6314                    if (ps.pkg != null) {
6315                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6316                                ps.readUserState(userId), userId);
6317                    } else {
6318                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6319                    }
6320                    if (ai != null) {
6321                        list.add(ai);
6322                    }
6323                }
6324            } else {
6325                list = new ArrayList<ApplicationInfo>(mPackages.size());
6326                for (PackageParser.Package p : mPackages.values()) {
6327                    if (p.mExtras != null) {
6328                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6329                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6330                        if (ai != null) {
6331                            list.add(ai);
6332                        }
6333                    }
6334                }
6335            }
6336
6337            return new ParceledListSlice<ApplicationInfo>(list);
6338        }
6339    }
6340
6341    @Override
6342    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6343        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6344            return null;
6345        }
6346
6347        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6348                "getEphemeralApplications");
6349        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6350                true /* requireFullPermission */, false /* checkShell */,
6351                "getEphemeralApplications");
6352        synchronized (mPackages) {
6353            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6354                    .getEphemeralApplicationsLPw(userId);
6355            if (ephemeralApps != null) {
6356                return new ParceledListSlice<>(ephemeralApps);
6357            }
6358        }
6359        return null;
6360    }
6361
6362    @Override
6363    public boolean isEphemeralApplication(String packageName, int userId) {
6364        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6365                true /* requireFullPermission */, false /* checkShell */,
6366                "isEphemeral");
6367        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6368            return false;
6369        }
6370
6371        if (!isCallerSameApp(packageName)) {
6372            return false;
6373        }
6374        synchronized (mPackages) {
6375            PackageParser.Package pkg = mPackages.get(packageName);
6376            if (pkg != null) {
6377                return pkg.applicationInfo.isEphemeralApp();
6378            }
6379        }
6380        return false;
6381    }
6382
6383    @Override
6384    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6385        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6386            return null;
6387        }
6388
6389        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6390                true /* requireFullPermission */, false /* checkShell */,
6391                "getCookie");
6392        if (!isCallerSameApp(packageName)) {
6393            return null;
6394        }
6395        synchronized (mPackages) {
6396            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6397                    packageName, userId);
6398        }
6399    }
6400
6401    @Override
6402    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6403        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6404            return true;
6405        }
6406
6407        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6408                true /* requireFullPermission */, true /* checkShell */,
6409                "setCookie");
6410        if (!isCallerSameApp(packageName)) {
6411            return false;
6412        }
6413        synchronized (mPackages) {
6414            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6415                    packageName, cookie, userId);
6416        }
6417    }
6418
6419    @Override
6420    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6421        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6422            return null;
6423        }
6424
6425        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6426                "getEphemeralApplicationIcon");
6427        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6428                true /* requireFullPermission */, false /* checkShell */,
6429                "getEphemeralApplicationIcon");
6430        synchronized (mPackages) {
6431            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6432                    packageName, userId);
6433        }
6434    }
6435
6436    private boolean isCallerSameApp(String packageName) {
6437        PackageParser.Package pkg = mPackages.get(packageName);
6438        return pkg != null
6439                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6440    }
6441
6442    @Override
6443    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6444        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6445    }
6446
6447    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6448        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6449
6450        // reader
6451        synchronized (mPackages) {
6452            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6453            final int userId = UserHandle.getCallingUserId();
6454            while (i.hasNext()) {
6455                final PackageParser.Package p = i.next();
6456                if (p.applicationInfo == null) continue;
6457
6458                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6459                        && !p.applicationInfo.isDirectBootAware();
6460                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6461                        && p.applicationInfo.isDirectBootAware();
6462
6463                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6464                        && (!mSafeMode || isSystemApp(p))
6465                        && (matchesUnaware || matchesAware)) {
6466                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6467                    if (ps != null) {
6468                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6469                                ps.readUserState(userId), userId);
6470                        if (ai != null) {
6471                            finalList.add(ai);
6472                        }
6473                    }
6474                }
6475            }
6476        }
6477
6478        return finalList;
6479    }
6480
6481    @Override
6482    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6483        if (!sUserManager.exists(userId)) return null;
6484        flags = updateFlagsForComponent(flags, userId, name);
6485        // reader
6486        synchronized (mPackages) {
6487            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6488            PackageSetting ps = provider != null
6489                    ? mSettings.mPackages.get(provider.owner.packageName)
6490                    : null;
6491            return ps != null
6492                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6493                    ? PackageParser.generateProviderInfo(provider, flags,
6494                            ps.readUserState(userId), userId)
6495                    : null;
6496        }
6497    }
6498
6499    /**
6500     * @deprecated
6501     */
6502    @Deprecated
6503    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6504        // reader
6505        synchronized (mPackages) {
6506            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6507                    .entrySet().iterator();
6508            final int userId = UserHandle.getCallingUserId();
6509            while (i.hasNext()) {
6510                Map.Entry<String, PackageParser.Provider> entry = i.next();
6511                PackageParser.Provider p = entry.getValue();
6512                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6513
6514                if (ps != null && p.syncable
6515                        && (!mSafeMode || (p.info.applicationInfo.flags
6516                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6517                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6518                            ps.readUserState(userId), userId);
6519                    if (info != null) {
6520                        outNames.add(entry.getKey());
6521                        outInfo.add(info);
6522                    }
6523                }
6524            }
6525        }
6526    }
6527
6528    @Override
6529    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6530            int uid, int flags) {
6531        final int userId = processName != null ? UserHandle.getUserId(uid)
6532                : UserHandle.getCallingUserId();
6533        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6534        flags = updateFlagsForComponent(flags, userId, processName);
6535
6536        ArrayList<ProviderInfo> finalList = null;
6537        // reader
6538        synchronized (mPackages) {
6539            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6540            while (i.hasNext()) {
6541                final PackageParser.Provider p = i.next();
6542                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6543                if (ps != null && p.info.authority != null
6544                        && (processName == null
6545                                || (p.info.processName.equals(processName)
6546                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6547                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6548                    if (finalList == null) {
6549                        finalList = new ArrayList<ProviderInfo>(3);
6550                    }
6551                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6552                            ps.readUserState(userId), userId);
6553                    if (info != null) {
6554                        finalList.add(info);
6555                    }
6556                }
6557            }
6558        }
6559
6560        if (finalList != null) {
6561            Collections.sort(finalList, mProviderInitOrderSorter);
6562            return new ParceledListSlice<ProviderInfo>(finalList);
6563        }
6564
6565        return ParceledListSlice.emptyList();
6566    }
6567
6568    @Override
6569    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6570        // reader
6571        synchronized (mPackages) {
6572            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6573            return PackageParser.generateInstrumentationInfo(i, flags);
6574        }
6575    }
6576
6577    @Override
6578    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6579            String targetPackage, int flags) {
6580        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6581    }
6582
6583    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6584            int flags) {
6585        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6586
6587        // reader
6588        synchronized (mPackages) {
6589            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6590            while (i.hasNext()) {
6591                final PackageParser.Instrumentation p = i.next();
6592                if (targetPackage == null
6593                        || targetPackage.equals(p.info.targetPackage)) {
6594                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6595                            flags);
6596                    if (ii != null) {
6597                        finalList.add(ii);
6598                    }
6599                }
6600            }
6601        }
6602
6603        return finalList;
6604    }
6605
6606    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6607        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6608        if (overlays == null) {
6609            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6610            return;
6611        }
6612        for (PackageParser.Package opkg : overlays.values()) {
6613            // Not much to do if idmap fails: we already logged the error
6614            // and we certainly don't want to abort installation of pkg simply
6615            // because an overlay didn't fit properly. For these reasons,
6616            // ignore the return value of createIdmapForPackagePairLI.
6617            createIdmapForPackagePairLI(pkg, opkg);
6618        }
6619    }
6620
6621    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6622            PackageParser.Package opkg) {
6623        if (!opkg.mTrustedOverlay) {
6624            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6625                    opkg.baseCodePath + ": overlay not trusted");
6626            return false;
6627        }
6628        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6629        if (overlaySet == null) {
6630            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6631                    opkg.baseCodePath + " but target package has no known overlays");
6632            return false;
6633        }
6634        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6635        // TODO: generate idmap for split APKs
6636        try {
6637            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6638        } catch (InstallerException e) {
6639            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6640                    + opkg.baseCodePath);
6641            return false;
6642        }
6643        PackageParser.Package[] overlayArray =
6644            overlaySet.values().toArray(new PackageParser.Package[0]);
6645        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6646            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6647                return p1.mOverlayPriority - p2.mOverlayPriority;
6648            }
6649        };
6650        Arrays.sort(overlayArray, cmp);
6651
6652        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6653        int i = 0;
6654        for (PackageParser.Package p : overlayArray) {
6655            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6656        }
6657        return true;
6658    }
6659
6660    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6661        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6662        try {
6663            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6664        } finally {
6665            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6666        }
6667    }
6668
6669    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6670        final File[] files = dir.listFiles();
6671        if (ArrayUtils.isEmpty(files)) {
6672            Log.d(TAG, "No files in app dir " + dir);
6673            return;
6674        }
6675
6676        if (DEBUG_PACKAGE_SCANNING) {
6677            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6678                    + " flags=0x" + Integer.toHexString(parseFlags));
6679        }
6680
6681        for (File file : files) {
6682            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6683                    && !PackageInstallerService.isStageName(file.getName());
6684            if (!isPackage) {
6685                // Ignore entries which are not packages
6686                continue;
6687            }
6688            try {
6689                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6690                        scanFlags, currentTime, null);
6691            } catch (PackageManagerException e) {
6692                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6693
6694                // Delete invalid userdata apps
6695                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6696                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6697                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6698                    removeCodePathLI(file);
6699                }
6700            }
6701        }
6702    }
6703
6704    private static File getSettingsProblemFile() {
6705        File dataDir = Environment.getDataDirectory();
6706        File systemDir = new File(dataDir, "system");
6707        File fname = new File(systemDir, "uiderrors.txt");
6708        return fname;
6709    }
6710
6711    static void reportSettingsProblem(int priority, String msg) {
6712        logCriticalInfo(priority, msg);
6713    }
6714
6715    static void logCriticalInfo(int priority, String msg) {
6716        Slog.println(priority, TAG, msg);
6717        EventLogTags.writePmCriticalInfo(msg);
6718        try {
6719            File fname = getSettingsProblemFile();
6720            FileOutputStream out = new FileOutputStream(fname, true);
6721            PrintWriter pw = new FastPrintWriter(out);
6722            SimpleDateFormat formatter = new SimpleDateFormat();
6723            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6724            pw.println(dateString + ": " + msg);
6725            pw.close();
6726            FileUtils.setPermissions(
6727                    fname.toString(),
6728                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6729                    -1, -1);
6730        } catch (java.io.IOException e) {
6731        }
6732    }
6733
6734    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6735        if (srcFile.isDirectory()) {
6736            final File baseFile = new File(pkg.baseCodePath);
6737            long maxModifiedTime = baseFile.lastModified();
6738            if (pkg.splitCodePaths != null) {
6739                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6740                    final File splitFile = new File(pkg.splitCodePaths[i]);
6741                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6742                }
6743            }
6744            return maxModifiedTime;
6745        }
6746        return srcFile.lastModified();
6747    }
6748
6749    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6750            final int policyFlags) throws PackageManagerException {
6751        // When upgrading from pre-N MR1, verify the package time stamp using the package
6752        // directory and not the APK file.
6753        final long lastModifiedTime = mIsPreNMR1Upgrade
6754                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6755        if (ps != null
6756                && ps.codePath.equals(srcFile)
6757                && ps.timeStamp == lastModifiedTime
6758                && !isCompatSignatureUpdateNeeded(pkg)
6759                && !isRecoverSignatureUpdateNeeded(pkg)) {
6760            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6761            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6762            ArraySet<PublicKey> signingKs;
6763            synchronized (mPackages) {
6764                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6765            }
6766            if (ps.signatures.mSignatures != null
6767                    && ps.signatures.mSignatures.length != 0
6768                    && signingKs != null) {
6769                // Optimization: reuse the existing cached certificates
6770                // if the package appears to be unchanged.
6771                pkg.mSignatures = ps.signatures.mSignatures;
6772                pkg.mSigningKeys = signingKs;
6773                return;
6774            }
6775
6776            Slog.w(TAG, "PackageSetting for " + ps.name
6777                    + " is missing signatures.  Collecting certs again to recover them.");
6778        } else {
6779            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6780        }
6781
6782        try {
6783            PackageParser.collectCertificates(pkg, policyFlags);
6784        } catch (PackageParserException e) {
6785            throw PackageManagerException.from(e);
6786        }
6787    }
6788
6789    /**
6790     *  Traces a package scan.
6791     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6792     */
6793    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6794            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6795        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6796        try {
6797            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6798        } finally {
6799            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6800        }
6801    }
6802
6803    /**
6804     *  Scans a package and returns the newly parsed package.
6805     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6806     */
6807    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6808            long currentTime, UserHandle user) throws PackageManagerException {
6809        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6810        PackageParser pp = new PackageParser();
6811        pp.setSeparateProcesses(mSeparateProcesses);
6812        pp.setOnlyCoreApps(mOnlyCore);
6813        pp.setDisplayMetrics(mMetrics);
6814
6815        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6816            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6817        }
6818
6819        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6820        final PackageParser.Package pkg;
6821        try {
6822            pkg = pp.parsePackage(scanFile, parseFlags);
6823        } catch (PackageParserException e) {
6824            throw PackageManagerException.from(e);
6825        } finally {
6826            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6827        }
6828
6829        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6830    }
6831
6832    /**
6833     *  Scans a package and returns the newly parsed package.
6834     *  @throws PackageManagerException on a parse error.
6835     */
6836    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6837            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6838            throws PackageManagerException {
6839        // If the package has children and this is the first dive in the function
6840        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6841        // packages (parent and children) would be successfully scanned before the
6842        // actual scan since scanning mutates internal state and we want to atomically
6843        // install the package and its children.
6844        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6845            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6846                scanFlags |= SCAN_CHECK_ONLY;
6847            }
6848        } else {
6849            scanFlags &= ~SCAN_CHECK_ONLY;
6850        }
6851
6852        // Scan the parent
6853        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6854                scanFlags, currentTime, user);
6855
6856        // Scan the children
6857        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6858        for (int i = 0; i < childCount; i++) {
6859            PackageParser.Package childPackage = pkg.childPackages.get(i);
6860            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6861                    currentTime, user);
6862        }
6863
6864
6865        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6866            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6867        }
6868
6869        return scannedPkg;
6870    }
6871
6872    /**
6873     *  Scans a package and returns the newly parsed package.
6874     *  @throws PackageManagerException on a parse error.
6875     */
6876    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6877            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6878            throws PackageManagerException {
6879        PackageSetting ps = null;
6880        PackageSetting updatedPkg;
6881        // reader
6882        synchronized (mPackages) {
6883            // Look to see if we already know about this package.
6884            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6885            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6886                // This package has been renamed to its original name.  Let's
6887                // use that.
6888                ps = mSettings.peekPackageLPr(oldName);
6889            }
6890            // If there was no original package, see one for the real package name.
6891            if (ps == null) {
6892                ps = mSettings.peekPackageLPr(pkg.packageName);
6893            }
6894            // Check to see if this package could be hiding/updating a system
6895            // package.  Must look for it either under the original or real
6896            // package name depending on our state.
6897            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6898            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6899
6900            // If this is a package we don't know about on the system partition, we
6901            // may need to remove disabled child packages on the system partition
6902            // or may need to not add child packages if the parent apk is updated
6903            // on the data partition and no longer defines this child package.
6904            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6905                // If this is a parent package for an updated system app and this system
6906                // app got an OTA update which no longer defines some of the child packages
6907                // we have to prune them from the disabled system packages.
6908                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6909                if (disabledPs != null) {
6910                    final int scannedChildCount = (pkg.childPackages != null)
6911                            ? pkg.childPackages.size() : 0;
6912                    final int disabledChildCount = disabledPs.childPackageNames != null
6913                            ? disabledPs.childPackageNames.size() : 0;
6914                    for (int i = 0; i < disabledChildCount; i++) {
6915                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6916                        boolean disabledPackageAvailable = false;
6917                        for (int j = 0; j < scannedChildCount; j++) {
6918                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6919                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6920                                disabledPackageAvailable = true;
6921                                break;
6922                            }
6923                         }
6924                         if (!disabledPackageAvailable) {
6925                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6926                         }
6927                    }
6928                }
6929            }
6930        }
6931
6932        boolean updatedPkgBetter = false;
6933        // First check if this is a system package that may involve an update
6934        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6935            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6936            // it needs to drop FLAG_PRIVILEGED.
6937            if (locationIsPrivileged(scanFile)) {
6938                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6939            } else {
6940                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6941            }
6942
6943            if (ps != null && !ps.codePath.equals(scanFile)) {
6944                // The path has changed from what was last scanned...  check the
6945                // version of the new path against what we have stored to determine
6946                // what to do.
6947                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6948                if (pkg.mVersionCode <= ps.versionCode) {
6949                    // The system package has been updated and the code path does not match
6950                    // Ignore entry. Skip it.
6951                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6952                            + " ignored: updated version " + ps.versionCode
6953                            + " better than this " + pkg.mVersionCode);
6954                    if (!updatedPkg.codePath.equals(scanFile)) {
6955                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6956                                + ps.name + " changing from " + updatedPkg.codePathString
6957                                + " to " + scanFile);
6958                        updatedPkg.codePath = scanFile;
6959                        updatedPkg.codePathString = scanFile.toString();
6960                        updatedPkg.resourcePath = scanFile;
6961                        updatedPkg.resourcePathString = scanFile.toString();
6962                    }
6963                    updatedPkg.pkg = pkg;
6964                    updatedPkg.versionCode = pkg.mVersionCode;
6965
6966                    // Update the disabled system child packages to point to the package too.
6967                    final int childCount = updatedPkg.childPackageNames != null
6968                            ? updatedPkg.childPackageNames.size() : 0;
6969                    for (int i = 0; i < childCount; i++) {
6970                        String childPackageName = updatedPkg.childPackageNames.get(i);
6971                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6972                                childPackageName);
6973                        if (updatedChildPkg != null) {
6974                            updatedChildPkg.pkg = pkg;
6975                            updatedChildPkg.versionCode = pkg.mVersionCode;
6976                        }
6977                    }
6978
6979                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6980                            + scanFile + " ignored: updated version " + ps.versionCode
6981                            + " better than this " + pkg.mVersionCode);
6982                } else {
6983                    // The current app on the system partition is better than
6984                    // what we have updated to on the data partition; switch
6985                    // back to the system partition version.
6986                    // At this point, its safely assumed that package installation for
6987                    // apps in system partition will go through. If not there won't be a working
6988                    // version of the app
6989                    // writer
6990                    synchronized (mPackages) {
6991                        // Just remove the loaded entries from package lists.
6992                        mPackages.remove(ps.name);
6993                    }
6994
6995                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6996                            + " reverting from " + ps.codePathString
6997                            + ": new version " + pkg.mVersionCode
6998                            + " better than installed " + ps.versionCode);
6999
7000                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7001                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7002                    synchronized (mInstallLock) {
7003                        args.cleanUpResourcesLI();
7004                    }
7005                    synchronized (mPackages) {
7006                        mSettings.enableSystemPackageLPw(ps.name);
7007                    }
7008                    updatedPkgBetter = true;
7009                }
7010            }
7011        }
7012
7013        if (updatedPkg != null) {
7014            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7015            // initially
7016            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7017
7018            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7019            // flag set initially
7020            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7021                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7022            }
7023        }
7024
7025        // Verify certificates against what was last scanned
7026        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7027
7028        /*
7029         * A new system app appeared, but we already had a non-system one of the
7030         * same name installed earlier.
7031         */
7032        boolean shouldHideSystemApp = false;
7033        if (updatedPkg == null && ps != null
7034                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7035            /*
7036             * Check to make sure the signatures match first. If they don't,
7037             * wipe the installed application and its data.
7038             */
7039            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7040                    != PackageManager.SIGNATURE_MATCH) {
7041                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7042                        + " signatures don't match existing userdata copy; removing");
7043                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7044                        "scanPackageInternalLI")) {
7045                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7046                }
7047                ps = null;
7048            } else {
7049                /*
7050                 * If the newly-added system app is an older version than the
7051                 * already installed version, hide it. It will be scanned later
7052                 * and re-added like an update.
7053                 */
7054                if (pkg.mVersionCode <= ps.versionCode) {
7055                    shouldHideSystemApp = true;
7056                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7057                            + " but new version " + pkg.mVersionCode + " better than installed "
7058                            + ps.versionCode + "; hiding system");
7059                } else {
7060                    /*
7061                     * The newly found system app is a newer version that the
7062                     * one previously installed. Simply remove the
7063                     * already-installed application and replace it with our own
7064                     * while keeping the application data.
7065                     */
7066                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7067                            + " reverting from " + ps.codePathString + ": new version "
7068                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7069                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7070                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7071                    synchronized (mInstallLock) {
7072                        args.cleanUpResourcesLI();
7073                    }
7074                }
7075            }
7076        }
7077
7078        // The apk is forward locked (not public) if its code and resources
7079        // are kept in different files. (except for app in either system or
7080        // vendor path).
7081        // TODO grab this value from PackageSettings
7082        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7083            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7084                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7085            }
7086        }
7087
7088        // TODO: extend to support forward-locked splits
7089        String resourcePath = null;
7090        String baseResourcePath = null;
7091        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7092            if (ps != null && ps.resourcePathString != null) {
7093                resourcePath = ps.resourcePathString;
7094                baseResourcePath = ps.resourcePathString;
7095            } else {
7096                // Should not happen at all. Just log an error.
7097                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7098            }
7099        } else {
7100            resourcePath = pkg.codePath;
7101            baseResourcePath = pkg.baseCodePath;
7102        }
7103
7104        // Set application objects path explicitly.
7105        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7106        pkg.setApplicationInfoCodePath(pkg.codePath);
7107        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7108        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7109        pkg.setApplicationInfoResourcePath(resourcePath);
7110        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7111        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7112
7113        // Note that we invoke the following method only if we are about to unpack an application
7114        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7115                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7116
7117        /*
7118         * If the system app should be overridden by a previously installed
7119         * data, hide the system app now and let the /data/app scan pick it up
7120         * again.
7121         */
7122        if (shouldHideSystemApp) {
7123            synchronized (mPackages) {
7124                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7125            }
7126        }
7127
7128        return scannedPkg;
7129    }
7130
7131    private static String fixProcessName(String defProcessName,
7132            String processName, int uid) {
7133        if (processName == null) {
7134            return defProcessName;
7135        }
7136        return processName;
7137    }
7138
7139    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7140            throws PackageManagerException {
7141        if (pkgSetting.signatures.mSignatures != null) {
7142            // Already existing package. Make sure signatures match
7143            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7144                    == PackageManager.SIGNATURE_MATCH;
7145            if (!match) {
7146                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7147                        == PackageManager.SIGNATURE_MATCH;
7148            }
7149            if (!match) {
7150                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7151                        == PackageManager.SIGNATURE_MATCH;
7152            }
7153            if (!match) {
7154                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7155                        + pkg.packageName + " signatures do not match the "
7156                        + "previously installed version; ignoring!");
7157            }
7158        }
7159
7160        // Check for shared user signatures
7161        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7162            // Already existing package. Make sure signatures match
7163            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7164                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7165            if (!match) {
7166                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7167                        == PackageManager.SIGNATURE_MATCH;
7168            }
7169            if (!match) {
7170                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7171                        == PackageManager.SIGNATURE_MATCH;
7172            }
7173            if (!match) {
7174                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7175                        "Package " + pkg.packageName
7176                        + " has no signatures that match those in shared user "
7177                        + pkgSetting.sharedUser.name + "; ignoring!");
7178            }
7179        }
7180    }
7181
7182    /**
7183     * Enforces that only the system UID or root's UID can call a method exposed
7184     * via Binder.
7185     *
7186     * @param message used as message if SecurityException is thrown
7187     * @throws SecurityException if the caller is not system or root
7188     */
7189    private static final void enforceSystemOrRoot(String message) {
7190        final int uid = Binder.getCallingUid();
7191        if (uid != Process.SYSTEM_UID && uid != 0) {
7192            throw new SecurityException(message);
7193        }
7194    }
7195
7196    @Override
7197    public void performFstrimIfNeeded() {
7198        enforceSystemOrRoot("Only the system can request fstrim");
7199
7200        // Before everything else, see whether we need to fstrim.
7201        try {
7202            IMountService ms = PackageHelper.getMountService();
7203            if (ms != null) {
7204                boolean doTrim = false;
7205                final long interval = android.provider.Settings.Global.getLong(
7206                        mContext.getContentResolver(),
7207                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7208                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7209                if (interval > 0) {
7210                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7211                    if (timeSinceLast > interval) {
7212                        doTrim = true;
7213                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7214                                + "; running immediately");
7215                    }
7216                }
7217                if (doTrim) {
7218                    final boolean dexOptDialogShown;
7219                    synchronized (mPackages) {
7220                        dexOptDialogShown = mDexOptDialogShown;
7221                    }
7222                    if (!isFirstBoot() && dexOptDialogShown) {
7223                        try {
7224                            ActivityManagerNative.getDefault().showBootMessage(
7225                                    mContext.getResources().getString(
7226                                            R.string.android_upgrading_fstrim), true);
7227                        } catch (RemoteException e) {
7228                        }
7229                    }
7230                    ms.runMaintenance();
7231                }
7232            } else {
7233                Slog.e(TAG, "Mount service unavailable!");
7234            }
7235        } catch (RemoteException e) {
7236            // Can't happen; MountService is local
7237        }
7238    }
7239
7240    @Override
7241    public void updatePackagesIfNeeded() {
7242        enforceSystemOrRoot("Only the system can request package update");
7243
7244        // We need to re-extract after an OTA.
7245        boolean causeUpgrade = isUpgrade();
7246
7247        // First boot or factory reset.
7248        // Note: we also handle devices that are upgrading to N right now as if it is their
7249        //       first boot, as they do not have profile data.
7250        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7251
7252        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7253        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7254
7255        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7256            return;
7257        }
7258
7259        List<PackageParser.Package> pkgs;
7260        synchronized (mPackages) {
7261            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7262        }
7263
7264        final long startTime = System.nanoTime();
7265        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7266                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7267
7268        final int elapsedTimeSeconds =
7269                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7270
7271        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7272        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7273        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7274        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7275        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7276    }
7277
7278    /**
7279     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7280     * containing statistics about the invocation. The array consists of three elements,
7281     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7282     * and {@code numberOfPackagesFailed}.
7283     */
7284    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7285            String compilerFilter) {
7286
7287        int numberOfPackagesVisited = 0;
7288        int numberOfPackagesOptimized = 0;
7289        int numberOfPackagesSkipped = 0;
7290        int numberOfPackagesFailed = 0;
7291        final int numberOfPackagesToDexopt = pkgs.size();
7292
7293        for (PackageParser.Package pkg : pkgs) {
7294            numberOfPackagesVisited++;
7295
7296            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7297                if (DEBUG_DEXOPT) {
7298                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7299                }
7300                numberOfPackagesSkipped++;
7301                continue;
7302            }
7303
7304            if (DEBUG_DEXOPT) {
7305                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7306                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7307            }
7308
7309            if (showDialog) {
7310                try {
7311                    ActivityManagerNative.getDefault().showBootMessage(
7312                            mContext.getResources().getString(R.string.android_upgrading_apk,
7313                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7314                } catch (RemoteException e) {
7315                }
7316                synchronized (mPackages) {
7317                    mDexOptDialogShown = true;
7318                }
7319            }
7320
7321            // If the OTA updates a system app which was previously preopted to a non-preopted state
7322            // the app might end up being verified at runtime. That's because by default the apps
7323            // are verify-profile but for preopted apps there's no profile.
7324            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7325            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7326            // filter (by default interpret-only).
7327            // Note that at this stage unused apps are already filtered.
7328            if (isSystemApp(pkg) &&
7329                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7330                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7331                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7332            }
7333
7334            // If the OTA updates a system app which was previously preopted to a non-preopted state
7335            // the app might end up being verified at runtime. That's because by default the apps
7336            // are verify-profile but for preopted apps there's no profile.
7337            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7338            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7339            // filter (by default interpret-only).
7340            // Note that at this stage unused apps are already filtered.
7341            if (isSystemApp(pkg) &&
7342                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7343                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7344                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7345            }
7346
7347            // checkProfiles is false to avoid merging profiles during boot which
7348            // might interfere with background compilation (b/28612421).
7349            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7350            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7351            // trade-off worth doing to save boot time work.
7352            int dexOptStatus = performDexOptTraced(pkg.packageName,
7353                    false /* checkProfiles */,
7354                    compilerFilter,
7355                    false /* force */);
7356            switch (dexOptStatus) {
7357                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7358                    numberOfPackagesOptimized++;
7359                    break;
7360                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7361                    numberOfPackagesSkipped++;
7362                    break;
7363                case PackageDexOptimizer.DEX_OPT_FAILED:
7364                    numberOfPackagesFailed++;
7365                    break;
7366                default:
7367                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7368                    break;
7369            }
7370        }
7371
7372        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7373                numberOfPackagesFailed };
7374    }
7375
7376    @Override
7377    public void notifyPackageUse(String packageName, int reason) {
7378        synchronized (mPackages) {
7379            PackageParser.Package p = mPackages.get(packageName);
7380            if (p == null) {
7381                return;
7382            }
7383            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7384        }
7385    }
7386
7387    @Override
7388    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
7389        int userId = UserHandle.getCallingUserId();
7390        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
7391        if (ai == null) {
7392            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
7393                + loadingPackageName + ", user=" + userId);
7394            return;
7395        }
7396        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
7397    }
7398
7399    // TODO: this is not used nor needed. Delete it.
7400    @Override
7401    public boolean performDexOptIfNeeded(String packageName) {
7402        int dexOptStatus = performDexOptTraced(packageName,
7403                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7404        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7405    }
7406
7407    @Override
7408    public boolean performDexOpt(String packageName,
7409            boolean checkProfiles, int compileReason, boolean force) {
7410        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7411                getCompilerFilterForReason(compileReason), force);
7412        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7413    }
7414
7415    @Override
7416    public boolean performDexOptMode(String packageName,
7417            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7418        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7419                targetCompilerFilter, force);
7420        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7421    }
7422
7423    private int performDexOptTraced(String packageName,
7424                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7425        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7426        try {
7427            return performDexOptInternal(packageName, checkProfiles,
7428                    targetCompilerFilter, force);
7429        } finally {
7430            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7431        }
7432    }
7433
7434    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7435    // if the package can now be considered up to date for the given filter.
7436    private int performDexOptInternal(String packageName,
7437                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7438        PackageParser.Package p;
7439        synchronized (mPackages) {
7440            p = mPackages.get(packageName);
7441            if (p == null) {
7442                // Package could not be found. Report failure.
7443                return PackageDexOptimizer.DEX_OPT_FAILED;
7444            }
7445            mPackageUsage.maybeWriteAsync(mPackages);
7446            mCompilerStats.maybeWriteAsync();
7447        }
7448        long callingId = Binder.clearCallingIdentity();
7449        try {
7450            synchronized (mInstallLock) {
7451                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7452                        targetCompilerFilter, force);
7453            }
7454        } finally {
7455            Binder.restoreCallingIdentity(callingId);
7456        }
7457    }
7458
7459    public ArraySet<String> getOptimizablePackages() {
7460        ArraySet<String> pkgs = new ArraySet<String>();
7461        synchronized (mPackages) {
7462            for (PackageParser.Package p : mPackages.values()) {
7463                if (PackageDexOptimizer.canOptimizePackage(p)) {
7464                    pkgs.add(p.packageName);
7465                }
7466            }
7467        }
7468        return pkgs;
7469    }
7470
7471    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7472            boolean checkProfiles, String targetCompilerFilter,
7473            boolean force) {
7474        // Select the dex optimizer based on the force parameter.
7475        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7476        //       allocate an object here.
7477        PackageDexOptimizer pdo = force
7478                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7479                : mPackageDexOptimizer;
7480
7481        // Optimize all dependencies first. Note: we ignore the return value and march on
7482        // on errors.
7483        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7484        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7485        if (!deps.isEmpty()) {
7486            for (PackageParser.Package depPackage : deps) {
7487                // TODO: Analyze and investigate if we (should) profile libraries.
7488                // Currently this will do a full compilation of the library by default.
7489                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7490                        false /* checkProfiles */,
7491                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7492                        getOrCreateCompilerPackageStats(depPackage));
7493            }
7494        }
7495        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7496                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7497    }
7498
7499    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7500        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7501            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7502            Set<String> collectedNames = new HashSet<>();
7503            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7504
7505            retValue.remove(p);
7506
7507            return retValue;
7508        } else {
7509            return Collections.emptyList();
7510        }
7511    }
7512
7513    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7514            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7515        if (!collectedNames.contains(p.packageName)) {
7516            collectedNames.add(p.packageName);
7517            collected.add(p);
7518
7519            if (p.usesLibraries != null) {
7520                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7521            }
7522            if (p.usesOptionalLibraries != null) {
7523                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7524                        collectedNames);
7525            }
7526        }
7527    }
7528
7529    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7530            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7531        for (String libName : libs) {
7532            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7533            if (libPkg != null) {
7534                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7535            }
7536        }
7537    }
7538
7539    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7540        synchronized (mPackages) {
7541            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7542            if (lib != null && lib.apk != null) {
7543                return mPackages.get(lib.apk);
7544            }
7545        }
7546        return null;
7547    }
7548
7549    public void shutdown() {
7550        mPackageUsage.writeNow(mPackages);
7551        mCompilerStats.writeNow();
7552    }
7553
7554    @Override
7555    public void dumpProfiles(String packageName) {
7556        PackageParser.Package pkg;
7557        synchronized (mPackages) {
7558            pkg = mPackages.get(packageName);
7559            if (pkg == null) {
7560                throw new IllegalArgumentException("Unknown package: " + packageName);
7561            }
7562        }
7563        /* Only the shell, root, or the app user should be able to dump profiles. */
7564        int callingUid = Binder.getCallingUid();
7565        if (callingUid != Process.SHELL_UID &&
7566            callingUid != Process.ROOT_UID &&
7567            callingUid != pkg.applicationInfo.uid) {
7568            throw new SecurityException("dumpProfiles");
7569        }
7570
7571        synchronized (mInstallLock) {
7572            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7573            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7574            try {
7575                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7576                String codePaths = TextUtils.join(";", allCodePaths);
7577                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
7578            } catch (InstallerException e) {
7579                Slog.w(TAG, "Failed to dump profiles", e);
7580            }
7581            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7582        }
7583    }
7584
7585    @Override
7586    public void forceDexOpt(String packageName) {
7587        enforceSystemOrRoot("forceDexOpt");
7588
7589        PackageParser.Package pkg;
7590        synchronized (mPackages) {
7591            pkg = mPackages.get(packageName);
7592            if (pkg == null) {
7593                throw new IllegalArgumentException("Unknown package: " + packageName);
7594            }
7595        }
7596
7597        synchronized (mInstallLock) {
7598            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7599
7600            // Whoever is calling forceDexOpt wants a fully compiled package.
7601            // Don't use profiles since that may cause compilation to be skipped.
7602            final int res = performDexOptInternalWithDependenciesLI(pkg,
7603                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7604                    true /* force */);
7605
7606            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7607            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7608                throw new IllegalStateException("Failed to dexopt: " + res);
7609            }
7610        }
7611    }
7612
7613    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7614        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7615            Slog.w(TAG, "Unable to update from " + oldPkg.name
7616                    + " to " + newPkg.packageName
7617                    + ": old package not in system partition");
7618            return false;
7619        } else if (mPackages.get(oldPkg.name) != null) {
7620            Slog.w(TAG, "Unable to update from " + oldPkg.name
7621                    + " to " + newPkg.packageName
7622                    + ": old package still exists");
7623            return false;
7624        }
7625        return true;
7626    }
7627
7628    void removeCodePathLI(File codePath) {
7629        if (codePath.isDirectory()) {
7630            try {
7631                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7632            } catch (InstallerException e) {
7633                Slog.w(TAG, "Failed to remove code path", e);
7634            }
7635        } else {
7636            codePath.delete();
7637        }
7638    }
7639
7640    private int[] resolveUserIds(int userId) {
7641        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7642    }
7643
7644    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7645        if (pkg == null) {
7646            Slog.wtf(TAG, "Package was null!", new Throwable());
7647            return;
7648        }
7649        clearAppDataLeafLIF(pkg, userId, flags);
7650        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7651        for (int i = 0; i < childCount; i++) {
7652            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7653        }
7654    }
7655
7656    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7657        final PackageSetting ps;
7658        synchronized (mPackages) {
7659            ps = mSettings.mPackages.get(pkg.packageName);
7660        }
7661        for (int realUserId : resolveUserIds(userId)) {
7662            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7663            try {
7664                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7665                        ceDataInode);
7666            } catch (InstallerException e) {
7667                Slog.w(TAG, String.valueOf(e));
7668            }
7669        }
7670    }
7671
7672    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7673        if (pkg == null) {
7674            Slog.wtf(TAG, "Package was null!", new Throwable());
7675            return;
7676        }
7677        destroyAppDataLeafLIF(pkg, userId, flags);
7678        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7679        for (int i = 0; i < childCount; i++) {
7680            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7681        }
7682    }
7683
7684    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7685        final PackageSetting ps;
7686        synchronized (mPackages) {
7687            ps = mSettings.mPackages.get(pkg.packageName);
7688        }
7689        for (int realUserId : resolveUserIds(userId)) {
7690            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7691            try {
7692                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7693                        ceDataInode);
7694            } catch (InstallerException e) {
7695                Slog.w(TAG, String.valueOf(e));
7696            }
7697        }
7698    }
7699
7700    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7701        if (pkg == null) {
7702            Slog.wtf(TAG, "Package was null!", new Throwable());
7703            return;
7704        }
7705        destroyAppProfilesLeafLIF(pkg);
7706        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7707        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7708        for (int i = 0; i < childCount; i++) {
7709            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7710            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7711                    true /* removeBaseMarker */);
7712        }
7713    }
7714
7715    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7716            boolean removeBaseMarker) {
7717        if (pkg.isForwardLocked()) {
7718            return;
7719        }
7720
7721        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7722            try {
7723                path = PackageManagerServiceUtils.realpath(new File(path));
7724            } catch (IOException e) {
7725                // TODO: Should we return early here ?
7726                Slog.w(TAG, "Failed to get canonical path", e);
7727                continue;
7728            }
7729
7730            final String useMarker = path.replace('/', '@');
7731            for (int realUserId : resolveUserIds(userId)) {
7732                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7733                if (removeBaseMarker) {
7734                    File foreignUseMark = new File(profileDir, useMarker);
7735                    if (foreignUseMark.exists()) {
7736                        if (!foreignUseMark.delete()) {
7737                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7738                                    + pkg.packageName);
7739                        }
7740                    }
7741                }
7742
7743                File[] markers = profileDir.listFiles();
7744                if (markers != null) {
7745                    final String searchString = "@" + pkg.packageName + "@";
7746                    // We also delete all markers that contain the package name we're
7747                    // uninstalling. These are associated with secondary dex-files belonging
7748                    // to the package. Reconstructing the path of these dex files is messy
7749                    // in general.
7750                    for (File marker : markers) {
7751                        if (marker.getName().indexOf(searchString) > 0) {
7752                            if (!marker.delete()) {
7753                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7754                                    + pkg.packageName);
7755                            }
7756                        }
7757                    }
7758                }
7759            }
7760        }
7761    }
7762
7763    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7764        try {
7765            mInstaller.destroyAppProfiles(pkg.packageName);
7766        } catch (InstallerException e) {
7767            Slog.w(TAG, String.valueOf(e));
7768        }
7769    }
7770
7771    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7772        if (pkg == null) {
7773            Slog.wtf(TAG, "Package was null!", new Throwable());
7774            return;
7775        }
7776        clearAppProfilesLeafLIF(pkg);
7777        // We don't remove the base foreign use marker when clearing profiles because
7778        // we will rename it when the app is updated. Unlike the actual profile contents,
7779        // the foreign use marker is good across installs.
7780        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7781        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7782        for (int i = 0; i < childCount; i++) {
7783            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7784        }
7785    }
7786
7787    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7788        try {
7789            mInstaller.clearAppProfiles(pkg.packageName);
7790        } catch (InstallerException e) {
7791            Slog.w(TAG, String.valueOf(e));
7792        }
7793    }
7794
7795    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7796            long lastUpdateTime) {
7797        // Set parent install/update time
7798        PackageSetting ps = (PackageSetting) pkg.mExtras;
7799        if (ps != null) {
7800            ps.firstInstallTime = firstInstallTime;
7801            ps.lastUpdateTime = lastUpdateTime;
7802        }
7803        // Set children install/update time
7804        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7805        for (int i = 0; i < childCount; i++) {
7806            PackageParser.Package childPkg = pkg.childPackages.get(i);
7807            ps = (PackageSetting) childPkg.mExtras;
7808            if (ps != null) {
7809                ps.firstInstallTime = firstInstallTime;
7810                ps.lastUpdateTime = lastUpdateTime;
7811            }
7812        }
7813    }
7814
7815    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7816            PackageParser.Package changingLib) {
7817        if (file.path != null) {
7818            usesLibraryFiles.add(file.path);
7819            return;
7820        }
7821        PackageParser.Package p = mPackages.get(file.apk);
7822        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7823            // If we are doing this while in the middle of updating a library apk,
7824            // then we need to make sure to use that new apk for determining the
7825            // dependencies here.  (We haven't yet finished committing the new apk
7826            // to the package manager state.)
7827            if (p == null || p.packageName.equals(changingLib.packageName)) {
7828                p = changingLib;
7829            }
7830        }
7831        if (p != null) {
7832            usesLibraryFiles.addAll(p.getAllCodePaths());
7833        }
7834    }
7835
7836    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7837            PackageParser.Package changingLib) throws PackageManagerException {
7838        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7839            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7840            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7841            for (int i=0; i<N; i++) {
7842                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7843                if (file == null) {
7844                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7845                            "Package " + pkg.packageName + " requires unavailable shared library "
7846                            + pkg.usesLibraries.get(i) + "; failing!");
7847                }
7848                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7849            }
7850            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7851            for (int i=0; i<N; i++) {
7852                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7853                if (file == null) {
7854                    Slog.w(TAG, "Package " + pkg.packageName
7855                            + " desires unavailable shared library "
7856                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7857                } else {
7858                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7859                }
7860            }
7861            N = usesLibraryFiles.size();
7862            if (N > 0) {
7863                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7864            } else {
7865                pkg.usesLibraryFiles = null;
7866            }
7867        }
7868    }
7869
7870    private static boolean hasString(List<String> list, List<String> which) {
7871        if (list == null) {
7872            return false;
7873        }
7874        for (int i=list.size()-1; i>=0; i--) {
7875            for (int j=which.size()-1; j>=0; j--) {
7876                if (which.get(j).equals(list.get(i))) {
7877                    return true;
7878                }
7879            }
7880        }
7881        return false;
7882    }
7883
7884    private void updateAllSharedLibrariesLPw() {
7885        for (PackageParser.Package pkg : mPackages.values()) {
7886            try {
7887                updateSharedLibrariesLPw(pkg, null);
7888            } catch (PackageManagerException e) {
7889                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7890            }
7891        }
7892    }
7893
7894    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7895            PackageParser.Package changingPkg) {
7896        ArrayList<PackageParser.Package> res = null;
7897        for (PackageParser.Package pkg : mPackages.values()) {
7898            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7899                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7900                if (res == null) {
7901                    res = new ArrayList<PackageParser.Package>();
7902                }
7903                res.add(pkg);
7904                try {
7905                    updateSharedLibrariesLPw(pkg, changingPkg);
7906                } catch (PackageManagerException e) {
7907                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7908                }
7909            }
7910        }
7911        return res;
7912    }
7913
7914    /**
7915     * Derive the value of the {@code cpuAbiOverride} based on the provided
7916     * value and an optional stored value from the package settings.
7917     */
7918    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7919        String cpuAbiOverride = null;
7920
7921        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7922            cpuAbiOverride = null;
7923        } else if (abiOverride != null) {
7924            cpuAbiOverride = abiOverride;
7925        } else if (settings != null) {
7926            cpuAbiOverride = settings.cpuAbiOverrideString;
7927        }
7928
7929        return cpuAbiOverride;
7930    }
7931
7932    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7933            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7934                    throws PackageManagerException {
7935        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7936        // If the package has children and this is the first dive in the function
7937        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7938        // whether all packages (parent and children) would be successfully scanned
7939        // before the actual scan since scanning mutates internal state and we want
7940        // to atomically install the package and its children.
7941        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7942            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7943                scanFlags |= SCAN_CHECK_ONLY;
7944            }
7945        } else {
7946            scanFlags &= ~SCAN_CHECK_ONLY;
7947        }
7948
7949        final PackageParser.Package scannedPkg;
7950        try {
7951            // Scan the parent
7952            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7953            // Scan the children
7954            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7955            for (int i = 0; i < childCount; i++) {
7956                PackageParser.Package childPkg = pkg.childPackages.get(i);
7957                scanPackageLI(childPkg, policyFlags,
7958                        scanFlags, currentTime, user);
7959            }
7960        } finally {
7961            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7962        }
7963
7964        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7965            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7966        }
7967
7968        return scannedPkg;
7969    }
7970
7971    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7972            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7973        boolean success = false;
7974        try {
7975            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7976                    currentTime, user);
7977            success = true;
7978            return res;
7979        } finally {
7980            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7981                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7982                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7983                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7984                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7985            }
7986        }
7987    }
7988
7989    /**
7990     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7991     */
7992    private static boolean apkHasCode(String fileName) {
7993        StrictJarFile jarFile = null;
7994        try {
7995            jarFile = new StrictJarFile(fileName,
7996                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7997            return jarFile.findEntry("classes.dex") != null;
7998        } catch (IOException ignore) {
7999        } finally {
8000            try {
8001                if (jarFile != null) {
8002                    jarFile.close();
8003                }
8004            } catch (IOException ignore) {}
8005        }
8006        return false;
8007    }
8008
8009    /**
8010     * Enforces code policy for the package. This ensures that if an APK has
8011     * declared hasCode="true" in its manifest that the APK actually contains
8012     * code.
8013     *
8014     * @throws PackageManagerException If bytecode could not be found when it should exist
8015     */
8016    private static void enforceCodePolicy(PackageParser.Package pkg)
8017            throws PackageManagerException {
8018        final boolean shouldHaveCode =
8019                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8020        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8021            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8022                    "Package " + pkg.baseCodePath + " code is missing");
8023        }
8024
8025        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8026            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8027                final boolean splitShouldHaveCode =
8028                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8029                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8030                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8031                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8032                }
8033            }
8034        }
8035    }
8036
8037    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8038            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8039            throws PackageManagerException {
8040        final File scanFile = new File(pkg.codePath);
8041        if (pkg.applicationInfo.getCodePath() == null ||
8042                pkg.applicationInfo.getResourcePath() == null) {
8043            // Bail out. The resource and code paths haven't been set.
8044            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8045                    "Code and resource paths haven't been set correctly");
8046        }
8047
8048        // Apply policy
8049        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8050            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8051            if (pkg.applicationInfo.isDirectBootAware()) {
8052                // we're direct boot aware; set for all components
8053                for (PackageParser.Service s : pkg.services) {
8054                    s.info.encryptionAware = s.info.directBootAware = true;
8055                }
8056                for (PackageParser.Provider p : pkg.providers) {
8057                    p.info.encryptionAware = p.info.directBootAware = true;
8058                }
8059                for (PackageParser.Activity a : pkg.activities) {
8060                    a.info.encryptionAware = a.info.directBootAware = true;
8061                }
8062                for (PackageParser.Activity r : pkg.receivers) {
8063                    r.info.encryptionAware = r.info.directBootAware = true;
8064                }
8065            }
8066        } else {
8067            // Only allow system apps to be flagged as core apps.
8068            pkg.coreApp = false;
8069            // clear flags not applicable to regular apps
8070            pkg.applicationInfo.privateFlags &=
8071                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8072            pkg.applicationInfo.privateFlags &=
8073                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8074        }
8075        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8076
8077        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8078            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8079        }
8080
8081        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8082            enforceCodePolicy(pkg);
8083        }
8084
8085        if (mCustomResolverComponentName != null &&
8086                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8087            setUpCustomResolverActivity(pkg);
8088        }
8089
8090        if (pkg.packageName.equals("android")) {
8091            synchronized (mPackages) {
8092                if (mAndroidApplication != null) {
8093                    Slog.w(TAG, "*************************************************");
8094                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8095                    Slog.w(TAG, " file=" + scanFile);
8096                    Slog.w(TAG, "*************************************************");
8097                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8098                            "Core android package being redefined.  Skipping.");
8099                }
8100
8101                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8102                    // Set up information for our fall-back user intent resolution activity.
8103                    mPlatformPackage = pkg;
8104                    pkg.mVersionCode = mSdkVersion;
8105                    mAndroidApplication = pkg.applicationInfo;
8106
8107                    if (!mResolverReplaced) {
8108                        mResolveActivity.applicationInfo = mAndroidApplication;
8109                        mResolveActivity.name = ResolverActivity.class.getName();
8110                        mResolveActivity.packageName = mAndroidApplication.packageName;
8111                        mResolveActivity.processName = "system:ui";
8112                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8113                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8114                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8115                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8116                        mResolveActivity.exported = true;
8117                        mResolveActivity.enabled = true;
8118                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8119                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8120                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8121                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8122                                | ActivityInfo.CONFIG_ORIENTATION
8123                                | ActivityInfo.CONFIG_KEYBOARD
8124                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8125                        mResolveInfo.activityInfo = mResolveActivity;
8126                        mResolveInfo.priority = 0;
8127                        mResolveInfo.preferredOrder = 0;
8128                        mResolveInfo.match = 0;
8129                        mResolveComponentName = new ComponentName(
8130                                mAndroidApplication.packageName, mResolveActivity.name);
8131                    }
8132                }
8133            }
8134        }
8135
8136        if (DEBUG_PACKAGE_SCANNING) {
8137            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8138                Log.d(TAG, "Scanning package " + pkg.packageName);
8139        }
8140
8141        synchronized (mPackages) {
8142            if (mPackages.containsKey(pkg.packageName)
8143                    || mSharedLibraries.containsKey(pkg.packageName)) {
8144                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8145                        "Application package " + pkg.packageName
8146                                + " already installed.  Skipping duplicate.");
8147            }
8148
8149            // If we're only installing presumed-existing packages, require that the
8150            // scanned APK is both already known and at the path previously established
8151            // for it.  Previously unknown packages we pick up normally, but if we have an
8152            // a priori expectation about this package's install presence, enforce it.
8153            // With a singular exception for new system packages. When an OTA contains
8154            // a new system package, we allow the codepath to change from a system location
8155            // to the user-installed location. If we don't allow this change, any newer,
8156            // user-installed version of the application will be ignored.
8157            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8158                if (mExpectingBetter.containsKey(pkg.packageName)) {
8159                    logCriticalInfo(Log.WARN,
8160                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8161                } else {
8162                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8163                    if (known != null) {
8164                        if (DEBUG_PACKAGE_SCANNING) {
8165                            Log.d(TAG, "Examining " + pkg.codePath
8166                                    + " and requiring known paths " + known.codePathString
8167                                    + " & " + known.resourcePathString);
8168                        }
8169                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8170                                || !pkg.applicationInfo.getResourcePath().equals(
8171                                known.resourcePathString)) {
8172                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8173                                    "Application package " + pkg.packageName
8174                                            + " found at " + pkg.applicationInfo.getCodePath()
8175                                            + " but expected at " + known.codePathString
8176                                            + "; ignoring.");
8177                        }
8178                    }
8179                }
8180            }
8181        }
8182
8183        // Initialize package source and resource directories
8184        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8185        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8186
8187        SharedUserSetting suid = null;
8188        PackageSetting pkgSetting = null;
8189
8190        if (!isSystemApp(pkg)) {
8191            // Only system apps can use these features.
8192            pkg.mOriginalPackages = null;
8193            pkg.mRealPackage = null;
8194            pkg.mAdoptPermissions = null;
8195        }
8196
8197        // Getting the package setting may have a side-effect, so if we
8198        // are only checking if scan would succeed, stash a copy of the
8199        // old setting to restore at the end.
8200        PackageSetting nonMutatedPs = null;
8201
8202        // writer
8203        synchronized (mPackages) {
8204            if (pkg.mSharedUserId != null) {
8205                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8206                if (suid == null) {
8207                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8208                            "Creating application package " + pkg.packageName
8209                            + " for shared user failed");
8210                }
8211                if (DEBUG_PACKAGE_SCANNING) {
8212                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8213                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8214                                + "): packages=" + suid.packages);
8215                }
8216            }
8217
8218            // Check if we are renaming from an original package name.
8219            PackageSetting origPackage = null;
8220            String realName = null;
8221            if (pkg.mOriginalPackages != null) {
8222                // This package may need to be renamed to a previously
8223                // installed name.  Let's check on that...
8224                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8225                if (pkg.mOriginalPackages.contains(renamed)) {
8226                    // This package had originally been installed as the
8227                    // original name, and we have already taken care of
8228                    // transitioning to the new one.  Just update the new
8229                    // one to continue using the old name.
8230                    realName = pkg.mRealPackage;
8231                    if (!pkg.packageName.equals(renamed)) {
8232                        // Callers into this function may have already taken
8233                        // care of renaming the package; only do it here if
8234                        // it is not already done.
8235                        pkg.setPackageName(renamed);
8236                    }
8237
8238                } else {
8239                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8240                        if ((origPackage = mSettings.peekPackageLPr(
8241                                pkg.mOriginalPackages.get(i))) != null) {
8242                            // We do have the package already installed under its
8243                            // original name...  should we use it?
8244                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8245                                // New package is not compatible with original.
8246                                origPackage = null;
8247                                continue;
8248                            } else if (origPackage.sharedUser != null) {
8249                                // Make sure uid is compatible between packages.
8250                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8251                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8252                                            + " to " + pkg.packageName + ": old uid "
8253                                            + origPackage.sharedUser.name
8254                                            + " differs from " + pkg.mSharedUserId);
8255                                    origPackage = null;
8256                                    continue;
8257                                }
8258                                // TODO: Add case when shared user id is added [b/28144775]
8259                            } else {
8260                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8261                                        + pkg.packageName + " to old name " + origPackage.name);
8262                            }
8263                            break;
8264                        }
8265                    }
8266                }
8267            }
8268
8269            if (mTransferedPackages.contains(pkg.packageName)) {
8270                Slog.w(TAG, "Package " + pkg.packageName
8271                        + " was transferred to another, but its .apk remains");
8272            }
8273
8274            // See comments in nonMutatedPs declaration
8275            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8276                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8277                if (foundPs != null) {
8278                    nonMutatedPs = new PackageSetting(foundPs);
8279                }
8280            }
8281
8282            // Just create the setting, don't add it yet. For already existing packages
8283            // the PkgSetting exists already and doesn't have to be created.
8284            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8285                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8286                    pkg.applicationInfo.primaryCpuAbi,
8287                    pkg.applicationInfo.secondaryCpuAbi,
8288                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8289                    user, false);
8290            if (pkgSetting == null) {
8291                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8292                        "Creating application package " + pkg.packageName + " failed");
8293            }
8294
8295            if (pkgSetting.origPackage != null) {
8296                // If we are first transitioning from an original package,
8297                // fix up the new package's name now.  We need to do this after
8298                // looking up the package under its new name, so getPackageLP
8299                // can take care of fiddling things correctly.
8300                pkg.setPackageName(origPackage.name);
8301
8302                // File a report about this.
8303                String msg = "New package " + pkgSetting.realName
8304                        + " renamed to replace old package " + pkgSetting.name;
8305                reportSettingsProblem(Log.WARN, msg);
8306
8307                // Make a note of it.
8308                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8309                    mTransferedPackages.add(origPackage.name);
8310                }
8311
8312                // No longer need to retain this.
8313                pkgSetting.origPackage = null;
8314            }
8315
8316            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8317                // Make a note of it.
8318                mTransferedPackages.add(pkg.packageName);
8319            }
8320
8321            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8322                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8323            }
8324
8325            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8326                // Check all shared libraries and map to their actual file path.
8327                // We only do this here for apps not on a system dir, because those
8328                // are the only ones that can fail an install due to this.  We
8329                // will take care of the system apps by updating all of their
8330                // library paths after the scan is done.
8331                updateSharedLibrariesLPw(pkg, null);
8332            }
8333
8334            if (mFoundPolicyFile) {
8335                SELinuxMMAC.assignSeinfoValue(pkg);
8336            }
8337
8338            pkg.applicationInfo.uid = pkgSetting.appId;
8339            pkg.mExtras = pkgSetting;
8340            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8341                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8342                    // We just determined the app is signed correctly, so bring
8343                    // over the latest parsed certs.
8344                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8345                } else {
8346                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8347                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8348                                "Package " + pkg.packageName + " upgrade keys do not match the "
8349                                + "previously installed version");
8350                    } else {
8351                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8352                        String msg = "System package " + pkg.packageName
8353                            + " signature changed; retaining data.";
8354                        reportSettingsProblem(Log.WARN, msg);
8355                    }
8356                }
8357            } else {
8358                try {
8359                    verifySignaturesLP(pkgSetting, pkg);
8360                    // We just determined the app is signed correctly, so bring
8361                    // over the latest parsed certs.
8362                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8363                } catch (PackageManagerException e) {
8364                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8365                        throw e;
8366                    }
8367                    // The signature has changed, but this package is in the system
8368                    // image...  let's recover!
8369                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8370                    // However...  if this package is part of a shared user, but it
8371                    // doesn't match the signature of the shared user, let's fail.
8372                    // What this means is that you can't change the signatures
8373                    // associated with an overall shared user, which doesn't seem all
8374                    // that unreasonable.
8375                    if (pkgSetting.sharedUser != null) {
8376                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8377                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8378                            throw new PackageManagerException(
8379                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8380                                            "Signature mismatch for shared user: "
8381                                            + pkgSetting.sharedUser);
8382                        }
8383                    }
8384                    // File a report about this.
8385                    String msg = "System package " + pkg.packageName
8386                        + " signature changed; retaining data.";
8387                    reportSettingsProblem(Log.WARN, msg);
8388                }
8389            }
8390            // Verify that this new package doesn't have any content providers
8391            // that conflict with existing packages.  Only do this if the
8392            // package isn't already installed, since we don't want to break
8393            // things that are installed.
8394            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8395                final int N = pkg.providers.size();
8396                int i;
8397                for (i=0; i<N; i++) {
8398                    PackageParser.Provider p = pkg.providers.get(i);
8399                    if (p.info.authority != null) {
8400                        String names[] = p.info.authority.split(";");
8401                        for (int j = 0; j < names.length; j++) {
8402                            if (mProvidersByAuthority.containsKey(names[j])) {
8403                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8404                                final String otherPackageName =
8405                                        ((other != null && other.getComponentName() != null) ?
8406                                                other.getComponentName().getPackageName() : "?");
8407                                throw new PackageManagerException(
8408                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8409                                                "Can't install because provider name " + names[j]
8410                                                + " (in package " + pkg.applicationInfo.packageName
8411                                                + ") is already used by " + otherPackageName);
8412                            }
8413                        }
8414                    }
8415                }
8416            }
8417
8418            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8419                // This package wants to adopt ownership of permissions from
8420                // another package.
8421                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8422                    final String origName = pkg.mAdoptPermissions.get(i);
8423                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8424                    if (orig != null) {
8425                        if (verifyPackageUpdateLPr(orig, pkg)) {
8426                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8427                                    + pkg.packageName);
8428                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8429                        }
8430                    }
8431                }
8432            }
8433        }
8434
8435        final String pkgName = pkg.packageName;
8436
8437        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8438        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8439        pkg.applicationInfo.processName = fixProcessName(
8440                pkg.applicationInfo.packageName,
8441                pkg.applicationInfo.processName,
8442                pkg.applicationInfo.uid);
8443
8444        if (pkg != mPlatformPackage) {
8445            // Get all of our default paths setup
8446            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8447        }
8448
8449        final String path = scanFile.getPath();
8450        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8451
8452        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8453            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8454
8455            // Some system apps still use directory structure for native libraries
8456            // in which case we might end up not detecting abi solely based on apk
8457            // structure. Try to detect abi based on directory structure.
8458            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8459                    pkg.applicationInfo.primaryCpuAbi == null) {
8460                setBundledAppAbisAndRoots(pkg, pkgSetting);
8461                setNativeLibraryPaths(pkg);
8462            }
8463
8464        } else {
8465            if ((scanFlags & SCAN_MOVE) != 0) {
8466                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8467                // but we already have this packages package info in the PackageSetting. We just
8468                // use that and derive the native library path based on the new codepath.
8469                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8470                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8471            }
8472
8473            // Set native library paths again. For moves, the path will be updated based on the
8474            // ABIs we've determined above. For non-moves, the path will be updated based on the
8475            // ABIs we determined during compilation, but the path will depend on the final
8476            // package path (after the rename away from the stage path).
8477            setNativeLibraryPaths(pkg);
8478        }
8479
8480        // This is a special case for the "system" package, where the ABI is
8481        // dictated by the zygote configuration (and init.rc). We should keep track
8482        // of this ABI so that we can deal with "normal" applications that run under
8483        // the same UID correctly.
8484        if (mPlatformPackage == pkg) {
8485            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8486                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8487        }
8488
8489        // If there's a mismatch between the abi-override in the package setting
8490        // and the abiOverride specified for the install. Warn about this because we
8491        // would've already compiled the app without taking the package setting into
8492        // account.
8493        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8494            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8495                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8496                        " for package " + pkg.packageName);
8497            }
8498        }
8499
8500        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8501        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8502        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8503
8504        // Copy the derived override back to the parsed package, so that we can
8505        // update the package settings accordingly.
8506        pkg.cpuAbiOverride = cpuAbiOverride;
8507
8508        if (DEBUG_ABI_SELECTION) {
8509            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8510                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8511                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8512        }
8513
8514        // Push the derived path down into PackageSettings so we know what to
8515        // clean up at uninstall time.
8516        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8517
8518        if (DEBUG_ABI_SELECTION) {
8519            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8520                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8521                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8522        }
8523
8524        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8525            // We don't do this here during boot because we can do it all
8526            // at once after scanning all existing packages.
8527            //
8528            // We also do this *before* we perform dexopt on this package, so that
8529            // we can avoid redundant dexopts, and also to make sure we've got the
8530            // code and package path correct.
8531            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8532                    pkg, true /* boot complete */);
8533        }
8534
8535        if (mFactoryTest && pkg.requestedPermissions.contains(
8536                android.Manifest.permission.FACTORY_TEST)) {
8537            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8538        }
8539
8540        if (isSystemApp(pkg)) {
8541            pkgSetting.isOrphaned = true;
8542        }
8543
8544        ArrayList<PackageParser.Package> clientLibPkgs = null;
8545
8546        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8547            if (nonMutatedPs != null) {
8548                synchronized (mPackages) {
8549                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8550                }
8551            }
8552            return pkg;
8553        }
8554
8555        // Only privileged apps and updated privileged apps can add child packages.
8556        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8557            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8558                throw new PackageManagerException("Only privileged apps and updated "
8559                        + "privileged apps can add child packages. Ignoring package "
8560                        + pkg.packageName);
8561            }
8562            final int childCount = pkg.childPackages.size();
8563            for (int i = 0; i < childCount; i++) {
8564                PackageParser.Package childPkg = pkg.childPackages.get(i);
8565                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8566                        childPkg.packageName)) {
8567                    throw new PackageManagerException("Cannot override a child package of "
8568                            + "another disabled system app. Ignoring package " + pkg.packageName);
8569                }
8570            }
8571        }
8572
8573        // writer
8574        synchronized (mPackages) {
8575            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8576                // Only system apps can add new shared libraries.
8577                if (pkg.libraryNames != null) {
8578                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8579                        String name = pkg.libraryNames.get(i);
8580                        boolean allowed = false;
8581                        if (pkg.isUpdatedSystemApp()) {
8582                            // New library entries can only be added through the
8583                            // system image.  This is important to get rid of a lot
8584                            // of nasty edge cases: for example if we allowed a non-
8585                            // system update of the app to add a library, then uninstalling
8586                            // the update would make the library go away, and assumptions
8587                            // we made such as through app install filtering would now
8588                            // have allowed apps on the device which aren't compatible
8589                            // with it.  Better to just have the restriction here, be
8590                            // conservative, and create many fewer cases that can negatively
8591                            // impact the user experience.
8592                            final PackageSetting sysPs = mSettings
8593                                    .getDisabledSystemPkgLPr(pkg.packageName);
8594                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8595                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8596                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8597                                        allowed = true;
8598                                        break;
8599                                    }
8600                                }
8601                            }
8602                        } else {
8603                            allowed = true;
8604                        }
8605                        if (allowed) {
8606                            if (!mSharedLibraries.containsKey(name)) {
8607                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8608                            } else if (!name.equals(pkg.packageName)) {
8609                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8610                                        + name + " already exists; skipping");
8611                            }
8612                        } else {
8613                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8614                                    + name + " that is not declared on system image; skipping");
8615                        }
8616                    }
8617                    if ((scanFlags & SCAN_BOOTING) == 0) {
8618                        // If we are not booting, we need to update any applications
8619                        // that are clients of our shared library.  If we are booting,
8620                        // this will all be done once the scan is complete.
8621                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8622                    }
8623                }
8624            }
8625        }
8626
8627        if ((scanFlags & SCAN_BOOTING) != 0) {
8628            // No apps can run during boot scan, so they don't need to be frozen
8629        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8630            // Caller asked to not kill app, so it's probably not frozen
8631        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8632            // Caller asked us to ignore frozen check for some reason; they
8633            // probably didn't know the package name
8634        } else {
8635            // We're doing major surgery on this package, so it better be frozen
8636            // right now to keep it from launching
8637            checkPackageFrozen(pkgName);
8638        }
8639
8640        // Also need to kill any apps that are dependent on the library.
8641        if (clientLibPkgs != null) {
8642            for (int i=0; i<clientLibPkgs.size(); i++) {
8643                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8644                killApplication(clientPkg.applicationInfo.packageName,
8645                        clientPkg.applicationInfo.uid, "update lib");
8646            }
8647        }
8648
8649        // Make sure we're not adding any bogus keyset info
8650        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8651        ksms.assertScannedPackageValid(pkg);
8652
8653        // writer
8654        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8655
8656        boolean createIdmapFailed = false;
8657        synchronized (mPackages) {
8658            // We don't expect installation to fail beyond this point
8659
8660            if (pkgSetting.pkg != null) {
8661                // Note that |user| might be null during the initial boot scan. If a codePath
8662                // for an app has changed during a boot scan, it's due to an app update that's
8663                // part of the system partition and marker changes must be applied to all users.
8664                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8665                    (user != null) ? user : UserHandle.ALL);
8666            }
8667
8668            // Add the new setting to mSettings
8669            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8670            // Add the new setting to mPackages
8671            mPackages.put(pkg.applicationInfo.packageName, pkg);
8672            // Make sure we don't accidentally delete its data.
8673            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8674            while (iter.hasNext()) {
8675                PackageCleanItem item = iter.next();
8676                if (pkgName.equals(item.packageName)) {
8677                    iter.remove();
8678                }
8679            }
8680
8681            // Take care of first install / last update times.
8682            if (currentTime != 0) {
8683                if (pkgSetting.firstInstallTime == 0) {
8684                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8685                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8686                    pkgSetting.lastUpdateTime = currentTime;
8687                }
8688            } else if (pkgSetting.firstInstallTime == 0) {
8689                // We need *something*.  Take time time stamp of the file.
8690                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8691            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8692                if (scanFileTime != pkgSetting.timeStamp) {
8693                    // A package on the system image has changed; consider this
8694                    // to be an update.
8695                    pkgSetting.lastUpdateTime = scanFileTime;
8696                }
8697            }
8698
8699            // Add the package's KeySets to the global KeySetManagerService
8700            ksms.addScannedPackageLPw(pkg);
8701
8702            int N = pkg.providers.size();
8703            StringBuilder r = null;
8704            int i;
8705            for (i=0; i<N; i++) {
8706                PackageParser.Provider p = pkg.providers.get(i);
8707                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8708                        p.info.processName, pkg.applicationInfo.uid);
8709                mProviders.addProvider(p);
8710                p.syncable = p.info.isSyncable;
8711                if (p.info.authority != null) {
8712                    String names[] = p.info.authority.split(";");
8713                    p.info.authority = null;
8714                    for (int j = 0; j < names.length; j++) {
8715                        if (j == 1 && p.syncable) {
8716                            // We only want the first authority for a provider to possibly be
8717                            // syncable, so if we already added this provider using a different
8718                            // authority clear the syncable flag. We copy the provider before
8719                            // changing it because the mProviders object contains a reference
8720                            // to a provider that we don't want to change.
8721                            // Only do this for the second authority since the resulting provider
8722                            // object can be the same for all future authorities for this provider.
8723                            p = new PackageParser.Provider(p);
8724                            p.syncable = false;
8725                        }
8726                        if (!mProvidersByAuthority.containsKey(names[j])) {
8727                            mProvidersByAuthority.put(names[j], p);
8728                            if (p.info.authority == null) {
8729                                p.info.authority = names[j];
8730                            } else {
8731                                p.info.authority = p.info.authority + ";" + names[j];
8732                            }
8733                            if (DEBUG_PACKAGE_SCANNING) {
8734                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8735                                    Log.d(TAG, "Registered content provider: " + names[j]
8736                                            + ", className = " + p.info.name + ", isSyncable = "
8737                                            + p.info.isSyncable);
8738                            }
8739                        } else {
8740                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8741                            Slog.w(TAG, "Skipping provider name " + names[j] +
8742                                    " (in package " + pkg.applicationInfo.packageName +
8743                                    "): name already used by "
8744                                    + ((other != null && other.getComponentName() != null)
8745                                            ? other.getComponentName().getPackageName() : "?"));
8746                        }
8747                    }
8748                }
8749                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8750                    if (r == null) {
8751                        r = new StringBuilder(256);
8752                    } else {
8753                        r.append(' ');
8754                    }
8755                    r.append(p.info.name);
8756                }
8757            }
8758            if (r != null) {
8759                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8760            }
8761
8762            N = pkg.services.size();
8763            r = null;
8764            for (i=0; i<N; i++) {
8765                PackageParser.Service s = pkg.services.get(i);
8766                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8767                        s.info.processName, pkg.applicationInfo.uid);
8768                mServices.addService(s);
8769                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8770                    if (r == null) {
8771                        r = new StringBuilder(256);
8772                    } else {
8773                        r.append(' ');
8774                    }
8775                    r.append(s.info.name);
8776                }
8777            }
8778            if (r != null) {
8779                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8780            }
8781
8782            N = pkg.receivers.size();
8783            r = null;
8784            for (i=0; i<N; i++) {
8785                PackageParser.Activity a = pkg.receivers.get(i);
8786                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8787                        a.info.processName, pkg.applicationInfo.uid);
8788                mReceivers.addActivity(a, "receiver");
8789                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8790                    if (r == null) {
8791                        r = new StringBuilder(256);
8792                    } else {
8793                        r.append(' ');
8794                    }
8795                    r.append(a.info.name);
8796                }
8797            }
8798            if (r != null) {
8799                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8800            }
8801
8802            N = pkg.activities.size();
8803            r = null;
8804            for (i=0; i<N; i++) {
8805                PackageParser.Activity a = pkg.activities.get(i);
8806                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8807                        a.info.processName, pkg.applicationInfo.uid);
8808                mActivities.addActivity(a, "activity");
8809                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8810                    if (r == null) {
8811                        r = new StringBuilder(256);
8812                    } else {
8813                        r.append(' ');
8814                    }
8815                    r.append(a.info.name);
8816                }
8817            }
8818            if (r != null) {
8819                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8820            }
8821
8822            N = pkg.permissionGroups.size();
8823            r = null;
8824            for (i=0; i<N; i++) {
8825                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8826                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8827                final String curPackageName = cur == null ? null : cur.info.packageName;
8828                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8829                if (cur == null || isPackageUpdate) {
8830                    mPermissionGroups.put(pg.info.name, pg);
8831                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8832                        if (r == null) {
8833                            r = new StringBuilder(256);
8834                        } else {
8835                            r.append(' ');
8836                        }
8837                        if (isPackageUpdate) {
8838                            r.append("UPD:");
8839                        }
8840                        r.append(pg.info.name);
8841                    }
8842                } else {
8843                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8844                            + pg.info.packageName + " ignored: original from "
8845                            + cur.info.packageName);
8846                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8847                        if (r == null) {
8848                            r = new StringBuilder(256);
8849                        } else {
8850                            r.append(' ');
8851                        }
8852                        r.append("DUP:");
8853                        r.append(pg.info.name);
8854                    }
8855                }
8856            }
8857            if (r != null) {
8858                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8859            }
8860
8861            N = pkg.permissions.size();
8862            r = null;
8863            for (i=0; i<N; i++) {
8864                PackageParser.Permission p = pkg.permissions.get(i);
8865
8866                // Assume by default that we did not install this permission into the system.
8867                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8868
8869                // Now that permission groups have a special meaning, we ignore permission
8870                // groups for legacy apps to prevent unexpected behavior. In particular,
8871                // permissions for one app being granted to someone just becase they happen
8872                // to be in a group defined by another app (before this had no implications).
8873                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8874                    p.group = mPermissionGroups.get(p.info.group);
8875                    // Warn for a permission in an unknown group.
8876                    if (p.info.group != null && p.group == null) {
8877                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8878                                + p.info.packageName + " in an unknown group " + p.info.group);
8879                    }
8880                }
8881
8882                ArrayMap<String, BasePermission> permissionMap =
8883                        p.tree ? mSettings.mPermissionTrees
8884                                : mSettings.mPermissions;
8885                BasePermission bp = permissionMap.get(p.info.name);
8886
8887                // Allow system apps to redefine non-system permissions
8888                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8889                    final boolean currentOwnerIsSystem = (bp.perm != null
8890                            && isSystemApp(bp.perm.owner));
8891                    if (isSystemApp(p.owner)) {
8892                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8893                            // It's a built-in permission and no owner, take ownership now
8894                            bp.packageSetting = pkgSetting;
8895                            bp.perm = p;
8896                            bp.uid = pkg.applicationInfo.uid;
8897                            bp.sourcePackage = p.info.packageName;
8898                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8899                        } else if (!currentOwnerIsSystem) {
8900                            String msg = "New decl " + p.owner + " of permission  "
8901                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8902                            reportSettingsProblem(Log.WARN, msg);
8903                            bp = null;
8904                        }
8905                    }
8906                }
8907
8908                if (bp == null) {
8909                    bp = new BasePermission(p.info.name, p.info.packageName,
8910                            BasePermission.TYPE_NORMAL);
8911                    permissionMap.put(p.info.name, bp);
8912                }
8913
8914                if (bp.perm == null) {
8915                    if (bp.sourcePackage == null
8916                            || bp.sourcePackage.equals(p.info.packageName)) {
8917                        BasePermission tree = findPermissionTreeLP(p.info.name);
8918                        if (tree == null
8919                                || tree.sourcePackage.equals(p.info.packageName)) {
8920                            bp.packageSetting = pkgSetting;
8921                            bp.perm = p;
8922                            bp.uid = pkg.applicationInfo.uid;
8923                            bp.sourcePackage = p.info.packageName;
8924                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8925                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8926                                if (r == null) {
8927                                    r = new StringBuilder(256);
8928                                } else {
8929                                    r.append(' ');
8930                                }
8931                                r.append(p.info.name);
8932                            }
8933                        } else {
8934                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8935                                    + p.info.packageName + " ignored: base tree "
8936                                    + tree.name + " is from package "
8937                                    + tree.sourcePackage);
8938                        }
8939                    } else {
8940                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8941                                + p.info.packageName + " ignored: original from "
8942                                + bp.sourcePackage);
8943                    }
8944                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8945                    if (r == null) {
8946                        r = new StringBuilder(256);
8947                    } else {
8948                        r.append(' ');
8949                    }
8950                    r.append("DUP:");
8951                    r.append(p.info.name);
8952                }
8953                if (bp.perm == p) {
8954                    bp.protectionLevel = p.info.protectionLevel;
8955                }
8956            }
8957
8958            if (r != null) {
8959                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8960            }
8961
8962            N = pkg.instrumentation.size();
8963            r = null;
8964            for (i=0; i<N; i++) {
8965                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8966                a.info.packageName = pkg.applicationInfo.packageName;
8967                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8968                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8969                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8970                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8971                a.info.dataDir = pkg.applicationInfo.dataDir;
8972                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8973                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8974
8975                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8976                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8977                mInstrumentation.put(a.getComponentName(), a);
8978                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8979                    if (r == null) {
8980                        r = new StringBuilder(256);
8981                    } else {
8982                        r.append(' ');
8983                    }
8984                    r.append(a.info.name);
8985                }
8986            }
8987            if (r != null) {
8988                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8989            }
8990
8991            if (pkg.protectedBroadcasts != null) {
8992                N = pkg.protectedBroadcasts.size();
8993                for (i=0; i<N; i++) {
8994                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8995                }
8996            }
8997
8998            pkgSetting.setTimeStamp(scanFileTime);
8999
9000            // Create idmap files for pairs of (packages, overlay packages).
9001            // Note: "android", ie framework-res.apk, is handled by native layers.
9002            if (pkg.mOverlayTarget != null) {
9003                // This is an overlay package.
9004                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9005                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9006                        mOverlays.put(pkg.mOverlayTarget,
9007                                new ArrayMap<String, PackageParser.Package>());
9008                    }
9009                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9010                    map.put(pkg.packageName, pkg);
9011                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9012                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9013                        createIdmapFailed = true;
9014                    }
9015                }
9016            } else if (mOverlays.containsKey(pkg.packageName) &&
9017                    !pkg.packageName.equals("android")) {
9018                // This is a regular package, with one or more known overlay packages.
9019                createIdmapsForPackageLI(pkg);
9020            }
9021        }
9022
9023        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9024
9025        if (createIdmapFailed) {
9026            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9027                    "scanPackageLI failed to createIdmap");
9028        }
9029        return pkg;
9030    }
9031
9032    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9033            PackageParser.Package update, UserHandle user) {
9034        if (existing.applicationInfo == null || update.applicationInfo == null) {
9035            // This isn't due to an app installation.
9036            return;
9037        }
9038
9039        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9040        final File newCodePath = new File(update.applicationInfo.getCodePath());
9041
9042        // The codePath hasn't changed, so there's nothing for us to do.
9043        if (Objects.equals(oldCodePath, newCodePath)) {
9044            return;
9045        }
9046
9047        File canonicalNewCodePath;
9048        try {
9049            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9050        } catch (IOException e) {
9051            Slog.w(TAG, "Failed to get canonical path.", e);
9052            return;
9053        }
9054
9055        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9056        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9057        // that the last component of the path (i.e, the name) doesn't need canonicalization
9058        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9059        // but may change in the future. Hopefully this function won't exist at that point.
9060        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9061                oldCodePath.getName());
9062
9063        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9064        // with "@".
9065        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9066        if (!oldMarkerPrefix.endsWith("@")) {
9067            oldMarkerPrefix += "@";
9068        }
9069        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9070        if (!newMarkerPrefix.endsWith("@")) {
9071            newMarkerPrefix += "@";
9072        }
9073
9074        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9075        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9076        for (String updatedPath : updatedPaths) {
9077            String updatedPathName = new File(updatedPath).getName();
9078            markerSuffixes.add(updatedPathName.replace('/', '@'));
9079        }
9080
9081        for (int userId : resolveUserIds(user.getIdentifier())) {
9082            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9083
9084            for (String markerSuffix : markerSuffixes) {
9085                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9086                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9087                if (oldForeignUseMark.exists()) {
9088                    try {
9089                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9090                                newForeignUseMark.getAbsolutePath());
9091                    } catch (ErrnoException e) {
9092                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9093                        oldForeignUseMark.delete();
9094                    }
9095                }
9096            }
9097        }
9098    }
9099
9100    /**
9101     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9102     * is derived purely on the basis of the contents of {@code scanFile} and
9103     * {@code cpuAbiOverride}.
9104     *
9105     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9106     */
9107    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9108                                 String cpuAbiOverride, boolean extractLibs)
9109            throws PackageManagerException {
9110        // TODO: We can probably be smarter about this stuff. For installed apps,
9111        // we can calculate this information at install time once and for all. For
9112        // system apps, we can probably assume that this information doesn't change
9113        // after the first boot scan. As things stand, we do lots of unnecessary work.
9114
9115        // Give ourselves some initial paths; we'll come back for another
9116        // pass once we've determined ABI below.
9117        setNativeLibraryPaths(pkg);
9118
9119        // We would never need to extract libs for forward-locked and external packages,
9120        // since the container service will do it for us. We shouldn't attempt to
9121        // extract libs from system app when it was not updated.
9122        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9123                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9124            extractLibs = false;
9125        }
9126
9127        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9128        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9129
9130        NativeLibraryHelper.Handle handle = null;
9131        try {
9132            handle = NativeLibraryHelper.Handle.create(pkg);
9133            // TODO(multiArch): This can be null for apps that didn't go through the
9134            // usual installation process. We can calculate it again, like we
9135            // do during install time.
9136            //
9137            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9138            // unnecessary.
9139            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9140
9141            // Null out the abis so that they can be recalculated.
9142            pkg.applicationInfo.primaryCpuAbi = null;
9143            pkg.applicationInfo.secondaryCpuAbi = null;
9144            if (isMultiArch(pkg.applicationInfo)) {
9145                // Warn if we've set an abiOverride for multi-lib packages..
9146                // By definition, we need to copy both 32 and 64 bit libraries for
9147                // such packages.
9148                if (pkg.cpuAbiOverride != null
9149                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9150                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9151                }
9152
9153                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9154                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9155                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9156                    if (extractLibs) {
9157                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9158                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9159                                useIsaSpecificSubdirs);
9160                    } else {
9161                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9162                    }
9163                }
9164
9165                maybeThrowExceptionForMultiArchCopy(
9166                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9167
9168                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9169                    if (extractLibs) {
9170                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9171                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9172                                useIsaSpecificSubdirs);
9173                    } else {
9174                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9175                    }
9176                }
9177
9178                maybeThrowExceptionForMultiArchCopy(
9179                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9180
9181                if (abi64 >= 0) {
9182                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9183                }
9184
9185                if (abi32 >= 0) {
9186                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9187                    if (abi64 >= 0) {
9188                        if (pkg.use32bitAbi) {
9189                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9190                            pkg.applicationInfo.primaryCpuAbi = abi;
9191                        } else {
9192                            pkg.applicationInfo.secondaryCpuAbi = abi;
9193                        }
9194                    } else {
9195                        pkg.applicationInfo.primaryCpuAbi = abi;
9196                    }
9197                }
9198
9199            } else {
9200                String[] abiList = (cpuAbiOverride != null) ?
9201                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9202
9203                // Enable gross and lame hacks for apps that are built with old
9204                // SDK tools. We must scan their APKs for renderscript bitcode and
9205                // not launch them if it's present. Don't bother checking on devices
9206                // that don't have 64 bit support.
9207                boolean needsRenderScriptOverride = false;
9208                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9209                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9210                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9211                    needsRenderScriptOverride = true;
9212                }
9213
9214                final int copyRet;
9215                if (extractLibs) {
9216                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9217                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9218                } else {
9219                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9220                }
9221
9222                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9223                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9224                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9225                }
9226
9227                if (copyRet >= 0) {
9228                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9229                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9230                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9231                } else if (needsRenderScriptOverride) {
9232                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9233                }
9234            }
9235        } catch (IOException ioe) {
9236            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9237        } finally {
9238            IoUtils.closeQuietly(handle);
9239        }
9240
9241        // Now that we've calculated the ABIs and determined if it's an internal app,
9242        // we will go ahead and populate the nativeLibraryPath.
9243        setNativeLibraryPaths(pkg);
9244    }
9245
9246    /**
9247     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9248     * i.e, so that all packages can be run inside a single process if required.
9249     *
9250     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9251     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9252     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9253     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9254     * updating a package that belongs to a shared user.
9255     *
9256     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9257     * adds unnecessary complexity.
9258     */
9259    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9260            PackageParser.Package scannedPackage, boolean bootComplete) {
9261        String requiredInstructionSet = null;
9262        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9263            requiredInstructionSet = VMRuntime.getInstructionSet(
9264                     scannedPackage.applicationInfo.primaryCpuAbi);
9265        }
9266
9267        PackageSetting requirer = null;
9268        for (PackageSetting ps : packagesForUser) {
9269            // If packagesForUser contains scannedPackage, we skip it. This will happen
9270            // when scannedPackage is an update of an existing package. Without this check,
9271            // we will never be able to change the ABI of any package belonging to a shared
9272            // user, even if it's compatible with other packages.
9273            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9274                if (ps.primaryCpuAbiString == null) {
9275                    continue;
9276                }
9277
9278                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9279                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9280                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9281                    // this but there's not much we can do.
9282                    String errorMessage = "Instruction set mismatch, "
9283                            + ((requirer == null) ? "[caller]" : requirer)
9284                            + " requires " + requiredInstructionSet + " whereas " + ps
9285                            + " requires " + instructionSet;
9286                    Slog.w(TAG, errorMessage);
9287                }
9288
9289                if (requiredInstructionSet == null) {
9290                    requiredInstructionSet = instructionSet;
9291                    requirer = ps;
9292                }
9293            }
9294        }
9295
9296        if (requiredInstructionSet != null) {
9297            String adjustedAbi;
9298            if (requirer != null) {
9299                // requirer != null implies that either scannedPackage was null or that scannedPackage
9300                // did not require an ABI, in which case we have to adjust scannedPackage to match
9301                // the ABI of the set (which is the same as requirer's ABI)
9302                adjustedAbi = requirer.primaryCpuAbiString;
9303                if (scannedPackage != null) {
9304                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9305                }
9306            } else {
9307                // requirer == null implies that we're updating all ABIs in the set to
9308                // match scannedPackage.
9309                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9310            }
9311
9312            for (PackageSetting ps : packagesForUser) {
9313                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9314                    if (ps.primaryCpuAbiString != null) {
9315                        continue;
9316                    }
9317
9318                    ps.primaryCpuAbiString = adjustedAbi;
9319                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9320                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9321                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9322                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9323                                + " (requirer="
9324                                + (requirer == null ? "null" : requirer.pkg.packageName)
9325                                + ", scannedPackage="
9326                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9327                                + ")");
9328                        try {
9329                            mInstaller.rmdex(ps.codePathString,
9330                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9331                        } catch (InstallerException ignored) {
9332                        }
9333                    }
9334                }
9335            }
9336        }
9337    }
9338
9339    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9340        synchronized (mPackages) {
9341            mResolverReplaced = true;
9342            // Set up information for custom user intent resolution activity.
9343            mResolveActivity.applicationInfo = pkg.applicationInfo;
9344            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9345            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9346            mResolveActivity.processName = pkg.applicationInfo.packageName;
9347            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9348            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9349                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9350            mResolveActivity.theme = 0;
9351            mResolveActivity.exported = true;
9352            mResolveActivity.enabled = true;
9353            mResolveInfo.activityInfo = mResolveActivity;
9354            mResolveInfo.priority = 0;
9355            mResolveInfo.preferredOrder = 0;
9356            mResolveInfo.match = 0;
9357            mResolveComponentName = mCustomResolverComponentName;
9358            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9359                    mResolveComponentName);
9360        }
9361    }
9362
9363    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9364        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9365
9366        // Set up information for ephemeral installer activity
9367        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9368        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9369        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9370        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9371        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9372        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9373                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9374        mEphemeralInstallerActivity.theme = 0;
9375        mEphemeralInstallerActivity.exported = true;
9376        mEphemeralInstallerActivity.enabled = true;
9377        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9378        mEphemeralInstallerInfo.priority = 0;
9379        mEphemeralInstallerInfo.preferredOrder = 1;
9380        mEphemeralInstallerInfo.isDefault = true;
9381        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9382                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9383
9384        if (DEBUG_EPHEMERAL) {
9385            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9386        }
9387    }
9388
9389    private static String calculateBundledApkRoot(final String codePathString) {
9390        final File codePath = new File(codePathString);
9391        final File codeRoot;
9392        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9393            codeRoot = Environment.getRootDirectory();
9394        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9395            codeRoot = Environment.getOemDirectory();
9396        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9397            codeRoot = Environment.getVendorDirectory();
9398        } else {
9399            // Unrecognized code path; take its top real segment as the apk root:
9400            // e.g. /something/app/blah.apk => /something
9401            try {
9402                File f = codePath.getCanonicalFile();
9403                File parent = f.getParentFile();    // non-null because codePath is a file
9404                File tmp;
9405                while ((tmp = parent.getParentFile()) != null) {
9406                    f = parent;
9407                    parent = tmp;
9408                }
9409                codeRoot = f;
9410                Slog.w(TAG, "Unrecognized code path "
9411                        + codePath + " - using " + codeRoot);
9412            } catch (IOException e) {
9413                // Can't canonicalize the code path -- shenanigans?
9414                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9415                return Environment.getRootDirectory().getPath();
9416            }
9417        }
9418        return codeRoot.getPath();
9419    }
9420
9421    /**
9422     * Derive and set the location of native libraries for the given package,
9423     * which varies depending on where and how the package was installed.
9424     */
9425    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9426        final ApplicationInfo info = pkg.applicationInfo;
9427        final String codePath = pkg.codePath;
9428        final File codeFile = new File(codePath);
9429        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9430        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9431
9432        info.nativeLibraryRootDir = null;
9433        info.nativeLibraryRootRequiresIsa = false;
9434        info.nativeLibraryDir = null;
9435        info.secondaryNativeLibraryDir = null;
9436
9437        if (isApkFile(codeFile)) {
9438            // Monolithic install
9439            if (bundledApp) {
9440                // If "/system/lib64/apkname" exists, assume that is the per-package
9441                // native library directory to use; otherwise use "/system/lib/apkname".
9442                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9443                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9444                        getPrimaryInstructionSet(info));
9445
9446                // This is a bundled system app so choose the path based on the ABI.
9447                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9448                // is just the default path.
9449                final String apkName = deriveCodePathName(codePath);
9450                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9451                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9452                        apkName).getAbsolutePath();
9453
9454                if (info.secondaryCpuAbi != null) {
9455                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9456                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9457                            secondaryLibDir, apkName).getAbsolutePath();
9458                }
9459            } else if (asecApp) {
9460                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9461                        .getAbsolutePath();
9462            } else {
9463                final String apkName = deriveCodePathName(codePath);
9464                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9465                        .getAbsolutePath();
9466            }
9467
9468            info.nativeLibraryRootRequiresIsa = false;
9469            info.nativeLibraryDir = info.nativeLibraryRootDir;
9470        } else {
9471            // Cluster install
9472            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9473            info.nativeLibraryRootRequiresIsa = true;
9474
9475            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9476                    getPrimaryInstructionSet(info)).getAbsolutePath();
9477
9478            if (info.secondaryCpuAbi != null) {
9479                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9480                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9481            }
9482        }
9483    }
9484
9485    /**
9486     * Calculate the abis and roots for a bundled app. These can uniquely
9487     * be determined from the contents of the system partition, i.e whether
9488     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9489     * of this information, and instead assume that the system was built
9490     * sensibly.
9491     */
9492    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9493                                           PackageSetting pkgSetting) {
9494        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9495
9496        // If "/system/lib64/apkname" exists, assume that is the per-package
9497        // native library directory to use; otherwise use "/system/lib/apkname".
9498        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9499        setBundledAppAbi(pkg, apkRoot, apkName);
9500        // pkgSetting might be null during rescan following uninstall of updates
9501        // to a bundled app, so accommodate that possibility.  The settings in
9502        // that case will be established later from the parsed package.
9503        //
9504        // If the settings aren't null, sync them up with what we've just derived.
9505        // note that apkRoot isn't stored in the package settings.
9506        if (pkgSetting != null) {
9507            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9508            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9509        }
9510    }
9511
9512    /**
9513     * Deduces the ABI of a bundled app and sets the relevant fields on the
9514     * parsed pkg object.
9515     *
9516     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9517     *        under which system libraries are installed.
9518     * @param apkName the name of the installed package.
9519     */
9520    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9521        final File codeFile = new File(pkg.codePath);
9522
9523        final boolean has64BitLibs;
9524        final boolean has32BitLibs;
9525        if (isApkFile(codeFile)) {
9526            // Monolithic install
9527            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9528            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9529        } else {
9530            // Cluster install
9531            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9532            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9533                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9534                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9535                has64BitLibs = (new File(rootDir, isa)).exists();
9536            } else {
9537                has64BitLibs = false;
9538            }
9539            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9540                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9541                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9542                has32BitLibs = (new File(rootDir, isa)).exists();
9543            } else {
9544                has32BitLibs = false;
9545            }
9546        }
9547
9548        if (has64BitLibs && !has32BitLibs) {
9549            // The package has 64 bit libs, but not 32 bit libs. Its primary
9550            // ABI should be 64 bit. We can safely assume here that the bundled
9551            // native libraries correspond to the most preferred ABI in the list.
9552
9553            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9554            pkg.applicationInfo.secondaryCpuAbi = null;
9555        } else if (has32BitLibs && !has64BitLibs) {
9556            // The package has 32 bit libs but not 64 bit libs. Its primary
9557            // ABI should be 32 bit.
9558
9559            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9560            pkg.applicationInfo.secondaryCpuAbi = null;
9561        } else if (has32BitLibs && has64BitLibs) {
9562            // The application has both 64 and 32 bit bundled libraries. We check
9563            // here that the app declares multiArch support, and warn if it doesn't.
9564            //
9565            // We will be lenient here and record both ABIs. The primary will be the
9566            // ABI that's higher on the list, i.e, a device that's configured to prefer
9567            // 64 bit apps will see a 64 bit primary ABI,
9568
9569            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9570                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9571            }
9572
9573            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9574                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9575                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9576            } else {
9577                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9578                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9579            }
9580        } else {
9581            pkg.applicationInfo.primaryCpuAbi = null;
9582            pkg.applicationInfo.secondaryCpuAbi = null;
9583        }
9584    }
9585
9586    private void killApplication(String pkgName, int appId, String reason) {
9587        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9588    }
9589
9590    private void killApplication(String pkgName, int appId, int userId, String reason) {
9591        // Request the ActivityManager to kill the process(only for existing packages)
9592        // so that we do not end up in a confused state while the user is still using the older
9593        // version of the application while the new one gets installed.
9594        final long token = Binder.clearCallingIdentity();
9595        try {
9596            IActivityManager am = ActivityManagerNative.getDefault();
9597            if (am != null) {
9598                try {
9599                    am.killApplication(pkgName, appId, userId, reason);
9600                } catch (RemoteException e) {
9601                }
9602            }
9603        } finally {
9604            Binder.restoreCallingIdentity(token);
9605        }
9606    }
9607
9608    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9609        // Remove the parent package setting
9610        PackageSetting ps = (PackageSetting) pkg.mExtras;
9611        if (ps != null) {
9612            removePackageLI(ps, chatty);
9613        }
9614        // Remove the child package setting
9615        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9616        for (int i = 0; i < childCount; i++) {
9617            PackageParser.Package childPkg = pkg.childPackages.get(i);
9618            ps = (PackageSetting) childPkg.mExtras;
9619            if (ps != null) {
9620                removePackageLI(ps, chatty);
9621            }
9622        }
9623    }
9624
9625    void removePackageLI(PackageSetting ps, boolean chatty) {
9626        if (DEBUG_INSTALL) {
9627            if (chatty)
9628                Log.d(TAG, "Removing package " + ps.name);
9629        }
9630
9631        // writer
9632        synchronized (mPackages) {
9633            mPackages.remove(ps.name);
9634            final PackageParser.Package pkg = ps.pkg;
9635            if (pkg != null) {
9636                cleanPackageDataStructuresLILPw(pkg, chatty);
9637            }
9638        }
9639    }
9640
9641    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9642        if (DEBUG_INSTALL) {
9643            if (chatty)
9644                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9645        }
9646
9647        // writer
9648        synchronized (mPackages) {
9649            // Remove the parent package
9650            mPackages.remove(pkg.applicationInfo.packageName);
9651            cleanPackageDataStructuresLILPw(pkg, chatty);
9652
9653            // Remove the child packages
9654            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9655            for (int i = 0; i < childCount; i++) {
9656                PackageParser.Package childPkg = pkg.childPackages.get(i);
9657                mPackages.remove(childPkg.applicationInfo.packageName);
9658                cleanPackageDataStructuresLILPw(childPkg, chatty);
9659            }
9660        }
9661    }
9662
9663    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9664        int N = pkg.providers.size();
9665        StringBuilder r = null;
9666        int i;
9667        for (i=0; i<N; i++) {
9668            PackageParser.Provider p = pkg.providers.get(i);
9669            mProviders.removeProvider(p);
9670            if (p.info.authority == null) {
9671
9672                /* There was another ContentProvider with this authority when
9673                 * this app was installed so this authority is null,
9674                 * Ignore it as we don't have to unregister the provider.
9675                 */
9676                continue;
9677            }
9678            String names[] = p.info.authority.split(";");
9679            for (int j = 0; j < names.length; j++) {
9680                if (mProvidersByAuthority.get(names[j]) == p) {
9681                    mProvidersByAuthority.remove(names[j]);
9682                    if (DEBUG_REMOVE) {
9683                        if (chatty)
9684                            Log.d(TAG, "Unregistered content provider: " + names[j]
9685                                    + ", className = " + p.info.name + ", isSyncable = "
9686                                    + p.info.isSyncable);
9687                    }
9688                }
9689            }
9690            if (DEBUG_REMOVE && chatty) {
9691                if (r == null) {
9692                    r = new StringBuilder(256);
9693                } else {
9694                    r.append(' ');
9695                }
9696                r.append(p.info.name);
9697            }
9698        }
9699        if (r != null) {
9700            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9701        }
9702
9703        N = pkg.services.size();
9704        r = null;
9705        for (i=0; i<N; i++) {
9706            PackageParser.Service s = pkg.services.get(i);
9707            mServices.removeService(s);
9708            if (chatty) {
9709                if (r == null) {
9710                    r = new StringBuilder(256);
9711                } else {
9712                    r.append(' ');
9713                }
9714                r.append(s.info.name);
9715            }
9716        }
9717        if (r != null) {
9718            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9719        }
9720
9721        N = pkg.receivers.size();
9722        r = null;
9723        for (i=0; i<N; i++) {
9724            PackageParser.Activity a = pkg.receivers.get(i);
9725            mReceivers.removeActivity(a, "receiver");
9726            if (DEBUG_REMOVE && chatty) {
9727                if (r == null) {
9728                    r = new StringBuilder(256);
9729                } else {
9730                    r.append(' ');
9731                }
9732                r.append(a.info.name);
9733            }
9734        }
9735        if (r != null) {
9736            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9737        }
9738
9739        N = pkg.activities.size();
9740        r = null;
9741        for (i=0; i<N; i++) {
9742            PackageParser.Activity a = pkg.activities.get(i);
9743            mActivities.removeActivity(a, "activity");
9744            if (DEBUG_REMOVE && chatty) {
9745                if (r == null) {
9746                    r = new StringBuilder(256);
9747                } else {
9748                    r.append(' ');
9749                }
9750                r.append(a.info.name);
9751            }
9752        }
9753        if (r != null) {
9754            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9755        }
9756
9757        N = pkg.permissions.size();
9758        r = null;
9759        for (i=0; i<N; i++) {
9760            PackageParser.Permission p = pkg.permissions.get(i);
9761            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9762            if (bp == null) {
9763                bp = mSettings.mPermissionTrees.get(p.info.name);
9764            }
9765            if (bp != null && bp.perm == p) {
9766                bp.perm = null;
9767                if (DEBUG_REMOVE && chatty) {
9768                    if (r == null) {
9769                        r = new StringBuilder(256);
9770                    } else {
9771                        r.append(' ');
9772                    }
9773                    r.append(p.info.name);
9774                }
9775            }
9776            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9777                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9778                if (appOpPkgs != null) {
9779                    appOpPkgs.remove(pkg.packageName);
9780                }
9781            }
9782        }
9783        if (r != null) {
9784            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9785        }
9786
9787        N = pkg.requestedPermissions.size();
9788        r = null;
9789        for (i=0; i<N; i++) {
9790            String perm = pkg.requestedPermissions.get(i);
9791            BasePermission bp = mSettings.mPermissions.get(perm);
9792            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9793                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9794                if (appOpPkgs != null) {
9795                    appOpPkgs.remove(pkg.packageName);
9796                    if (appOpPkgs.isEmpty()) {
9797                        mAppOpPermissionPackages.remove(perm);
9798                    }
9799                }
9800            }
9801        }
9802        if (r != null) {
9803            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9804        }
9805
9806        N = pkg.instrumentation.size();
9807        r = null;
9808        for (i=0; i<N; i++) {
9809            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9810            mInstrumentation.remove(a.getComponentName());
9811            if (DEBUG_REMOVE && chatty) {
9812                if (r == null) {
9813                    r = new StringBuilder(256);
9814                } else {
9815                    r.append(' ');
9816                }
9817                r.append(a.info.name);
9818            }
9819        }
9820        if (r != null) {
9821            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9822        }
9823
9824        r = null;
9825        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9826            // Only system apps can hold shared libraries.
9827            if (pkg.libraryNames != null) {
9828                for (i=0; i<pkg.libraryNames.size(); i++) {
9829                    String name = pkg.libraryNames.get(i);
9830                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9831                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9832                        mSharedLibraries.remove(name);
9833                        if (DEBUG_REMOVE && chatty) {
9834                            if (r == null) {
9835                                r = new StringBuilder(256);
9836                            } else {
9837                                r.append(' ');
9838                            }
9839                            r.append(name);
9840                        }
9841                    }
9842                }
9843            }
9844        }
9845        if (r != null) {
9846            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9847        }
9848    }
9849
9850    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9851        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9852            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9853                return true;
9854            }
9855        }
9856        return false;
9857    }
9858
9859    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9860    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9861    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9862
9863    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9864        // Update the parent permissions
9865        updatePermissionsLPw(pkg.packageName, pkg, flags);
9866        // Update the child permissions
9867        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9868        for (int i = 0; i < childCount; i++) {
9869            PackageParser.Package childPkg = pkg.childPackages.get(i);
9870            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9871        }
9872    }
9873
9874    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9875            int flags) {
9876        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9877        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9878    }
9879
9880    private void updatePermissionsLPw(String changingPkg,
9881            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9882        // Make sure there are no dangling permission trees.
9883        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9884        while (it.hasNext()) {
9885            final BasePermission bp = it.next();
9886            if (bp.packageSetting == null) {
9887                // We may not yet have parsed the package, so just see if
9888                // we still know about its settings.
9889                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9890            }
9891            if (bp.packageSetting == null) {
9892                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9893                        + " from package " + bp.sourcePackage);
9894                it.remove();
9895            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9896                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9897                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9898                            + " from package " + bp.sourcePackage);
9899                    flags |= UPDATE_PERMISSIONS_ALL;
9900                    it.remove();
9901                }
9902            }
9903        }
9904
9905        // Make sure all dynamic permissions have been assigned to a package,
9906        // and make sure there are no dangling permissions.
9907        it = mSettings.mPermissions.values().iterator();
9908        while (it.hasNext()) {
9909            final BasePermission bp = it.next();
9910            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9911                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9912                        + bp.name + " pkg=" + bp.sourcePackage
9913                        + " info=" + bp.pendingInfo);
9914                if (bp.packageSetting == null && bp.pendingInfo != null) {
9915                    final BasePermission tree = findPermissionTreeLP(bp.name);
9916                    if (tree != null && tree.perm != null) {
9917                        bp.packageSetting = tree.packageSetting;
9918                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9919                                new PermissionInfo(bp.pendingInfo));
9920                        bp.perm.info.packageName = tree.perm.info.packageName;
9921                        bp.perm.info.name = bp.name;
9922                        bp.uid = tree.uid;
9923                    }
9924                }
9925            }
9926            if (bp.packageSetting == null) {
9927                // We may not yet have parsed the package, so just see if
9928                // we still know about its settings.
9929                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9930            }
9931            if (bp.packageSetting == null) {
9932                Slog.w(TAG, "Removing dangling permission: " + bp.name
9933                        + " from package " + bp.sourcePackage);
9934                it.remove();
9935            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9936                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9937                    Slog.i(TAG, "Removing old permission: " + bp.name
9938                            + " from package " + bp.sourcePackage);
9939                    flags |= UPDATE_PERMISSIONS_ALL;
9940                    it.remove();
9941                }
9942            }
9943        }
9944
9945        // Now update the permissions for all packages, in particular
9946        // replace the granted permissions of the system packages.
9947        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9948            for (PackageParser.Package pkg : mPackages.values()) {
9949                if (pkg != pkgInfo) {
9950                    // Only replace for packages on requested volume
9951                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9952                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9953                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9954                    grantPermissionsLPw(pkg, replace, changingPkg);
9955                }
9956            }
9957        }
9958
9959        if (pkgInfo != null) {
9960            // Only replace for packages on requested volume
9961            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9962            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9963                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9964            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9965        }
9966    }
9967
9968    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9969            String packageOfInterest) {
9970        // IMPORTANT: There are two types of permissions: install and runtime.
9971        // Install time permissions are granted when the app is installed to
9972        // all device users and users added in the future. Runtime permissions
9973        // are granted at runtime explicitly to specific users. Normal and signature
9974        // protected permissions are install time permissions. Dangerous permissions
9975        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9976        // otherwise they are runtime permissions. This function does not manage
9977        // runtime permissions except for the case an app targeting Lollipop MR1
9978        // being upgraded to target a newer SDK, in which case dangerous permissions
9979        // are transformed from install time to runtime ones.
9980
9981        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9982        if (ps == null) {
9983            return;
9984        }
9985
9986        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9987
9988        PermissionsState permissionsState = ps.getPermissionsState();
9989        PermissionsState origPermissions = permissionsState;
9990
9991        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9992
9993        boolean runtimePermissionsRevoked = false;
9994        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9995
9996        boolean changedInstallPermission = false;
9997
9998        if (replace) {
9999            ps.installPermissionsFixed = false;
10000            if (!ps.isSharedUser()) {
10001                origPermissions = new PermissionsState(permissionsState);
10002                permissionsState.reset();
10003            } else {
10004                // We need to know only about runtime permission changes since the
10005                // calling code always writes the install permissions state but
10006                // the runtime ones are written only if changed. The only cases of
10007                // changed runtime permissions here are promotion of an install to
10008                // runtime and revocation of a runtime from a shared user.
10009                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
10010                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
10011                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10012                    runtimePermissionsRevoked = true;
10013                }
10014            }
10015        }
10016
10017        permissionsState.setGlobalGids(mGlobalGids);
10018
10019        final int N = pkg.requestedPermissions.size();
10020        for (int i=0; i<N; i++) {
10021            final String name = pkg.requestedPermissions.get(i);
10022            final BasePermission bp = mSettings.mPermissions.get(name);
10023
10024            if (DEBUG_INSTALL) {
10025                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10026            }
10027
10028            if (bp == null || bp.packageSetting == null) {
10029                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10030                    Slog.w(TAG, "Unknown permission " + name
10031                            + " in package " + pkg.packageName);
10032                }
10033                continue;
10034            }
10035
10036            final String perm = bp.name;
10037            boolean allowedSig = false;
10038            int grant = GRANT_DENIED;
10039
10040            // Keep track of app op permissions.
10041            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10042                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10043                if (pkgs == null) {
10044                    pkgs = new ArraySet<>();
10045                    mAppOpPermissionPackages.put(bp.name, pkgs);
10046                }
10047                pkgs.add(pkg.packageName);
10048            }
10049
10050            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10051            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10052                    >= Build.VERSION_CODES.M;
10053            switch (level) {
10054                case PermissionInfo.PROTECTION_NORMAL: {
10055                    // For all apps normal permissions are install time ones.
10056                    grant = GRANT_INSTALL;
10057                } break;
10058
10059                case PermissionInfo.PROTECTION_DANGEROUS: {
10060                    // If a permission review is required for legacy apps we represent
10061                    // their permissions as always granted runtime ones since we need
10062                    // to keep the review required permission flag per user while an
10063                    // install permission's state is shared across all users.
10064                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired
10065                            && !Build.PERMISSIONS_REVIEW_REQUIRED) {
10066                        // For legacy apps dangerous permissions are install time ones.
10067                        grant = GRANT_INSTALL;
10068                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10069                        // For legacy apps that became modern, install becomes runtime.
10070                        grant = GRANT_UPGRADE;
10071                    } else if (mPromoteSystemApps
10072                            && isSystemApp(ps)
10073                            && mExistingSystemPackages.contains(ps.name)) {
10074                        // For legacy system apps, install becomes runtime.
10075                        // We cannot check hasInstallPermission() for system apps since those
10076                        // permissions were granted implicitly and not persisted pre-M.
10077                        grant = GRANT_UPGRADE;
10078                    } else {
10079                        // For modern apps keep runtime permissions unchanged.
10080                        grant = GRANT_RUNTIME;
10081                    }
10082                } break;
10083
10084                case PermissionInfo.PROTECTION_SIGNATURE: {
10085                    // For all apps signature permissions are install time ones.
10086                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10087                    if (allowedSig) {
10088                        grant = GRANT_INSTALL;
10089                    }
10090                } break;
10091            }
10092
10093            if (DEBUG_INSTALL) {
10094                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10095            }
10096
10097            if (grant != GRANT_DENIED) {
10098                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10099                    // If this is an existing, non-system package, then
10100                    // we can't add any new permissions to it.
10101                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10102                        // Except...  if this is a permission that was added
10103                        // to the platform (note: need to only do this when
10104                        // updating the platform).
10105                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10106                            grant = GRANT_DENIED;
10107                        }
10108                    }
10109                }
10110
10111                switch (grant) {
10112                    case GRANT_INSTALL: {
10113                        // Revoke this as runtime permission to handle the case of
10114                        // a runtime permission being downgraded to an install one.
10115                        // Also in permission review mode we keep dangerous permissions
10116                        // for legacy apps
10117                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10118                            if (origPermissions.getRuntimePermissionState(
10119                                    bp.name, userId) != null) {
10120                                // Revoke the runtime permission and clear the flags.
10121                                origPermissions.revokeRuntimePermission(bp, userId);
10122                                origPermissions.updatePermissionFlags(bp, userId,
10123                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10124                                // If we revoked a permission permission, we have to write.
10125                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10126                                        changedRuntimePermissionUserIds, userId);
10127                            }
10128                        }
10129                        // Grant an install permission.
10130                        if (permissionsState.grantInstallPermission(bp) !=
10131                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10132                            changedInstallPermission = true;
10133                        }
10134                    } break;
10135
10136                    case GRANT_RUNTIME: {
10137                        // Grant previously granted runtime permissions.
10138                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10139                            PermissionState permissionState = origPermissions
10140                                    .getRuntimePermissionState(bp.name, userId);
10141                            int flags = permissionState != null
10142                                    ? permissionState.getFlags() : 0;
10143                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10144                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10145                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10146                                    // If we cannot put the permission as it was, we have to write.
10147                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10148                                            changedRuntimePermissionUserIds, userId);
10149                                }
10150                                // If the app supports runtime permissions no need for a review.
10151                                if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
10152                                        && appSupportsRuntimePermissions
10153                                        && (flags & PackageManager
10154                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10155                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10156                                    // Since we changed the flags, we have to write.
10157                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10158                                            changedRuntimePermissionUserIds, userId);
10159                                }
10160                            } else if ((mPermissionReviewRequired
10161                                        || Build.PERMISSIONS_REVIEW_REQUIRED)
10162                                    && !appSupportsRuntimePermissions) {
10163                                // For legacy apps that need a permission review, every new
10164                                // runtime permission is granted but it is pending a review.
10165                                // We also need to review only platform defined runtime
10166                                // permissions as these are the only ones the platform knows
10167                                // how to disable the API to simulate revocation as legacy
10168                                // apps don't expect to run with revoked permissions.
10169                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10170                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10171                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10172                                        // We changed the flags, hence have to write.
10173                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10174                                                changedRuntimePermissionUserIds, userId);
10175                                    }
10176                                }
10177                                if (permissionsState.grantRuntimePermission(bp, userId)
10178                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10179                                    // We changed the permission, hence have to write.
10180                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10181                                            changedRuntimePermissionUserIds, userId);
10182                                }
10183                            }
10184                            // Propagate the permission flags.
10185                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10186                        }
10187                    } break;
10188
10189                    case GRANT_UPGRADE: {
10190                        // Grant runtime permissions for a previously held install permission.
10191                        PermissionState permissionState = origPermissions
10192                                .getInstallPermissionState(bp.name);
10193                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10194
10195                        if (origPermissions.revokeInstallPermission(bp)
10196                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10197                            // We will be transferring the permission flags, so clear them.
10198                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10199                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10200                            changedInstallPermission = true;
10201                        }
10202
10203                        // If the permission is not to be promoted to runtime we ignore it and
10204                        // also its other flags as they are not applicable to install permissions.
10205                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10206                            for (int userId : currentUserIds) {
10207                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10208                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10209                                    // Transfer the permission flags.
10210                                    permissionsState.updatePermissionFlags(bp, userId,
10211                                            flags, flags);
10212                                    // If we granted the permission, we have to write.
10213                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10214                                            changedRuntimePermissionUserIds, userId);
10215                                }
10216                            }
10217                        }
10218                    } break;
10219
10220                    default: {
10221                        if (packageOfInterest == null
10222                                || packageOfInterest.equals(pkg.packageName)) {
10223                            Slog.w(TAG, "Not granting permission " + perm
10224                                    + " to package " + pkg.packageName
10225                                    + " because it was previously installed without");
10226                        }
10227                    } break;
10228                }
10229            } else {
10230                if (permissionsState.revokeInstallPermission(bp) !=
10231                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10232                    // Also drop the permission flags.
10233                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10234                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10235                    changedInstallPermission = true;
10236                    Slog.i(TAG, "Un-granting permission " + perm
10237                            + " from package " + pkg.packageName
10238                            + " (protectionLevel=" + bp.protectionLevel
10239                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10240                            + ")");
10241                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10242                    // Don't print warning for app op permissions, since it is fine for them
10243                    // not to be granted, there is a UI for the user to decide.
10244                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10245                        Slog.w(TAG, "Not granting permission " + perm
10246                                + " to package " + pkg.packageName
10247                                + " (protectionLevel=" + bp.protectionLevel
10248                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10249                                + ")");
10250                    }
10251                }
10252            }
10253        }
10254
10255        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10256                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10257            // This is the first that we have heard about this package, so the
10258            // permissions we have now selected are fixed until explicitly
10259            // changed.
10260            ps.installPermissionsFixed = true;
10261        }
10262
10263        // Persist the runtime permissions state for users with changes. If permissions
10264        // were revoked because no app in the shared user declares them we have to
10265        // write synchronously to avoid losing runtime permissions state.
10266        for (int userId : changedRuntimePermissionUserIds) {
10267            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10268        }
10269
10270        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10271    }
10272
10273    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10274        boolean allowed = false;
10275        final int NP = PackageParser.NEW_PERMISSIONS.length;
10276        for (int ip=0; ip<NP; ip++) {
10277            final PackageParser.NewPermissionInfo npi
10278                    = PackageParser.NEW_PERMISSIONS[ip];
10279            if (npi.name.equals(perm)
10280                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10281                allowed = true;
10282                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10283                        + pkg.packageName);
10284                break;
10285            }
10286        }
10287        return allowed;
10288    }
10289
10290    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10291            BasePermission bp, PermissionsState origPermissions) {
10292        boolean allowed;
10293        allowed = (compareSignatures(
10294                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10295                        == PackageManager.SIGNATURE_MATCH)
10296                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10297                        == PackageManager.SIGNATURE_MATCH);
10298        if (!allowed && (bp.protectionLevel
10299                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10300            if (isSystemApp(pkg)) {
10301                // For updated system applications, a system permission
10302                // is granted only if it had been defined by the original application.
10303                if (pkg.isUpdatedSystemApp()) {
10304                    final PackageSetting sysPs = mSettings
10305                            .getDisabledSystemPkgLPr(pkg.packageName);
10306                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10307                        // If the original was granted this permission, we take
10308                        // that grant decision as read and propagate it to the
10309                        // update.
10310                        if (sysPs.isPrivileged()) {
10311                            allowed = true;
10312                        }
10313                    } else {
10314                        // The system apk may have been updated with an older
10315                        // version of the one on the data partition, but which
10316                        // granted a new system permission that it didn't have
10317                        // before.  In this case we do want to allow the app to
10318                        // now get the new permission if the ancestral apk is
10319                        // privileged to get it.
10320                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10321                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10322                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10323                                    allowed = true;
10324                                    break;
10325                                }
10326                            }
10327                        }
10328                        // Also if a privileged parent package on the system image or any of
10329                        // its children requested a privileged permission, the updated child
10330                        // packages can also get the permission.
10331                        if (pkg.parentPackage != null) {
10332                            final PackageSetting disabledSysParentPs = mSettings
10333                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10334                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10335                                    && disabledSysParentPs.isPrivileged()) {
10336                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10337                                    allowed = true;
10338                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10339                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10340                                    for (int i = 0; i < count; i++) {
10341                                        PackageParser.Package disabledSysChildPkg =
10342                                                disabledSysParentPs.pkg.childPackages.get(i);
10343                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10344                                                perm)) {
10345                                            allowed = true;
10346                                            break;
10347                                        }
10348                                    }
10349                                }
10350                            }
10351                        }
10352                    }
10353                } else {
10354                    allowed = isPrivilegedApp(pkg);
10355                }
10356            }
10357        }
10358        if (!allowed) {
10359            if (!allowed && (bp.protectionLevel
10360                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10361                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10362                // If this was a previously normal/dangerous permission that got moved
10363                // to a system permission as part of the runtime permission redesign, then
10364                // we still want to blindly grant it to old apps.
10365                allowed = true;
10366            }
10367            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10368                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10369                // If this permission is to be granted to the system installer and
10370                // this app is an installer, then it gets the permission.
10371                allowed = true;
10372            }
10373            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10374                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10375                // If this permission is to be granted to the system verifier and
10376                // this app is a verifier, then it gets the permission.
10377                allowed = true;
10378            }
10379            if (!allowed && (bp.protectionLevel
10380                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10381                    && isSystemApp(pkg)) {
10382                // Any pre-installed system app is allowed to get this permission.
10383                allowed = true;
10384            }
10385            if (!allowed && (bp.protectionLevel
10386                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10387                // For development permissions, a development permission
10388                // is granted only if it was already granted.
10389                allowed = origPermissions.hasInstallPermission(perm);
10390            }
10391            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10392                    && pkg.packageName.equals(mSetupWizardPackage)) {
10393                // If this permission is to be granted to the system setup wizard and
10394                // this app is a setup wizard, then it gets the permission.
10395                allowed = true;
10396            }
10397        }
10398        return allowed;
10399    }
10400
10401    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10402        final int permCount = pkg.requestedPermissions.size();
10403        for (int j = 0; j < permCount; j++) {
10404            String requestedPermission = pkg.requestedPermissions.get(j);
10405            if (permission.equals(requestedPermission)) {
10406                return true;
10407            }
10408        }
10409        return false;
10410    }
10411
10412    final class ActivityIntentResolver
10413            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10414        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10415                boolean defaultOnly, int userId) {
10416            if (!sUserManager.exists(userId)) return null;
10417            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10418            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10419        }
10420
10421        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10422                int userId) {
10423            if (!sUserManager.exists(userId)) return null;
10424            mFlags = flags;
10425            return super.queryIntent(intent, resolvedType,
10426                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10427        }
10428
10429        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10430                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10431            if (!sUserManager.exists(userId)) return null;
10432            if (packageActivities == null) {
10433                return null;
10434            }
10435            mFlags = flags;
10436            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10437            final int N = packageActivities.size();
10438            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10439                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10440
10441            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10442            for (int i = 0; i < N; ++i) {
10443                intentFilters = packageActivities.get(i).intents;
10444                if (intentFilters != null && intentFilters.size() > 0) {
10445                    PackageParser.ActivityIntentInfo[] array =
10446                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10447                    intentFilters.toArray(array);
10448                    listCut.add(array);
10449                }
10450            }
10451            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10452        }
10453
10454        /**
10455         * Finds a privileged activity that matches the specified activity names.
10456         */
10457        private PackageParser.Activity findMatchingActivity(
10458                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10459            for (PackageParser.Activity sysActivity : activityList) {
10460                if (sysActivity.info.name.equals(activityInfo.name)) {
10461                    return sysActivity;
10462                }
10463                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10464                    return sysActivity;
10465                }
10466                if (sysActivity.info.targetActivity != null) {
10467                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10468                        return sysActivity;
10469                    }
10470                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10471                        return sysActivity;
10472                    }
10473                }
10474            }
10475            return null;
10476        }
10477
10478        public class IterGenerator<E> {
10479            public Iterator<E> generate(ActivityIntentInfo info) {
10480                return null;
10481            }
10482        }
10483
10484        public class ActionIterGenerator extends IterGenerator<String> {
10485            @Override
10486            public Iterator<String> generate(ActivityIntentInfo info) {
10487                return info.actionsIterator();
10488            }
10489        }
10490
10491        public class CategoriesIterGenerator extends IterGenerator<String> {
10492            @Override
10493            public Iterator<String> generate(ActivityIntentInfo info) {
10494                return info.categoriesIterator();
10495            }
10496        }
10497
10498        public class SchemesIterGenerator extends IterGenerator<String> {
10499            @Override
10500            public Iterator<String> generate(ActivityIntentInfo info) {
10501                return info.schemesIterator();
10502            }
10503        }
10504
10505        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10506            @Override
10507            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10508                return info.authoritiesIterator();
10509            }
10510        }
10511
10512        /**
10513         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10514         * MODIFIED. Do not pass in a list that should not be changed.
10515         */
10516        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10517                IterGenerator<T> generator, Iterator<T> searchIterator) {
10518            // loop through the set of actions; every one must be found in the intent filter
10519            while (searchIterator.hasNext()) {
10520                // we must have at least one filter in the list to consider a match
10521                if (intentList.size() == 0) {
10522                    break;
10523                }
10524
10525                final T searchAction = searchIterator.next();
10526
10527                // loop through the set of intent filters
10528                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10529                while (intentIter.hasNext()) {
10530                    final ActivityIntentInfo intentInfo = intentIter.next();
10531                    boolean selectionFound = false;
10532
10533                    // loop through the intent filter's selection criteria; at least one
10534                    // of them must match the searched criteria
10535                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10536                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10537                        final T intentSelection = intentSelectionIter.next();
10538                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10539                            selectionFound = true;
10540                            break;
10541                        }
10542                    }
10543
10544                    // the selection criteria wasn't found in this filter's set; this filter
10545                    // is not a potential match
10546                    if (!selectionFound) {
10547                        intentIter.remove();
10548                    }
10549                }
10550            }
10551        }
10552
10553        private boolean isProtectedAction(ActivityIntentInfo filter) {
10554            final Iterator<String> actionsIter = filter.actionsIterator();
10555            while (actionsIter != null && actionsIter.hasNext()) {
10556                final String filterAction = actionsIter.next();
10557                if (PROTECTED_ACTIONS.contains(filterAction)) {
10558                    return true;
10559                }
10560            }
10561            return false;
10562        }
10563
10564        /**
10565         * Adjusts the priority of the given intent filter according to policy.
10566         * <p>
10567         * <ul>
10568         * <li>The priority for non privileged applications is capped to '0'</li>
10569         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10570         * <li>The priority for unbundled updates to privileged applications is capped to the
10571         *      priority defined on the system partition</li>
10572         * </ul>
10573         * <p>
10574         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10575         * allowed to obtain any priority on any action.
10576         */
10577        private void adjustPriority(
10578                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10579            // nothing to do; priority is fine as-is
10580            if (intent.getPriority() <= 0) {
10581                return;
10582            }
10583
10584            final ActivityInfo activityInfo = intent.activity.info;
10585            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10586
10587            final boolean privilegedApp =
10588                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10589            if (!privilegedApp) {
10590                // non-privileged applications can never define a priority >0
10591                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10592                        + " package: " + applicationInfo.packageName
10593                        + " activity: " + intent.activity.className
10594                        + " origPrio: " + intent.getPriority());
10595                intent.setPriority(0);
10596                return;
10597            }
10598
10599            if (systemActivities == null) {
10600                // the system package is not disabled; we're parsing the system partition
10601                if (isProtectedAction(intent)) {
10602                    if (mDeferProtectedFilters) {
10603                        // We can't deal with these just yet. No component should ever obtain a
10604                        // >0 priority for a protected actions, with ONE exception -- the setup
10605                        // wizard. The setup wizard, however, cannot be known until we're able to
10606                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10607                        // until all intent filters have been processed. Chicken, meet egg.
10608                        // Let the filter temporarily have a high priority and rectify the
10609                        // priorities after all system packages have been scanned.
10610                        mProtectedFilters.add(intent);
10611                        if (DEBUG_FILTERS) {
10612                            Slog.i(TAG, "Protected action; save for later;"
10613                                    + " package: " + applicationInfo.packageName
10614                                    + " activity: " + intent.activity.className
10615                                    + " origPrio: " + intent.getPriority());
10616                        }
10617                        return;
10618                    } else {
10619                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10620                            Slog.i(TAG, "No setup wizard;"
10621                                + " All protected intents capped to priority 0");
10622                        }
10623                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10624                            if (DEBUG_FILTERS) {
10625                                Slog.i(TAG, "Found setup wizard;"
10626                                    + " allow priority " + intent.getPriority() + ";"
10627                                    + " package: " + intent.activity.info.packageName
10628                                    + " activity: " + intent.activity.className
10629                                    + " priority: " + intent.getPriority());
10630                            }
10631                            // setup wizard gets whatever it wants
10632                            return;
10633                        }
10634                        Slog.w(TAG, "Protected action; cap priority to 0;"
10635                                + " package: " + intent.activity.info.packageName
10636                                + " activity: " + intent.activity.className
10637                                + " origPrio: " + intent.getPriority());
10638                        intent.setPriority(0);
10639                        return;
10640                    }
10641                }
10642                // privileged apps on the system image get whatever priority they request
10643                return;
10644            }
10645
10646            // privileged app unbundled update ... try to find the same activity
10647            final PackageParser.Activity foundActivity =
10648                    findMatchingActivity(systemActivities, activityInfo);
10649            if (foundActivity == null) {
10650                // this is a new activity; it cannot obtain >0 priority
10651                if (DEBUG_FILTERS) {
10652                    Slog.i(TAG, "New activity; cap priority to 0;"
10653                            + " package: " + applicationInfo.packageName
10654                            + " activity: " + intent.activity.className
10655                            + " origPrio: " + intent.getPriority());
10656                }
10657                intent.setPriority(0);
10658                return;
10659            }
10660
10661            // found activity, now check for filter equivalence
10662
10663            // a shallow copy is enough; we modify the list, not its contents
10664            final List<ActivityIntentInfo> intentListCopy =
10665                    new ArrayList<>(foundActivity.intents);
10666            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10667
10668            // find matching action subsets
10669            final Iterator<String> actionsIterator = intent.actionsIterator();
10670            if (actionsIterator != null) {
10671                getIntentListSubset(
10672                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10673                if (intentListCopy.size() == 0) {
10674                    // no more intents to match; we're not equivalent
10675                    if (DEBUG_FILTERS) {
10676                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10677                                + " package: " + applicationInfo.packageName
10678                                + " activity: " + intent.activity.className
10679                                + " origPrio: " + intent.getPriority());
10680                    }
10681                    intent.setPriority(0);
10682                    return;
10683                }
10684            }
10685
10686            // find matching category subsets
10687            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10688            if (categoriesIterator != null) {
10689                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10690                        categoriesIterator);
10691                if (intentListCopy.size() == 0) {
10692                    // no more intents to match; we're not equivalent
10693                    if (DEBUG_FILTERS) {
10694                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10695                                + " package: " + applicationInfo.packageName
10696                                + " activity: " + intent.activity.className
10697                                + " origPrio: " + intent.getPriority());
10698                    }
10699                    intent.setPriority(0);
10700                    return;
10701                }
10702            }
10703
10704            // find matching schemes subsets
10705            final Iterator<String> schemesIterator = intent.schemesIterator();
10706            if (schemesIterator != null) {
10707                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10708                        schemesIterator);
10709                if (intentListCopy.size() == 0) {
10710                    // no more intents to match; we're not equivalent
10711                    if (DEBUG_FILTERS) {
10712                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10713                                + " package: " + applicationInfo.packageName
10714                                + " activity: " + intent.activity.className
10715                                + " origPrio: " + intent.getPriority());
10716                    }
10717                    intent.setPriority(0);
10718                    return;
10719                }
10720            }
10721
10722            // find matching authorities subsets
10723            final Iterator<IntentFilter.AuthorityEntry>
10724                    authoritiesIterator = intent.authoritiesIterator();
10725            if (authoritiesIterator != null) {
10726                getIntentListSubset(intentListCopy,
10727                        new AuthoritiesIterGenerator(),
10728                        authoritiesIterator);
10729                if (intentListCopy.size() == 0) {
10730                    // no more intents to match; we're not equivalent
10731                    if (DEBUG_FILTERS) {
10732                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10733                                + " package: " + applicationInfo.packageName
10734                                + " activity: " + intent.activity.className
10735                                + " origPrio: " + intent.getPriority());
10736                    }
10737                    intent.setPriority(0);
10738                    return;
10739                }
10740            }
10741
10742            // we found matching filter(s); app gets the max priority of all intents
10743            int cappedPriority = 0;
10744            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10745                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10746            }
10747            if (intent.getPriority() > cappedPriority) {
10748                if (DEBUG_FILTERS) {
10749                    Slog.i(TAG, "Found matching filter(s);"
10750                            + " cap priority to " + cappedPriority + ";"
10751                            + " package: " + applicationInfo.packageName
10752                            + " activity: " + intent.activity.className
10753                            + " origPrio: " + intent.getPriority());
10754                }
10755                intent.setPriority(cappedPriority);
10756                return;
10757            }
10758            // all this for nothing; the requested priority was <= what was on the system
10759        }
10760
10761        public final void addActivity(PackageParser.Activity a, String type) {
10762            mActivities.put(a.getComponentName(), a);
10763            if (DEBUG_SHOW_INFO)
10764                Log.v(
10765                TAG, "  " + type + " " +
10766                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10767            if (DEBUG_SHOW_INFO)
10768                Log.v(TAG, "    Class=" + a.info.name);
10769            final int NI = a.intents.size();
10770            for (int j=0; j<NI; j++) {
10771                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10772                if ("activity".equals(type)) {
10773                    final PackageSetting ps =
10774                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10775                    final List<PackageParser.Activity> systemActivities =
10776                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10777                    adjustPriority(systemActivities, intent);
10778                }
10779                if (DEBUG_SHOW_INFO) {
10780                    Log.v(TAG, "    IntentFilter:");
10781                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10782                }
10783                if (!intent.debugCheck()) {
10784                    Log.w(TAG, "==> For Activity " + a.info.name);
10785                }
10786                addFilter(intent);
10787            }
10788        }
10789
10790        public final void removeActivity(PackageParser.Activity a, String type) {
10791            mActivities.remove(a.getComponentName());
10792            if (DEBUG_SHOW_INFO) {
10793                Log.v(TAG, "  " + type + " "
10794                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10795                                : a.info.name) + ":");
10796                Log.v(TAG, "    Class=" + a.info.name);
10797            }
10798            final int NI = a.intents.size();
10799            for (int j=0; j<NI; j++) {
10800                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10801                if (DEBUG_SHOW_INFO) {
10802                    Log.v(TAG, "    IntentFilter:");
10803                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10804                }
10805                removeFilter(intent);
10806            }
10807        }
10808
10809        @Override
10810        protected boolean allowFilterResult(
10811                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10812            ActivityInfo filterAi = filter.activity.info;
10813            for (int i=dest.size()-1; i>=0; i--) {
10814                ActivityInfo destAi = dest.get(i).activityInfo;
10815                if (destAi.name == filterAi.name
10816                        && destAi.packageName == filterAi.packageName) {
10817                    return false;
10818                }
10819            }
10820            return true;
10821        }
10822
10823        @Override
10824        protected ActivityIntentInfo[] newArray(int size) {
10825            return new ActivityIntentInfo[size];
10826        }
10827
10828        @Override
10829        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10830            if (!sUserManager.exists(userId)) return true;
10831            PackageParser.Package p = filter.activity.owner;
10832            if (p != null) {
10833                PackageSetting ps = (PackageSetting)p.mExtras;
10834                if (ps != null) {
10835                    // System apps are never considered stopped for purposes of
10836                    // filtering, because there may be no way for the user to
10837                    // actually re-launch them.
10838                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10839                            && ps.getStopped(userId);
10840                }
10841            }
10842            return false;
10843        }
10844
10845        @Override
10846        protected boolean isPackageForFilter(String packageName,
10847                PackageParser.ActivityIntentInfo info) {
10848            return packageName.equals(info.activity.owner.packageName);
10849        }
10850
10851        @Override
10852        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10853                int match, int userId) {
10854            if (!sUserManager.exists(userId)) return null;
10855            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10856                return null;
10857            }
10858            final PackageParser.Activity activity = info.activity;
10859            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10860            if (ps == null) {
10861                return null;
10862            }
10863            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10864                    ps.readUserState(userId), userId);
10865            if (ai == null) {
10866                return null;
10867            }
10868            final ResolveInfo res = new ResolveInfo();
10869            res.activityInfo = ai;
10870            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10871                res.filter = info;
10872            }
10873            if (info != null) {
10874                res.handleAllWebDataURI = info.handleAllWebDataURI();
10875            }
10876            res.priority = info.getPriority();
10877            res.preferredOrder = activity.owner.mPreferredOrder;
10878            //System.out.println("Result: " + res.activityInfo.className +
10879            //                   " = " + res.priority);
10880            res.match = match;
10881            res.isDefault = info.hasDefault;
10882            res.labelRes = info.labelRes;
10883            res.nonLocalizedLabel = info.nonLocalizedLabel;
10884            if (userNeedsBadging(userId)) {
10885                res.noResourceId = true;
10886            } else {
10887                res.icon = info.icon;
10888            }
10889            res.iconResourceId = info.icon;
10890            res.system = res.activityInfo.applicationInfo.isSystemApp();
10891            return res;
10892        }
10893
10894        @Override
10895        protected void sortResults(List<ResolveInfo> results) {
10896            Collections.sort(results, mResolvePrioritySorter);
10897        }
10898
10899        @Override
10900        protected void dumpFilter(PrintWriter out, String prefix,
10901                PackageParser.ActivityIntentInfo filter) {
10902            out.print(prefix); out.print(
10903                    Integer.toHexString(System.identityHashCode(filter.activity)));
10904                    out.print(' ');
10905                    filter.activity.printComponentShortName(out);
10906                    out.print(" filter ");
10907                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10908        }
10909
10910        @Override
10911        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10912            return filter.activity;
10913        }
10914
10915        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10916            PackageParser.Activity activity = (PackageParser.Activity)label;
10917            out.print(prefix); out.print(
10918                    Integer.toHexString(System.identityHashCode(activity)));
10919                    out.print(' ');
10920                    activity.printComponentShortName(out);
10921            if (count > 1) {
10922                out.print(" ("); out.print(count); out.print(" filters)");
10923            }
10924            out.println();
10925        }
10926
10927        // Keys are String (activity class name), values are Activity.
10928        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10929                = new ArrayMap<ComponentName, PackageParser.Activity>();
10930        private int mFlags;
10931    }
10932
10933    private final class ServiceIntentResolver
10934            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10935        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10936                boolean defaultOnly, int userId) {
10937            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10938            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10939        }
10940
10941        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10942                int userId) {
10943            if (!sUserManager.exists(userId)) return null;
10944            mFlags = flags;
10945            return super.queryIntent(intent, resolvedType,
10946                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10947        }
10948
10949        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10950                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10951            if (!sUserManager.exists(userId)) return null;
10952            if (packageServices == null) {
10953                return null;
10954            }
10955            mFlags = flags;
10956            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10957            final int N = packageServices.size();
10958            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10959                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10960
10961            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10962            for (int i = 0; i < N; ++i) {
10963                intentFilters = packageServices.get(i).intents;
10964                if (intentFilters != null && intentFilters.size() > 0) {
10965                    PackageParser.ServiceIntentInfo[] array =
10966                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10967                    intentFilters.toArray(array);
10968                    listCut.add(array);
10969                }
10970            }
10971            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10972        }
10973
10974        public final void addService(PackageParser.Service s) {
10975            mServices.put(s.getComponentName(), s);
10976            if (DEBUG_SHOW_INFO) {
10977                Log.v(TAG, "  "
10978                        + (s.info.nonLocalizedLabel != null
10979                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10980                Log.v(TAG, "    Class=" + s.info.name);
10981            }
10982            final int NI = s.intents.size();
10983            int j;
10984            for (j=0; j<NI; j++) {
10985                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10986                if (DEBUG_SHOW_INFO) {
10987                    Log.v(TAG, "    IntentFilter:");
10988                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10989                }
10990                if (!intent.debugCheck()) {
10991                    Log.w(TAG, "==> For Service " + s.info.name);
10992                }
10993                addFilter(intent);
10994            }
10995        }
10996
10997        public final void removeService(PackageParser.Service s) {
10998            mServices.remove(s.getComponentName());
10999            if (DEBUG_SHOW_INFO) {
11000                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
11001                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11002                Log.v(TAG, "    Class=" + s.info.name);
11003            }
11004            final int NI = s.intents.size();
11005            int j;
11006            for (j=0; j<NI; j++) {
11007                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11008                if (DEBUG_SHOW_INFO) {
11009                    Log.v(TAG, "    IntentFilter:");
11010                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11011                }
11012                removeFilter(intent);
11013            }
11014        }
11015
11016        @Override
11017        protected boolean allowFilterResult(
11018                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11019            ServiceInfo filterSi = filter.service.info;
11020            for (int i=dest.size()-1; i>=0; i--) {
11021                ServiceInfo destAi = dest.get(i).serviceInfo;
11022                if (destAi.name == filterSi.name
11023                        && destAi.packageName == filterSi.packageName) {
11024                    return false;
11025                }
11026            }
11027            return true;
11028        }
11029
11030        @Override
11031        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11032            return new PackageParser.ServiceIntentInfo[size];
11033        }
11034
11035        @Override
11036        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11037            if (!sUserManager.exists(userId)) return true;
11038            PackageParser.Package p = filter.service.owner;
11039            if (p != null) {
11040                PackageSetting ps = (PackageSetting)p.mExtras;
11041                if (ps != null) {
11042                    // System apps are never considered stopped for purposes of
11043                    // filtering, because there may be no way for the user to
11044                    // actually re-launch them.
11045                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11046                            && ps.getStopped(userId);
11047                }
11048            }
11049            return false;
11050        }
11051
11052        @Override
11053        protected boolean isPackageForFilter(String packageName,
11054                PackageParser.ServiceIntentInfo info) {
11055            return packageName.equals(info.service.owner.packageName);
11056        }
11057
11058        @Override
11059        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11060                int match, int userId) {
11061            if (!sUserManager.exists(userId)) return null;
11062            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11063            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11064                return null;
11065            }
11066            final PackageParser.Service service = info.service;
11067            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11068            if (ps == null) {
11069                return null;
11070            }
11071            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11072                    ps.readUserState(userId), userId);
11073            if (si == null) {
11074                return null;
11075            }
11076            final ResolveInfo res = new ResolveInfo();
11077            res.serviceInfo = si;
11078            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11079                res.filter = filter;
11080            }
11081            res.priority = info.getPriority();
11082            res.preferredOrder = service.owner.mPreferredOrder;
11083            res.match = match;
11084            res.isDefault = info.hasDefault;
11085            res.labelRes = info.labelRes;
11086            res.nonLocalizedLabel = info.nonLocalizedLabel;
11087            res.icon = info.icon;
11088            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11089            return res;
11090        }
11091
11092        @Override
11093        protected void sortResults(List<ResolveInfo> results) {
11094            Collections.sort(results, mResolvePrioritySorter);
11095        }
11096
11097        @Override
11098        protected void dumpFilter(PrintWriter out, String prefix,
11099                PackageParser.ServiceIntentInfo filter) {
11100            out.print(prefix); out.print(
11101                    Integer.toHexString(System.identityHashCode(filter.service)));
11102                    out.print(' ');
11103                    filter.service.printComponentShortName(out);
11104                    out.print(" filter ");
11105                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11106        }
11107
11108        @Override
11109        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11110            return filter.service;
11111        }
11112
11113        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11114            PackageParser.Service service = (PackageParser.Service)label;
11115            out.print(prefix); out.print(
11116                    Integer.toHexString(System.identityHashCode(service)));
11117                    out.print(' ');
11118                    service.printComponentShortName(out);
11119            if (count > 1) {
11120                out.print(" ("); out.print(count); out.print(" filters)");
11121            }
11122            out.println();
11123        }
11124
11125//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11126//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11127//            final List<ResolveInfo> retList = Lists.newArrayList();
11128//            while (i.hasNext()) {
11129//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11130//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11131//                    retList.add(resolveInfo);
11132//                }
11133//            }
11134//            return retList;
11135//        }
11136
11137        // Keys are String (activity class name), values are Activity.
11138        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11139                = new ArrayMap<ComponentName, PackageParser.Service>();
11140        private int mFlags;
11141    };
11142
11143    private final class ProviderIntentResolver
11144            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11145        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11146                boolean defaultOnly, int userId) {
11147            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11148            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11149        }
11150
11151        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11152                int userId) {
11153            if (!sUserManager.exists(userId))
11154                return null;
11155            mFlags = flags;
11156            return super.queryIntent(intent, resolvedType,
11157                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11158        }
11159
11160        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11161                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11162            if (!sUserManager.exists(userId))
11163                return null;
11164            if (packageProviders == null) {
11165                return null;
11166            }
11167            mFlags = flags;
11168            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11169            final int N = packageProviders.size();
11170            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11171                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11172
11173            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11174            for (int i = 0; i < N; ++i) {
11175                intentFilters = packageProviders.get(i).intents;
11176                if (intentFilters != null && intentFilters.size() > 0) {
11177                    PackageParser.ProviderIntentInfo[] array =
11178                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11179                    intentFilters.toArray(array);
11180                    listCut.add(array);
11181                }
11182            }
11183            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11184        }
11185
11186        public final void addProvider(PackageParser.Provider p) {
11187            if (mProviders.containsKey(p.getComponentName())) {
11188                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11189                return;
11190            }
11191
11192            mProviders.put(p.getComponentName(), p);
11193            if (DEBUG_SHOW_INFO) {
11194                Log.v(TAG, "  "
11195                        + (p.info.nonLocalizedLabel != null
11196                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11197                Log.v(TAG, "    Class=" + p.info.name);
11198            }
11199            final int NI = p.intents.size();
11200            int j;
11201            for (j = 0; j < NI; j++) {
11202                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11203                if (DEBUG_SHOW_INFO) {
11204                    Log.v(TAG, "    IntentFilter:");
11205                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11206                }
11207                if (!intent.debugCheck()) {
11208                    Log.w(TAG, "==> For Provider " + p.info.name);
11209                }
11210                addFilter(intent);
11211            }
11212        }
11213
11214        public final void removeProvider(PackageParser.Provider p) {
11215            mProviders.remove(p.getComponentName());
11216            if (DEBUG_SHOW_INFO) {
11217                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11218                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11219                Log.v(TAG, "    Class=" + p.info.name);
11220            }
11221            final int NI = p.intents.size();
11222            int j;
11223            for (j = 0; j < NI; j++) {
11224                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11225                if (DEBUG_SHOW_INFO) {
11226                    Log.v(TAG, "    IntentFilter:");
11227                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11228                }
11229                removeFilter(intent);
11230            }
11231        }
11232
11233        @Override
11234        protected boolean allowFilterResult(
11235                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11236            ProviderInfo filterPi = filter.provider.info;
11237            for (int i = dest.size() - 1; i >= 0; i--) {
11238                ProviderInfo destPi = dest.get(i).providerInfo;
11239                if (destPi.name == filterPi.name
11240                        && destPi.packageName == filterPi.packageName) {
11241                    return false;
11242                }
11243            }
11244            return true;
11245        }
11246
11247        @Override
11248        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11249            return new PackageParser.ProviderIntentInfo[size];
11250        }
11251
11252        @Override
11253        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11254            if (!sUserManager.exists(userId))
11255                return true;
11256            PackageParser.Package p = filter.provider.owner;
11257            if (p != null) {
11258                PackageSetting ps = (PackageSetting) p.mExtras;
11259                if (ps != null) {
11260                    // System apps are never considered stopped for purposes of
11261                    // filtering, because there may be no way for the user to
11262                    // actually re-launch them.
11263                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11264                            && ps.getStopped(userId);
11265                }
11266            }
11267            return false;
11268        }
11269
11270        @Override
11271        protected boolean isPackageForFilter(String packageName,
11272                PackageParser.ProviderIntentInfo info) {
11273            return packageName.equals(info.provider.owner.packageName);
11274        }
11275
11276        @Override
11277        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11278                int match, int userId) {
11279            if (!sUserManager.exists(userId))
11280                return null;
11281            final PackageParser.ProviderIntentInfo info = filter;
11282            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11283                return null;
11284            }
11285            final PackageParser.Provider provider = info.provider;
11286            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11287            if (ps == null) {
11288                return null;
11289            }
11290            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11291                    ps.readUserState(userId), userId);
11292            if (pi == null) {
11293                return null;
11294            }
11295            final ResolveInfo res = new ResolveInfo();
11296            res.providerInfo = pi;
11297            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11298                res.filter = filter;
11299            }
11300            res.priority = info.getPriority();
11301            res.preferredOrder = provider.owner.mPreferredOrder;
11302            res.match = match;
11303            res.isDefault = info.hasDefault;
11304            res.labelRes = info.labelRes;
11305            res.nonLocalizedLabel = info.nonLocalizedLabel;
11306            res.icon = info.icon;
11307            res.system = res.providerInfo.applicationInfo.isSystemApp();
11308            return res;
11309        }
11310
11311        @Override
11312        protected void sortResults(List<ResolveInfo> results) {
11313            Collections.sort(results, mResolvePrioritySorter);
11314        }
11315
11316        @Override
11317        protected void dumpFilter(PrintWriter out, String prefix,
11318                PackageParser.ProviderIntentInfo filter) {
11319            out.print(prefix);
11320            out.print(
11321                    Integer.toHexString(System.identityHashCode(filter.provider)));
11322            out.print(' ');
11323            filter.provider.printComponentShortName(out);
11324            out.print(" filter ");
11325            out.println(Integer.toHexString(System.identityHashCode(filter)));
11326        }
11327
11328        @Override
11329        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11330            return filter.provider;
11331        }
11332
11333        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11334            PackageParser.Provider provider = (PackageParser.Provider)label;
11335            out.print(prefix); out.print(
11336                    Integer.toHexString(System.identityHashCode(provider)));
11337                    out.print(' ');
11338                    provider.printComponentShortName(out);
11339            if (count > 1) {
11340                out.print(" ("); out.print(count); out.print(" filters)");
11341            }
11342            out.println();
11343        }
11344
11345        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11346                = new ArrayMap<ComponentName, PackageParser.Provider>();
11347        private int mFlags;
11348    }
11349
11350    private static final class EphemeralIntentResolver
11351            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11352        /**
11353         * The result that has the highest defined order. Ordering applies on a
11354         * per-package basis. Mapping is from package name to Pair of order and
11355         * EphemeralResolveInfo.
11356         * <p>
11357         * NOTE: This is implemented as a field variable for convenience and efficiency.
11358         * By having a field variable, we're able to track filter ordering as soon as
11359         * a non-zero order is defined. Otherwise, multiple loops across the result set
11360         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11361         * this needs to be contained entirely within {@link #filterResults()}.
11362         */
11363        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11364
11365        @Override
11366        protected EphemeralResolveIntentInfo[] newArray(int size) {
11367            return new EphemeralResolveIntentInfo[size];
11368        }
11369
11370        @Override
11371        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11372            return true;
11373        }
11374
11375        @Override
11376        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11377                int userId) {
11378            if (!sUserManager.exists(userId)) {
11379                return null;
11380            }
11381            final String packageName = info.getEphemeralResolveInfo().getPackageName();
11382            final Integer order = info.getOrder();
11383            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11384                    mOrderResult.get(packageName);
11385            // ordering is enabled and this item's order isn't high enough
11386            if (lastOrderResult != null && lastOrderResult.first >= order) {
11387                return null;
11388            }
11389            final EphemeralResolveInfo res = info.getEphemeralResolveInfo();
11390            if (order > 0) {
11391                // non-zero order, enable ordering
11392                mOrderResult.put(packageName, new Pair<>(order, res));
11393            }
11394            return res;
11395        }
11396
11397        @Override
11398        protected void filterResults(List<EphemeralResolveInfo> results) {
11399            // only do work if ordering is enabled [most of the time it won't be]
11400            if (mOrderResult.size() == 0) {
11401                return;
11402            }
11403            int resultSize = results.size();
11404            for (int i = 0; i < resultSize; i++) {
11405                final EphemeralResolveInfo info = results.get(i);
11406                final String packageName = info.getPackageName();
11407                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11408                if (savedInfo == null) {
11409                    // package doesn't having ordering
11410                    continue;
11411                }
11412                if (savedInfo.second == info) {
11413                    // circled back to the highest ordered item; remove from order list
11414                    mOrderResult.remove(savedInfo);
11415                    if (mOrderResult.size() == 0) {
11416                        // no more ordered items
11417                        break;
11418                    }
11419                    continue;
11420                }
11421                // item has a worse order, remove it from the result list
11422                results.remove(i);
11423                resultSize--;
11424                i--;
11425            }
11426        }
11427    }
11428
11429    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11430            new Comparator<ResolveInfo>() {
11431        public int compare(ResolveInfo r1, ResolveInfo r2) {
11432            int v1 = r1.priority;
11433            int v2 = r2.priority;
11434            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11435            if (v1 != v2) {
11436                return (v1 > v2) ? -1 : 1;
11437            }
11438            v1 = r1.preferredOrder;
11439            v2 = r2.preferredOrder;
11440            if (v1 != v2) {
11441                return (v1 > v2) ? -1 : 1;
11442            }
11443            if (r1.isDefault != r2.isDefault) {
11444                return r1.isDefault ? -1 : 1;
11445            }
11446            v1 = r1.match;
11447            v2 = r2.match;
11448            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11449            if (v1 != v2) {
11450                return (v1 > v2) ? -1 : 1;
11451            }
11452            if (r1.system != r2.system) {
11453                return r1.system ? -1 : 1;
11454            }
11455            if (r1.activityInfo != null) {
11456                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11457            }
11458            if (r1.serviceInfo != null) {
11459                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11460            }
11461            if (r1.providerInfo != null) {
11462                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11463            }
11464            return 0;
11465        }
11466    };
11467
11468    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11469            new Comparator<ProviderInfo>() {
11470        public int compare(ProviderInfo p1, ProviderInfo p2) {
11471            final int v1 = p1.initOrder;
11472            final int v2 = p2.initOrder;
11473            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11474        }
11475    };
11476
11477    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11478            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11479            final int[] userIds) {
11480        mHandler.post(new Runnable() {
11481            @Override
11482            public void run() {
11483                try {
11484                    final IActivityManager am = ActivityManagerNative.getDefault();
11485                    if (am == null) return;
11486                    final int[] resolvedUserIds;
11487                    if (userIds == null) {
11488                        resolvedUserIds = am.getRunningUserIds();
11489                    } else {
11490                        resolvedUserIds = userIds;
11491                    }
11492                    for (int id : resolvedUserIds) {
11493                        final Intent intent = new Intent(action,
11494                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11495                        if (extras != null) {
11496                            intent.putExtras(extras);
11497                        }
11498                        if (targetPkg != null) {
11499                            intent.setPackage(targetPkg);
11500                        }
11501                        // Modify the UID when posting to other users
11502                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11503                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11504                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11505                            intent.putExtra(Intent.EXTRA_UID, uid);
11506                        }
11507                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11508                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11509                        if (DEBUG_BROADCASTS) {
11510                            RuntimeException here = new RuntimeException("here");
11511                            here.fillInStackTrace();
11512                            Slog.d(TAG, "Sending to user " + id + ": "
11513                                    + intent.toShortString(false, true, false, false)
11514                                    + " " + intent.getExtras(), here);
11515                        }
11516                        am.broadcastIntent(null, intent, null, finishedReceiver,
11517                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11518                                null, finishedReceiver != null, false, id);
11519                    }
11520                } catch (RemoteException ex) {
11521                }
11522            }
11523        });
11524    }
11525
11526    /**
11527     * Check if the external storage media is available. This is true if there
11528     * is a mounted external storage medium or if the external storage is
11529     * emulated.
11530     */
11531    private boolean isExternalMediaAvailable() {
11532        return mMediaMounted || Environment.isExternalStorageEmulated();
11533    }
11534
11535    @Override
11536    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11537        // writer
11538        synchronized (mPackages) {
11539            if (!isExternalMediaAvailable()) {
11540                // If the external storage is no longer mounted at this point,
11541                // the caller may not have been able to delete all of this
11542                // packages files and can not delete any more.  Bail.
11543                return null;
11544            }
11545            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11546            if (lastPackage != null) {
11547                pkgs.remove(lastPackage);
11548            }
11549            if (pkgs.size() > 0) {
11550                return pkgs.get(0);
11551            }
11552        }
11553        return null;
11554    }
11555
11556    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11557        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11558                userId, andCode ? 1 : 0, packageName);
11559        if (mSystemReady) {
11560            msg.sendToTarget();
11561        } else {
11562            if (mPostSystemReadyMessages == null) {
11563                mPostSystemReadyMessages = new ArrayList<>();
11564            }
11565            mPostSystemReadyMessages.add(msg);
11566        }
11567    }
11568
11569    void startCleaningPackages() {
11570        // reader
11571        if (!isExternalMediaAvailable()) {
11572            return;
11573        }
11574        synchronized (mPackages) {
11575            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11576                return;
11577            }
11578        }
11579        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11580        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11581        IActivityManager am = ActivityManagerNative.getDefault();
11582        if (am != null) {
11583            try {
11584                am.startService(null, intent, null, mContext.getOpPackageName(),
11585                        UserHandle.USER_SYSTEM);
11586            } catch (RemoteException e) {
11587            }
11588        }
11589    }
11590
11591    @Override
11592    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11593            int installFlags, String installerPackageName, int userId) {
11594        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11595
11596        final int callingUid = Binder.getCallingUid();
11597        enforceCrossUserPermission(callingUid, userId,
11598                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11599
11600        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11601            try {
11602                if (observer != null) {
11603                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11604                }
11605            } catch (RemoteException re) {
11606            }
11607            return;
11608        }
11609
11610        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11611            installFlags |= PackageManager.INSTALL_FROM_ADB;
11612
11613        } else {
11614            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11615            // about installerPackageName.
11616
11617            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11618            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11619        }
11620
11621        UserHandle user;
11622        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11623            user = UserHandle.ALL;
11624        } else {
11625            user = new UserHandle(userId);
11626        }
11627
11628        // Only system components can circumvent runtime permissions when installing.
11629        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11630                && mContext.checkCallingOrSelfPermission(Manifest.permission
11631                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11632            throw new SecurityException("You need the "
11633                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11634                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11635        }
11636
11637        final File originFile = new File(originPath);
11638        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11639
11640        final Message msg = mHandler.obtainMessage(INIT_COPY);
11641        final VerificationInfo verificationInfo = new VerificationInfo(
11642                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11643        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11644                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11645                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11646                null /*certificates*/);
11647        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11648        msg.obj = params;
11649
11650        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11651                System.identityHashCode(msg.obj));
11652        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11653                System.identityHashCode(msg.obj));
11654
11655        mHandler.sendMessage(msg);
11656    }
11657
11658    void installStage(String packageName, File stagedDir, String stagedCid,
11659            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11660            String installerPackageName, int installerUid, UserHandle user,
11661            Certificate[][] certificates) {
11662        if (DEBUG_EPHEMERAL) {
11663            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11664                Slog.d(TAG, "Ephemeral install of " + packageName);
11665            }
11666        }
11667        final VerificationInfo verificationInfo = new VerificationInfo(
11668                sessionParams.originatingUri, sessionParams.referrerUri,
11669                sessionParams.originatingUid, installerUid);
11670
11671        final OriginInfo origin;
11672        if (stagedDir != null) {
11673            origin = OriginInfo.fromStagedFile(stagedDir);
11674        } else {
11675            origin = OriginInfo.fromStagedContainer(stagedCid);
11676        }
11677
11678        final Message msg = mHandler.obtainMessage(INIT_COPY);
11679        final InstallParams params = new InstallParams(origin, null, observer,
11680                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11681                verificationInfo, user, sessionParams.abiOverride,
11682                sessionParams.grantedRuntimePermissions, certificates);
11683        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11684        msg.obj = params;
11685
11686        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11687                System.identityHashCode(msg.obj));
11688        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11689                System.identityHashCode(msg.obj));
11690
11691        mHandler.sendMessage(msg);
11692    }
11693
11694    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11695            int userId) {
11696        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11697        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11698    }
11699
11700    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11701            int appId, int userId) {
11702        Bundle extras = new Bundle(1);
11703        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11704
11705        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11706                packageName, extras, 0, null, null, new int[] {userId});
11707        try {
11708            IActivityManager am = ActivityManagerNative.getDefault();
11709            if (isSystem && am.isUserRunning(userId, 0)) {
11710                // The just-installed/enabled app is bundled on the system, so presumed
11711                // to be able to run automatically without needing an explicit launch.
11712                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11713                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11714                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11715                        .setPackage(packageName);
11716                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11717                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11718            }
11719        } catch (RemoteException e) {
11720            // shouldn't happen
11721            Slog.w(TAG, "Unable to bootstrap installed package", e);
11722        }
11723    }
11724
11725    @Override
11726    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11727            int userId) {
11728        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11729        PackageSetting pkgSetting;
11730        final int uid = Binder.getCallingUid();
11731        enforceCrossUserPermission(uid, userId,
11732                true /* requireFullPermission */, true /* checkShell */,
11733                "setApplicationHiddenSetting for user " + userId);
11734
11735        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11736            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11737            return false;
11738        }
11739
11740        long callingId = Binder.clearCallingIdentity();
11741        try {
11742            boolean sendAdded = false;
11743            boolean sendRemoved = false;
11744            // writer
11745            synchronized (mPackages) {
11746                pkgSetting = mSettings.mPackages.get(packageName);
11747                if (pkgSetting == null) {
11748                    return false;
11749                }
11750                // Do not allow "android" is being disabled
11751                if ("android".equals(packageName)) {
11752                    Slog.w(TAG, "Cannot hide package: android");
11753                    return false;
11754                }
11755                // Only allow protected packages to hide themselves.
11756                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11757                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11758                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11759                    return false;
11760                }
11761
11762                if (pkgSetting.getHidden(userId) != hidden) {
11763                    pkgSetting.setHidden(hidden, userId);
11764                    mSettings.writePackageRestrictionsLPr(userId);
11765                    if (hidden) {
11766                        sendRemoved = true;
11767                    } else {
11768                        sendAdded = true;
11769                    }
11770                }
11771            }
11772            if (sendAdded) {
11773                sendPackageAddedForUser(packageName, pkgSetting, userId);
11774                return true;
11775            }
11776            if (sendRemoved) {
11777                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11778                        "hiding pkg");
11779                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11780                return true;
11781            }
11782        } finally {
11783            Binder.restoreCallingIdentity(callingId);
11784        }
11785        return false;
11786    }
11787
11788    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11789            int userId) {
11790        final PackageRemovedInfo info = new PackageRemovedInfo();
11791        info.removedPackage = packageName;
11792        info.removedUsers = new int[] {userId};
11793        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11794        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11795    }
11796
11797    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11798        if (pkgList.length > 0) {
11799            Bundle extras = new Bundle(1);
11800            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11801
11802            sendPackageBroadcast(
11803                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11804                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11805                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11806                    new int[] {userId});
11807        }
11808    }
11809
11810    /**
11811     * Returns true if application is not found or there was an error. Otherwise it returns
11812     * the hidden state of the package for the given user.
11813     */
11814    @Override
11815    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11816        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11817        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11818                true /* requireFullPermission */, false /* checkShell */,
11819                "getApplicationHidden for user " + userId);
11820        PackageSetting pkgSetting;
11821        long callingId = Binder.clearCallingIdentity();
11822        try {
11823            // writer
11824            synchronized (mPackages) {
11825                pkgSetting = mSettings.mPackages.get(packageName);
11826                if (pkgSetting == null) {
11827                    return true;
11828                }
11829                return pkgSetting.getHidden(userId);
11830            }
11831        } finally {
11832            Binder.restoreCallingIdentity(callingId);
11833        }
11834    }
11835
11836    /**
11837     * @hide
11838     */
11839    @Override
11840    public int installExistingPackageAsUser(String packageName, int userId) {
11841        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11842                null);
11843        PackageSetting pkgSetting;
11844        final int uid = Binder.getCallingUid();
11845        enforceCrossUserPermission(uid, userId,
11846                true /* requireFullPermission */, true /* checkShell */,
11847                "installExistingPackage for user " + userId);
11848        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11849            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11850        }
11851
11852        long callingId = Binder.clearCallingIdentity();
11853        try {
11854            boolean installed = false;
11855
11856            // writer
11857            synchronized (mPackages) {
11858                pkgSetting = mSettings.mPackages.get(packageName);
11859                if (pkgSetting == null) {
11860                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11861                }
11862                if (!pkgSetting.getInstalled(userId)) {
11863                    pkgSetting.setInstalled(true, userId);
11864                    pkgSetting.setHidden(false, userId);
11865                    mSettings.writePackageRestrictionsLPr(userId);
11866                    installed = true;
11867                }
11868            }
11869
11870            if (installed) {
11871                if (pkgSetting.pkg != null) {
11872                    synchronized (mInstallLock) {
11873                        // We don't need to freeze for a brand new install
11874                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11875                    }
11876                }
11877                sendPackageAddedForUser(packageName, pkgSetting, userId);
11878            }
11879        } finally {
11880            Binder.restoreCallingIdentity(callingId);
11881        }
11882
11883        return PackageManager.INSTALL_SUCCEEDED;
11884    }
11885
11886    boolean isUserRestricted(int userId, String restrictionKey) {
11887        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11888        if (restrictions.getBoolean(restrictionKey, false)) {
11889            Log.w(TAG, "User is restricted: " + restrictionKey);
11890            return true;
11891        }
11892        return false;
11893    }
11894
11895    @Override
11896    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11897            int userId) {
11898        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11899        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11900                true /* requireFullPermission */, true /* checkShell */,
11901                "setPackagesSuspended for user " + userId);
11902
11903        if (ArrayUtils.isEmpty(packageNames)) {
11904            return packageNames;
11905        }
11906
11907        // List of package names for whom the suspended state has changed.
11908        List<String> changedPackages = new ArrayList<>(packageNames.length);
11909        // List of package names for whom the suspended state is not set as requested in this
11910        // method.
11911        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11912        long callingId = Binder.clearCallingIdentity();
11913        try {
11914            for (int i = 0; i < packageNames.length; i++) {
11915                String packageName = packageNames[i];
11916                boolean changed = false;
11917                final int appId;
11918                synchronized (mPackages) {
11919                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11920                    if (pkgSetting == null) {
11921                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11922                                + "\". Skipping suspending/un-suspending.");
11923                        unactionedPackages.add(packageName);
11924                        continue;
11925                    }
11926                    appId = pkgSetting.appId;
11927                    if (pkgSetting.getSuspended(userId) != suspended) {
11928                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11929                            unactionedPackages.add(packageName);
11930                            continue;
11931                        }
11932                        pkgSetting.setSuspended(suspended, userId);
11933                        mSettings.writePackageRestrictionsLPr(userId);
11934                        changed = true;
11935                        changedPackages.add(packageName);
11936                    }
11937                }
11938
11939                if (changed && suspended) {
11940                    killApplication(packageName, UserHandle.getUid(userId, appId),
11941                            "suspending package");
11942                }
11943            }
11944        } finally {
11945            Binder.restoreCallingIdentity(callingId);
11946        }
11947
11948        if (!changedPackages.isEmpty()) {
11949            sendPackagesSuspendedForUser(changedPackages.toArray(
11950                    new String[changedPackages.size()]), userId, suspended);
11951        }
11952
11953        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11954    }
11955
11956    @Override
11957    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11958        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11959                true /* requireFullPermission */, false /* checkShell */,
11960                "isPackageSuspendedForUser for user " + userId);
11961        synchronized (mPackages) {
11962            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11963            if (pkgSetting == null) {
11964                throw new IllegalArgumentException("Unknown target package: " + packageName);
11965            }
11966            return pkgSetting.getSuspended(userId);
11967        }
11968    }
11969
11970    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11971        if (isPackageDeviceAdmin(packageName, userId)) {
11972            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11973                    + "\": has an active device admin");
11974            return false;
11975        }
11976
11977        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11978        if (packageName.equals(activeLauncherPackageName)) {
11979            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11980                    + "\": contains the active launcher");
11981            return false;
11982        }
11983
11984        if (packageName.equals(mRequiredInstallerPackage)) {
11985            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11986                    + "\": required for package installation");
11987            return false;
11988        }
11989
11990        if (packageName.equals(mRequiredUninstallerPackage)) {
11991            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11992                    + "\": required for package uninstallation");
11993            return false;
11994        }
11995
11996        if (packageName.equals(mRequiredVerifierPackage)) {
11997            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11998                    + "\": required for package verification");
11999            return false;
12000        }
12001
12002        if (packageName.equals(getDefaultDialerPackageName(userId))) {
12003            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12004                    + "\": is the default dialer");
12005            return false;
12006        }
12007
12008        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12009            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12010                    + "\": protected package");
12011            return false;
12012        }
12013
12014        return true;
12015    }
12016
12017    private String getActiveLauncherPackageName(int userId) {
12018        Intent intent = new Intent(Intent.ACTION_MAIN);
12019        intent.addCategory(Intent.CATEGORY_HOME);
12020        ResolveInfo resolveInfo = resolveIntent(
12021                intent,
12022                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12023                PackageManager.MATCH_DEFAULT_ONLY,
12024                userId);
12025
12026        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12027    }
12028
12029    private String getDefaultDialerPackageName(int userId) {
12030        synchronized (mPackages) {
12031            return mSettings.getDefaultDialerPackageNameLPw(userId);
12032        }
12033    }
12034
12035    @Override
12036    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12037        mContext.enforceCallingOrSelfPermission(
12038                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12039                "Only package verification agents can verify applications");
12040
12041        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12042        final PackageVerificationResponse response = new PackageVerificationResponse(
12043                verificationCode, Binder.getCallingUid());
12044        msg.arg1 = id;
12045        msg.obj = response;
12046        mHandler.sendMessage(msg);
12047    }
12048
12049    @Override
12050    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12051            long millisecondsToDelay) {
12052        mContext.enforceCallingOrSelfPermission(
12053                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12054                "Only package verification agents can extend verification timeouts");
12055
12056        final PackageVerificationState state = mPendingVerification.get(id);
12057        final PackageVerificationResponse response = new PackageVerificationResponse(
12058                verificationCodeAtTimeout, Binder.getCallingUid());
12059
12060        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12061            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12062        }
12063        if (millisecondsToDelay < 0) {
12064            millisecondsToDelay = 0;
12065        }
12066        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12067                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12068            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12069        }
12070
12071        if ((state != null) && !state.timeoutExtended()) {
12072            state.extendTimeout();
12073
12074            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12075            msg.arg1 = id;
12076            msg.obj = response;
12077            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12078        }
12079    }
12080
12081    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12082            int verificationCode, UserHandle user) {
12083        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12084        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12085        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12086        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12087        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12088
12089        mContext.sendBroadcastAsUser(intent, user,
12090                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12091    }
12092
12093    private ComponentName matchComponentForVerifier(String packageName,
12094            List<ResolveInfo> receivers) {
12095        ActivityInfo targetReceiver = null;
12096
12097        final int NR = receivers.size();
12098        for (int i = 0; i < NR; i++) {
12099            final ResolveInfo info = receivers.get(i);
12100            if (info.activityInfo == null) {
12101                continue;
12102            }
12103
12104            if (packageName.equals(info.activityInfo.packageName)) {
12105                targetReceiver = info.activityInfo;
12106                break;
12107            }
12108        }
12109
12110        if (targetReceiver == null) {
12111            return null;
12112        }
12113
12114        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12115    }
12116
12117    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12118            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12119        if (pkgInfo.verifiers.length == 0) {
12120            return null;
12121        }
12122
12123        final int N = pkgInfo.verifiers.length;
12124        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12125        for (int i = 0; i < N; i++) {
12126            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12127
12128            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12129                    receivers);
12130            if (comp == null) {
12131                continue;
12132            }
12133
12134            final int verifierUid = getUidForVerifier(verifierInfo);
12135            if (verifierUid == -1) {
12136                continue;
12137            }
12138
12139            if (DEBUG_VERIFY) {
12140                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12141                        + " with the correct signature");
12142            }
12143            sufficientVerifiers.add(comp);
12144            verificationState.addSufficientVerifier(verifierUid);
12145        }
12146
12147        return sufficientVerifiers;
12148    }
12149
12150    private int getUidForVerifier(VerifierInfo verifierInfo) {
12151        synchronized (mPackages) {
12152            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12153            if (pkg == null) {
12154                return -1;
12155            } else if (pkg.mSignatures.length != 1) {
12156                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12157                        + " has more than one signature; ignoring");
12158                return -1;
12159            }
12160
12161            /*
12162             * If the public key of the package's signature does not match
12163             * our expected public key, then this is a different package and
12164             * we should skip.
12165             */
12166
12167            final byte[] expectedPublicKey;
12168            try {
12169                final Signature verifierSig = pkg.mSignatures[0];
12170                final PublicKey publicKey = verifierSig.getPublicKey();
12171                expectedPublicKey = publicKey.getEncoded();
12172            } catch (CertificateException e) {
12173                return -1;
12174            }
12175
12176            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12177
12178            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12179                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12180                        + " does not have the expected public key; ignoring");
12181                return -1;
12182            }
12183
12184            return pkg.applicationInfo.uid;
12185        }
12186    }
12187
12188    @Override
12189    public void finishPackageInstall(int token, boolean didLaunch) {
12190        enforceSystemOrRoot("Only the system is allowed to finish installs");
12191
12192        if (DEBUG_INSTALL) {
12193            Slog.v(TAG, "BM finishing package install for " + token);
12194        }
12195        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12196
12197        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12198        mHandler.sendMessage(msg);
12199    }
12200
12201    /**
12202     * Get the verification agent timeout.
12203     *
12204     * @return verification timeout in milliseconds
12205     */
12206    private long getVerificationTimeout() {
12207        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12208                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12209                DEFAULT_VERIFICATION_TIMEOUT);
12210    }
12211
12212    /**
12213     * Get the default verification agent response code.
12214     *
12215     * @return default verification response code
12216     */
12217    private int getDefaultVerificationResponse() {
12218        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12219                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12220                DEFAULT_VERIFICATION_RESPONSE);
12221    }
12222
12223    /**
12224     * Check whether or not package verification has been enabled.
12225     *
12226     * @return true if verification should be performed
12227     */
12228    private boolean isVerificationEnabled(int userId, int installFlags) {
12229        if (!DEFAULT_VERIFY_ENABLE) {
12230            return false;
12231        }
12232        // Ephemeral apps don't get the full verification treatment
12233        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12234            if (DEBUG_EPHEMERAL) {
12235                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12236            }
12237            return false;
12238        }
12239
12240        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12241
12242        // Check if installing from ADB
12243        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12244            // Do not run verification in a test harness environment
12245            if (ActivityManager.isRunningInTestHarness()) {
12246                return false;
12247            }
12248            if (ensureVerifyAppsEnabled) {
12249                return true;
12250            }
12251            // Check if the developer does not want package verification for ADB installs
12252            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12253                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12254                return false;
12255            }
12256        }
12257
12258        if (ensureVerifyAppsEnabled) {
12259            return true;
12260        }
12261
12262        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12263                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12264    }
12265
12266    @Override
12267    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12268            throws RemoteException {
12269        mContext.enforceCallingOrSelfPermission(
12270                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12271                "Only intentfilter verification agents can verify applications");
12272
12273        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12274        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12275                Binder.getCallingUid(), verificationCode, failedDomains);
12276        msg.arg1 = id;
12277        msg.obj = response;
12278        mHandler.sendMessage(msg);
12279    }
12280
12281    @Override
12282    public int getIntentVerificationStatus(String packageName, int userId) {
12283        synchronized (mPackages) {
12284            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12285        }
12286    }
12287
12288    @Override
12289    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12290        mContext.enforceCallingOrSelfPermission(
12291                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12292
12293        boolean result = false;
12294        synchronized (mPackages) {
12295            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12296        }
12297        if (result) {
12298            scheduleWritePackageRestrictionsLocked(userId);
12299        }
12300        return result;
12301    }
12302
12303    @Override
12304    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12305            String packageName) {
12306        synchronized (mPackages) {
12307            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12308        }
12309    }
12310
12311    @Override
12312    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12313        if (TextUtils.isEmpty(packageName)) {
12314            return ParceledListSlice.emptyList();
12315        }
12316        synchronized (mPackages) {
12317            PackageParser.Package pkg = mPackages.get(packageName);
12318            if (pkg == null || pkg.activities == null) {
12319                return ParceledListSlice.emptyList();
12320            }
12321            final int count = pkg.activities.size();
12322            ArrayList<IntentFilter> result = new ArrayList<>();
12323            for (int n=0; n<count; n++) {
12324                PackageParser.Activity activity = pkg.activities.get(n);
12325                if (activity.intents != null && activity.intents.size() > 0) {
12326                    result.addAll(activity.intents);
12327                }
12328            }
12329            return new ParceledListSlice<>(result);
12330        }
12331    }
12332
12333    @Override
12334    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12335        mContext.enforceCallingOrSelfPermission(
12336                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12337
12338        synchronized (mPackages) {
12339            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12340            if (packageName != null) {
12341                result |= updateIntentVerificationStatus(packageName,
12342                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12343                        userId);
12344                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12345                        packageName, userId);
12346            }
12347            return result;
12348        }
12349    }
12350
12351    @Override
12352    public String getDefaultBrowserPackageName(int userId) {
12353        synchronized (mPackages) {
12354            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12355        }
12356    }
12357
12358    /**
12359     * Get the "allow unknown sources" setting.
12360     *
12361     * @return the current "allow unknown sources" setting
12362     */
12363    private int getUnknownSourcesSettings() {
12364        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12365                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12366                -1);
12367    }
12368
12369    @Override
12370    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12371        final int uid = Binder.getCallingUid();
12372        // writer
12373        synchronized (mPackages) {
12374            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12375            if (targetPackageSetting == null) {
12376                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12377            }
12378
12379            PackageSetting installerPackageSetting;
12380            if (installerPackageName != null) {
12381                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12382                if (installerPackageSetting == null) {
12383                    throw new IllegalArgumentException("Unknown installer package: "
12384                            + installerPackageName);
12385                }
12386            } else {
12387                installerPackageSetting = null;
12388            }
12389
12390            Signature[] callerSignature;
12391            Object obj = mSettings.getUserIdLPr(uid);
12392            if (obj != null) {
12393                if (obj instanceof SharedUserSetting) {
12394                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12395                } else if (obj instanceof PackageSetting) {
12396                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12397                } else {
12398                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12399                }
12400            } else {
12401                throw new SecurityException("Unknown calling UID: " + uid);
12402            }
12403
12404            // Verify: can't set installerPackageName to a package that is
12405            // not signed with the same cert as the caller.
12406            if (installerPackageSetting != null) {
12407                if (compareSignatures(callerSignature,
12408                        installerPackageSetting.signatures.mSignatures)
12409                        != PackageManager.SIGNATURE_MATCH) {
12410                    throw new SecurityException(
12411                            "Caller does not have same cert as new installer package "
12412                            + installerPackageName);
12413                }
12414            }
12415
12416            // Verify: if target already has an installer package, it must
12417            // be signed with the same cert as the caller.
12418            if (targetPackageSetting.installerPackageName != null) {
12419                PackageSetting setting = mSettings.mPackages.get(
12420                        targetPackageSetting.installerPackageName);
12421                // If the currently set package isn't valid, then it's always
12422                // okay to change it.
12423                if (setting != null) {
12424                    if (compareSignatures(callerSignature,
12425                            setting.signatures.mSignatures)
12426                            != PackageManager.SIGNATURE_MATCH) {
12427                        throw new SecurityException(
12428                                "Caller does not have same cert as old installer package "
12429                                + targetPackageSetting.installerPackageName);
12430                    }
12431                }
12432            }
12433
12434            // Okay!
12435            targetPackageSetting.installerPackageName = installerPackageName;
12436            if (installerPackageName != null) {
12437                mSettings.mInstallerPackages.add(installerPackageName);
12438            }
12439            scheduleWriteSettingsLocked();
12440        }
12441    }
12442
12443    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12444        // Queue up an async operation since the package installation may take a little while.
12445        mHandler.post(new Runnable() {
12446            public void run() {
12447                mHandler.removeCallbacks(this);
12448                 // Result object to be returned
12449                PackageInstalledInfo res = new PackageInstalledInfo();
12450                res.setReturnCode(currentStatus);
12451                res.uid = -1;
12452                res.pkg = null;
12453                res.removedInfo = null;
12454                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12455                    args.doPreInstall(res.returnCode);
12456                    synchronized (mInstallLock) {
12457                        installPackageTracedLI(args, res);
12458                    }
12459                    args.doPostInstall(res.returnCode, res.uid);
12460                }
12461
12462                // A restore should be performed at this point if (a) the install
12463                // succeeded, (b) the operation is not an update, and (c) the new
12464                // package has not opted out of backup participation.
12465                final boolean update = res.removedInfo != null
12466                        && res.removedInfo.removedPackage != null;
12467                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12468                boolean doRestore = !update
12469                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12470
12471                // Set up the post-install work request bookkeeping.  This will be used
12472                // and cleaned up by the post-install event handling regardless of whether
12473                // there's a restore pass performed.  Token values are >= 1.
12474                int token;
12475                if (mNextInstallToken < 0) mNextInstallToken = 1;
12476                token = mNextInstallToken++;
12477
12478                PostInstallData data = new PostInstallData(args, res);
12479                mRunningInstalls.put(token, data);
12480                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12481
12482                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12483                    // Pass responsibility to the Backup Manager.  It will perform a
12484                    // restore if appropriate, then pass responsibility back to the
12485                    // Package Manager to run the post-install observer callbacks
12486                    // and broadcasts.
12487                    IBackupManager bm = IBackupManager.Stub.asInterface(
12488                            ServiceManager.getService(Context.BACKUP_SERVICE));
12489                    if (bm != null) {
12490                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12491                                + " to BM for possible restore");
12492                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12493                        try {
12494                            // TODO: http://b/22388012
12495                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12496                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12497                            } else {
12498                                doRestore = false;
12499                            }
12500                        } catch (RemoteException e) {
12501                            // can't happen; the backup manager is local
12502                        } catch (Exception e) {
12503                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12504                            doRestore = false;
12505                        }
12506                    } else {
12507                        Slog.e(TAG, "Backup Manager not found!");
12508                        doRestore = false;
12509                    }
12510                }
12511
12512                if (!doRestore) {
12513                    // No restore possible, or the Backup Manager was mysteriously not
12514                    // available -- just fire the post-install work request directly.
12515                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12516
12517                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12518
12519                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12520                    mHandler.sendMessage(msg);
12521                }
12522            }
12523        });
12524    }
12525
12526    /**
12527     * Callback from PackageSettings whenever an app is first transitioned out of the
12528     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12529     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12530     * here whether the app is the target of an ongoing install, and only send the
12531     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12532     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12533     * handling.
12534     */
12535    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12536        // Serialize this with the rest of the install-process message chain.  In the
12537        // restore-at-install case, this Runnable will necessarily run before the
12538        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12539        // are coherent.  In the non-restore case, the app has already completed install
12540        // and been launched through some other means, so it is not in a problematic
12541        // state for observers to see the FIRST_LAUNCH signal.
12542        mHandler.post(new Runnable() {
12543            @Override
12544            public void run() {
12545                for (int i = 0; i < mRunningInstalls.size(); i++) {
12546                    final PostInstallData data = mRunningInstalls.valueAt(i);
12547                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12548                        continue;
12549                    }
12550                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12551                        // right package; but is it for the right user?
12552                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12553                            if (userId == data.res.newUsers[uIndex]) {
12554                                if (DEBUG_BACKUP) {
12555                                    Slog.i(TAG, "Package " + pkgName
12556                                            + " being restored so deferring FIRST_LAUNCH");
12557                                }
12558                                return;
12559                            }
12560                        }
12561                    }
12562                }
12563                // didn't find it, so not being restored
12564                if (DEBUG_BACKUP) {
12565                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12566                }
12567                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12568            }
12569        });
12570    }
12571
12572    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12573        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12574                installerPkg, null, userIds);
12575    }
12576
12577    private abstract class HandlerParams {
12578        private static final int MAX_RETRIES = 4;
12579
12580        /**
12581         * Number of times startCopy() has been attempted and had a non-fatal
12582         * error.
12583         */
12584        private int mRetries = 0;
12585
12586        /** User handle for the user requesting the information or installation. */
12587        private final UserHandle mUser;
12588        String traceMethod;
12589        int traceCookie;
12590
12591        HandlerParams(UserHandle user) {
12592            mUser = user;
12593        }
12594
12595        UserHandle getUser() {
12596            return mUser;
12597        }
12598
12599        HandlerParams setTraceMethod(String traceMethod) {
12600            this.traceMethod = traceMethod;
12601            return this;
12602        }
12603
12604        HandlerParams setTraceCookie(int traceCookie) {
12605            this.traceCookie = traceCookie;
12606            return this;
12607        }
12608
12609        final boolean startCopy() {
12610            boolean res;
12611            try {
12612                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12613
12614                if (++mRetries > MAX_RETRIES) {
12615                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12616                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12617                    handleServiceError();
12618                    return false;
12619                } else {
12620                    handleStartCopy();
12621                    res = true;
12622                }
12623            } catch (RemoteException e) {
12624                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12625                mHandler.sendEmptyMessage(MCS_RECONNECT);
12626                res = false;
12627            }
12628            handleReturnCode();
12629            return res;
12630        }
12631
12632        final void serviceError() {
12633            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12634            handleServiceError();
12635            handleReturnCode();
12636        }
12637
12638        abstract void handleStartCopy() throws RemoteException;
12639        abstract void handleServiceError();
12640        abstract void handleReturnCode();
12641    }
12642
12643    class MeasureParams extends HandlerParams {
12644        private final PackageStats mStats;
12645        private boolean mSuccess;
12646
12647        private final IPackageStatsObserver mObserver;
12648
12649        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12650            super(new UserHandle(stats.userHandle));
12651            mObserver = observer;
12652            mStats = stats;
12653        }
12654
12655        @Override
12656        public String toString() {
12657            return "MeasureParams{"
12658                + Integer.toHexString(System.identityHashCode(this))
12659                + " " + mStats.packageName + "}";
12660        }
12661
12662        @Override
12663        void handleStartCopy() throws RemoteException {
12664            synchronized (mInstallLock) {
12665                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12666            }
12667
12668            if (mSuccess) {
12669                boolean mounted = false;
12670                try {
12671                    final String status = Environment.getExternalStorageState();
12672                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12673                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12674                } catch (Exception e) {
12675                }
12676
12677                if (mounted) {
12678                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12679
12680                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12681                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12682
12683                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12684                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12685
12686                    // Always subtract cache size, since it's a subdirectory
12687                    mStats.externalDataSize -= mStats.externalCacheSize;
12688
12689                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12690                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12691
12692                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12693                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12694                }
12695            }
12696        }
12697
12698        @Override
12699        void handleReturnCode() {
12700            if (mObserver != null) {
12701                try {
12702                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12703                } catch (RemoteException e) {
12704                    Slog.i(TAG, "Observer no longer exists.");
12705                }
12706            }
12707        }
12708
12709        @Override
12710        void handleServiceError() {
12711            Slog.e(TAG, "Could not measure application " + mStats.packageName
12712                            + " external storage");
12713        }
12714    }
12715
12716    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12717            throws RemoteException {
12718        long result = 0;
12719        for (File path : paths) {
12720            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12721        }
12722        return result;
12723    }
12724
12725    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12726        for (File path : paths) {
12727            try {
12728                mcs.clearDirectory(path.getAbsolutePath());
12729            } catch (RemoteException e) {
12730            }
12731        }
12732    }
12733
12734    static class OriginInfo {
12735        /**
12736         * Location where install is coming from, before it has been
12737         * copied/renamed into place. This could be a single monolithic APK
12738         * file, or a cluster directory. This location may be untrusted.
12739         */
12740        final File file;
12741        final String cid;
12742
12743        /**
12744         * Flag indicating that {@link #file} or {@link #cid} has already been
12745         * staged, meaning downstream users don't need to defensively copy the
12746         * contents.
12747         */
12748        final boolean staged;
12749
12750        /**
12751         * Flag indicating that {@link #file} or {@link #cid} is an already
12752         * installed app that is being moved.
12753         */
12754        final boolean existing;
12755
12756        final String resolvedPath;
12757        final File resolvedFile;
12758
12759        static OriginInfo fromNothing() {
12760            return new OriginInfo(null, null, false, false);
12761        }
12762
12763        static OriginInfo fromUntrustedFile(File file) {
12764            return new OriginInfo(file, null, false, false);
12765        }
12766
12767        static OriginInfo fromExistingFile(File file) {
12768            return new OriginInfo(file, null, false, true);
12769        }
12770
12771        static OriginInfo fromStagedFile(File file) {
12772            return new OriginInfo(file, null, true, false);
12773        }
12774
12775        static OriginInfo fromStagedContainer(String cid) {
12776            return new OriginInfo(null, cid, true, false);
12777        }
12778
12779        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12780            this.file = file;
12781            this.cid = cid;
12782            this.staged = staged;
12783            this.existing = existing;
12784
12785            if (cid != null) {
12786                resolvedPath = PackageHelper.getSdDir(cid);
12787                resolvedFile = new File(resolvedPath);
12788            } else if (file != null) {
12789                resolvedPath = file.getAbsolutePath();
12790                resolvedFile = file;
12791            } else {
12792                resolvedPath = null;
12793                resolvedFile = null;
12794            }
12795        }
12796    }
12797
12798    static class MoveInfo {
12799        final int moveId;
12800        final String fromUuid;
12801        final String toUuid;
12802        final String packageName;
12803        final String dataAppName;
12804        final int appId;
12805        final String seinfo;
12806        final int targetSdkVersion;
12807
12808        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12809                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12810            this.moveId = moveId;
12811            this.fromUuid = fromUuid;
12812            this.toUuid = toUuid;
12813            this.packageName = packageName;
12814            this.dataAppName = dataAppName;
12815            this.appId = appId;
12816            this.seinfo = seinfo;
12817            this.targetSdkVersion = targetSdkVersion;
12818        }
12819    }
12820
12821    static class VerificationInfo {
12822        /** A constant used to indicate that a uid value is not present. */
12823        public static final int NO_UID = -1;
12824
12825        /** URI referencing where the package was downloaded from. */
12826        final Uri originatingUri;
12827
12828        /** HTTP referrer URI associated with the originatingURI. */
12829        final Uri referrer;
12830
12831        /** UID of the application that the install request originated from. */
12832        final int originatingUid;
12833
12834        /** UID of application requesting the install */
12835        final int installerUid;
12836
12837        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12838            this.originatingUri = originatingUri;
12839            this.referrer = referrer;
12840            this.originatingUid = originatingUid;
12841            this.installerUid = installerUid;
12842        }
12843    }
12844
12845    class InstallParams extends HandlerParams {
12846        final OriginInfo origin;
12847        final MoveInfo move;
12848        final IPackageInstallObserver2 observer;
12849        int installFlags;
12850        final String installerPackageName;
12851        final String volumeUuid;
12852        private InstallArgs mArgs;
12853        private int mRet;
12854        final String packageAbiOverride;
12855        final String[] grantedRuntimePermissions;
12856        final VerificationInfo verificationInfo;
12857        final Certificate[][] certificates;
12858
12859        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12860                int installFlags, String installerPackageName, String volumeUuid,
12861                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12862                String[] grantedPermissions, Certificate[][] certificates) {
12863            super(user);
12864            this.origin = origin;
12865            this.move = move;
12866            this.observer = observer;
12867            this.installFlags = installFlags;
12868            this.installerPackageName = installerPackageName;
12869            this.volumeUuid = volumeUuid;
12870            this.verificationInfo = verificationInfo;
12871            this.packageAbiOverride = packageAbiOverride;
12872            this.grantedRuntimePermissions = grantedPermissions;
12873            this.certificates = certificates;
12874        }
12875
12876        @Override
12877        public String toString() {
12878            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12879                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12880        }
12881
12882        private int installLocationPolicy(PackageInfoLite pkgLite) {
12883            String packageName = pkgLite.packageName;
12884            int installLocation = pkgLite.installLocation;
12885            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12886            // reader
12887            synchronized (mPackages) {
12888                // Currently installed package which the new package is attempting to replace or
12889                // null if no such package is installed.
12890                PackageParser.Package installedPkg = mPackages.get(packageName);
12891                // Package which currently owns the data which the new package will own if installed.
12892                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12893                // will be null whereas dataOwnerPkg will contain information about the package
12894                // which was uninstalled while keeping its data.
12895                PackageParser.Package dataOwnerPkg = installedPkg;
12896                if (dataOwnerPkg  == null) {
12897                    PackageSetting ps = mSettings.mPackages.get(packageName);
12898                    if (ps != null) {
12899                        dataOwnerPkg = ps.pkg;
12900                    }
12901                }
12902
12903                if (dataOwnerPkg != null) {
12904                    // If installed, the package will get access to data left on the device by its
12905                    // predecessor. As a security measure, this is permited only if this is not a
12906                    // version downgrade or if the predecessor package is marked as debuggable and
12907                    // a downgrade is explicitly requested.
12908                    //
12909                    // On debuggable platform builds, downgrades are permitted even for
12910                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12911                    // not offer security guarantees and thus it's OK to disable some security
12912                    // mechanisms to make debugging/testing easier on those builds. However, even on
12913                    // debuggable builds downgrades of packages are permitted only if requested via
12914                    // installFlags. This is because we aim to keep the behavior of debuggable
12915                    // platform builds as close as possible to the behavior of non-debuggable
12916                    // platform builds.
12917                    final boolean downgradeRequested =
12918                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12919                    final boolean packageDebuggable =
12920                                (dataOwnerPkg.applicationInfo.flags
12921                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12922                    final boolean downgradePermitted =
12923                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12924                    if (!downgradePermitted) {
12925                        try {
12926                            checkDowngrade(dataOwnerPkg, pkgLite);
12927                        } catch (PackageManagerException e) {
12928                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12929                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12930                        }
12931                    }
12932                }
12933
12934                if (installedPkg != null) {
12935                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12936                        // Check for updated system application.
12937                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12938                            if (onSd) {
12939                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12940                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12941                            }
12942                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12943                        } else {
12944                            if (onSd) {
12945                                // Install flag overrides everything.
12946                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12947                            }
12948                            // If current upgrade specifies particular preference
12949                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12950                                // Application explicitly specified internal.
12951                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12952                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12953                                // App explictly prefers external. Let policy decide
12954                            } else {
12955                                // Prefer previous location
12956                                if (isExternal(installedPkg)) {
12957                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12958                                }
12959                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12960                            }
12961                        }
12962                    } else {
12963                        // Invalid install. Return error code
12964                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12965                    }
12966                }
12967            }
12968            // All the special cases have been taken care of.
12969            // Return result based on recommended install location.
12970            if (onSd) {
12971                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12972            }
12973            return pkgLite.recommendedInstallLocation;
12974        }
12975
12976        /*
12977         * Invoke remote method to get package information and install
12978         * location values. Override install location based on default
12979         * policy if needed and then create install arguments based
12980         * on the install location.
12981         */
12982        public void handleStartCopy() throws RemoteException {
12983            int ret = PackageManager.INSTALL_SUCCEEDED;
12984
12985            // If we're already staged, we've firmly committed to an install location
12986            if (origin.staged) {
12987                if (origin.file != null) {
12988                    installFlags |= PackageManager.INSTALL_INTERNAL;
12989                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12990                } else if (origin.cid != null) {
12991                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12992                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12993                } else {
12994                    throw new IllegalStateException("Invalid stage location");
12995                }
12996            }
12997
12998            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12999            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
13000            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13001            PackageInfoLite pkgLite = null;
13002
13003            if (onInt && onSd) {
13004                // Check if both bits are set.
13005                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
13006                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13007            } else if (onSd && ephemeral) {
13008                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
13009                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13010            } else {
13011                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13012                        packageAbiOverride);
13013
13014                if (DEBUG_EPHEMERAL && ephemeral) {
13015                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
13016                }
13017
13018                /*
13019                 * If we have too little free space, try to free cache
13020                 * before giving up.
13021                 */
13022                if (!origin.staged && pkgLite.recommendedInstallLocation
13023                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13024                    // TODO: focus freeing disk space on the target device
13025                    final StorageManager storage = StorageManager.from(mContext);
13026                    final long lowThreshold = storage.getStorageLowBytes(
13027                            Environment.getDataDirectory());
13028
13029                    final long sizeBytes = mContainerService.calculateInstalledSize(
13030                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13031
13032                    try {
13033                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
13034                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13035                                installFlags, packageAbiOverride);
13036                    } catch (InstallerException e) {
13037                        Slog.w(TAG, "Failed to free cache", e);
13038                    }
13039
13040                    /*
13041                     * The cache free must have deleted the file we
13042                     * downloaded to install.
13043                     *
13044                     * TODO: fix the "freeCache" call to not delete
13045                     *       the file we care about.
13046                     */
13047                    if (pkgLite.recommendedInstallLocation
13048                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13049                        pkgLite.recommendedInstallLocation
13050                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13051                    }
13052                }
13053            }
13054
13055            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13056                int loc = pkgLite.recommendedInstallLocation;
13057                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13058                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13059                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13060                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13061                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13062                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13063                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13064                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13065                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13066                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13067                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13068                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13069                } else {
13070                    // Override with defaults if needed.
13071                    loc = installLocationPolicy(pkgLite);
13072                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13073                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13074                    } else if (!onSd && !onInt) {
13075                        // Override install location with flags
13076                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13077                            // Set the flag to install on external media.
13078                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13079                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13080                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13081                            if (DEBUG_EPHEMERAL) {
13082                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13083                            }
13084                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13085                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13086                                    |PackageManager.INSTALL_INTERNAL);
13087                        } else {
13088                            // Make sure the flag for installing on external
13089                            // media is unset
13090                            installFlags |= PackageManager.INSTALL_INTERNAL;
13091                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13092                        }
13093                    }
13094                }
13095            }
13096
13097            final InstallArgs args = createInstallArgs(this);
13098            mArgs = args;
13099
13100            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13101                // TODO: http://b/22976637
13102                // Apps installed for "all" users use the device owner to verify the app
13103                UserHandle verifierUser = getUser();
13104                if (verifierUser == UserHandle.ALL) {
13105                    verifierUser = UserHandle.SYSTEM;
13106                }
13107
13108                /*
13109                 * Determine if we have any installed package verifiers. If we
13110                 * do, then we'll defer to them to verify the packages.
13111                 */
13112                final int requiredUid = mRequiredVerifierPackage == null ? -1
13113                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13114                                verifierUser.getIdentifier());
13115                if (!origin.existing && requiredUid != -1
13116                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13117                    final Intent verification = new Intent(
13118                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13119                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13120                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13121                            PACKAGE_MIME_TYPE);
13122                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13123
13124                    // Query all live verifiers based on current user state
13125                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13126                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13127
13128                    if (DEBUG_VERIFY) {
13129                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13130                                + verification.toString() + " with " + pkgLite.verifiers.length
13131                                + " optional verifiers");
13132                    }
13133
13134                    final int verificationId = mPendingVerificationToken++;
13135
13136                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13137
13138                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13139                            installerPackageName);
13140
13141                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13142                            installFlags);
13143
13144                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13145                            pkgLite.packageName);
13146
13147                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13148                            pkgLite.versionCode);
13149
13150                    if (verificationInfo != null) {
13151                        if (verificationInfo.originatingUri != null) {
13152                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13153                                    verificationInfo.originatingUri);
13154                        }
13155                        if (verificationInfo.referrer != null) {
13156                            verification.putExtra(Intent.EXTRA_REFERRER,
13157                                    verificationInfo.referrer);
13158                        }
13159                        if (verificationInfo.originatingUid >= 0) {
13160                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13161                                    verificationInfo.originatingUid);
13162                        }
13163                        if (verificationInfo.installerUid >= 0) {
13164                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13165                                    verificationInfo.installerUid);
13166                        }
13167                    }
13168
13169                    final PackageVerificationState verificationState = new PackageVerificationState(
13170                            requiredUid, args);
13171
13172                    mPendingVerification.append(verificationId, verificationState);
13173
13174                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13175                            receivers, verificationState);
13176
13177                    /*
13178                     * If any sufficient verifiers were listed in the package
13179                     * manifest, attempt to ask them.
13180                     */
13181                    if (sufficientVerifiers != null) {
13182                        final int N = sufficientVerifiers.size();
13183                        if (N == 0) {
13184                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13185                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13186                        } else {
13187                            for (int i = 0; i < N; i++) {
13188                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13189
13190                                final Intent sufficientIntent = new Intent(verification);
13191                                sufficientIntent.setComponent(verifierComponent);
13192                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13193                            }
13194                        }
13195                    }
13196
13197                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13198                            mRequiredVerifierPackage, receivers);
13199                    if (ret == PackageManager.INSTALL_SUCCEEDED
13200                            && mRequiredVerifierPackage != null) {
13201                        Trace.asyncTraceBegin(
13202                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13203                        /*
13204                         * Send the intent to the required verification agent,
13205                         * but only start the verification timeout after the
13206                         * target BroadcastReceivers have run.
13207                         */
13208                        verification.setComponent(requiredVerifierComponent);
13209                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13210                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13211                                new BroadcastReceiver() {
13212                                    @Override
13213                                    public void onReceive(Context context, Intent intent) {
13214                                        final Message msg = mHandler
13215                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13216                                        msg.arg1 = verificationId;
13217                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13218                                    }
13219                                }, null, 0, null, null);
13220
13221                        /*
13222                         * We don't want the copy to proceed until verification
13223                         * succeeds, so null out this field.
13224                         */
13225                        mArgs = null;
13226                    }
13227                } else {
13228                    /*
13229                     * No package verification is enabled, so immediately start
13230                     * the remote call to initiate copy using temporary file.
13231                     */
13232                    ret = args.copyApk(mContainerService, true);
13233                }
13234            }
13235
13236            mRet = ret;
13237        }
13238
13239        @Override
13240        void handleReturnCode() {
13241            // If mArgs is null, then MCS couldn't be reached. When it
13242            // reconnects, it will try again to install. At that point, this
13243            // will succeed.
13244            if (mArgs != null) {
13245                processPendingInstall(mArgs, mRet);
13246            }
13247        }
13248
13249        @Override
13250        void handleServiceError() {
13251            mArgs = createInstallArgs(this);
13252            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13253        }
13254
13255        public boolean isForwardLocked() {
13256            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13257        }
13258    }
13259
13260    /**
13261     * Used during creation of InstallArgs
13262     *
13263     * @param installFlags package installation flags
13264     * @return true if should be installed on external storage
13265     */
13266    private static boolean installOnExternalAsec(int installFlags) {
13267        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13268            return false;
13269        }
13270        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13271            return true;
13272        }
13273        return false;
13274    }
13275
13276    /**
13277     * Used during creation of InstallArgs
13278     *
13279     * @param installFlags package installation flags
13280     * @return true if should be installed as forward locked
13281     */
13282    private static boolean installForwardLocked(int installFlags) {
13283        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13284    }
13285
13286    private InstallArgs createInstallArgs(InstallParams params) {
13287        if (params.move != null) {
13288            return new MoveInstallArgs(params);
13289        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13290            return new AsecInstallArgs(params);
13291        } else {
13292            return new FileInstallArgs(params);
13293        }
13294    }
13295
13296    /**
13297     * Create args that describe an existing installed package. Typically used
13298     * when cleaning up old installs, or used as a move source.
13299     */
13300    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13301            String resourcePath, String[] instructionSets) {
13302        final boolean isInAsec;
13303        if (installOnExternalAsec(installFlags)) {
13304            /* Apps on SD card are always in ASEC containers. */
13305            isInAsec = true;
13306        } else if (installForwardLocked(installFlags)
13307                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13308            /*
13309             * Forward-locked apps are only in ASEC containers if they're the
13310             * new style
13311             */
13312            isInAsec = true;
13313        } else {
13314            isInAsec = false;
13315        }
13316
13317        if (isInAsec) {
13318            return new AsecInstallArgs(codePath, instructionSets,
13319                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13320        } else {
13321            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13322        }
13323    }
13324
13325    static abstract class InstallArgs {
13326        /** @see InstallParams#origin */
13327        final OriginInfo origin;
13328        /** @see InstallParams#move */
13329        final MoveInfo move;
13330
13331        final IPackageInstallObserver2 observer;
13332        // Always refers to PackageManager flags only
13333        final int installFlags;
13334        final String installerPackageName;
13335        final String volumeUuid;
13336        final UserHandle user;
13337        final String abiOverride;
13338        final String[] installGrantPermissions;
13339        /** If non-null, drop an async trace when the install completes */
13340        final String traceMethod;
13341        final int traceCookie;
13342        final Certificate[][] certificates;
13343
13344        // The list of instruction sets supported by this app. This is currently
13345        // only used during the rmdex() phase to clean up resources. We can get rid of this
13346        // if we move dex files under the common app path.
13347        /* nullable */ String[] instructionSets;
13348
13349        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13350                int installFlags, String installerPackageName, String volumeUuid,
13351                UserHandle user, String[] instructionSets,
13352                String abiOverride, String[] installGrantPermissions,
13353                String traceMethod, int traceCookie, Certificate[][] certificates) {
13354            this.origin = origin;
13355            this.move = move;
13356            this.installFlags = installFlags;
13357            this.observer = observer;
13358            this.installerPackageName = installerPackageName;
13359            this.volumeUuid = volumeUuid;
13360            this.user = user;
13361            this.instructionSets = instructionSets;
13362            this.abiOverride = abiOverride;
13363            this.installGrantPermissions = installGrantPermissions;
13364            this.traceMethod = traceMethod;
13365            this.traceCookie = traceCookie;
13366            this.certificates = certificates;
13367        }
13368
13369        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13370        abstract int doPreInstall(int status);
13371
13372        /**
13373         * Rename package into final resting place. All paths on the given
13374         * scanned package should be updated to reflect the rename.
13375         */
13376        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13377        abstract int doPostInstall(int status, int uid);
13378
13379        /** @see PackageSettingBase#codePathString */
13380        abstract String getCodePath();
13381        /** @see PackageSettingBase#resourcePathString */
13382        abstract String getResourcePath();
13383
13384        // Need installer lock especially for dex file removal.
13385        abstract void cleanUpResourcesLI();
13386        abstract boolean doPostDeleteLI(boolean delete);
13387
13388        /**
13389         * Called before the source arguments are copied. This is used mostly
13390         * for MoveParams when it needs to read the source file to put it in the
13391         * destination.
13392         */
13393        int doPreCopy() {
13394            return PackageManager.INSTALL_SUCCEEDED;
13395        }
13396
13397        /**
13398         * Called after the source arguments are copied. This is used mostly for
13399         * MoveParams when it needs to read the source file to put it in the
13400         * destination.
13401         */
13402        int doPostCopy(int uid) {
13403            return PackageManager.INSTALL_SUCCEEDED;
13404        }
13405
13406        protected boolean isFwdLocked() {
13407            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13408        }
13409
13410        protected boolean isExternalAsec() {
13411            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13412        }
13413
13414        protected boolean isEphemeral() {
13415            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13416        }
13417
13418        UserHandle getUser() {
13419            return user;
13420        }
13421    }
13422
13423    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13424        if (!allCodePaths.isEmpty()) {
13425            if (instructionSets == null) {
13426                throw new IllegalStateException("instructionSet == null");
13427            }
13428            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13429            for (String codePath : allCodePaths) {
13430                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13431                    try {
13432                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13433                    } catch (InstallerException ignored) {
13434                    }
13435                }
13436            }
13437        }
13438    }
13439
13440    /**
13441     * Logic to handle installation of non-ASEC applications, including copying
13442     * and renaming logic.
13443     */
13444    class FileInstallArgs extends InstallArgs {
13445        private File codeFile;
13446        private File resourceFile;
13447
13448        // Example topology:
13449        // /data/app/com.example/base.apk
13450        // /data/app/com.example/split_foo.apk
13451        // /data/app/com.example/lib/arm/libfoo.so
13452        // /data/app/com.example/lib/arm64/libfoo.so
13453        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13454
13455        /** New install */
13456        FileInstallArgs(InstallParams params) {
13457            super(params.origin, params.move, params.observer, params.installFlags,
13458                    params.installerPackageName, params.volumeUuid,
13459                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13460                    params.grantedRuntimePermissions,
13461                    params.traceMethod, params.traceCookie, params.certificates);
13462            if (isFwdLocked()) {
13463                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13464            }
13465        }
13466
13467        /** Existing install */
13468        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13469            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13470                    null, null, null, 0, null /*certificates*/);
13471            this.codeFile = (codePath != null) ? new File(codePath) : null;
13472            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13473        }
13474
13475        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13476            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13477            try {
13478                return doCopyApk(imcs, temp);
13479            } finally {
13480                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13481            }
13482        }
13483
13484        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13485            if (origin.staged) {
13486                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13487                codeFile = origin.file;
13488                resourceFile = origin.file;
13489                return PackageManager.INSTALL_SUCCEEDED;
13490            }
13491
13492            try {
13493                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13494                final File tempDir =
13495                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13496                codeFile = tempDir;
13497                resourceFile = tempDir;
13498            } catch (IOException e) {
13499                Slog.w(TAG, "Failed to create copy file: " + e);
13500                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13501            }
13502
13503            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13504                @Override
13505                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13506                    if (!FileUtils.isValidExtFilename(name)) {
13507                        throw new IllegalArgumentException("Invalid filename: " + name);
13508                    }
13509                    try {
13510                        final File file = new File(codeFile, name);
13511                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13512                                O_RDWR | O_CREAT, 0644);
13513                        Os.chmod(file.getAbsolutePath(), 0644);
13514                        return new ParcelFileDescriptor(fd);
13515                    } catch (ErrnoException e) {
13516                        throw new RemoteException("Failed to open: " + e.getMessage());
13517                    }
13518                }
13519            };
13520
13521            int ret = PackageManager.INSTALL_SUCCEEDED;
13522            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13523            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13524                Slog.e(TAG, "Failed to copy package");
13525                return ret;
13526            }
13527
13528            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13529            NativeLibraryHelper.Handle handle = null;
13530            try {
13531                handle = NativeLibraryHelper.Handle.create(codeFile);
13532                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13533                        abiOverride);
13534            } catch (IOException e) {
13535                Slog.e(TAG, "Copying native libraries failed", e);
13536                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13537            } finally {
13538                IoUtils.closeQuietly(handle);
13539            }
13540
13541            return ret;
13542        }
13543
13544        int doPreInstall(int status) {
13545            if (status != PackageManager.INSTALL_SUCCEEDED) {
13546                cleanUp();
13547            }
13548            return status;
13549        }
13550
13551        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13552            if (status != PackageManager.INSTALL_SUCCEEDED) {
13553                cleanUp();
13554                return false;
13555            }
13556
13557            final File targetDir = codeFile.getParentFile();
13558            final File beforeCodeFile = codeFile;
13559            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13560
13561            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13562            try {
13563                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13564            } catch (ErrnoException e) {
13565                Slog.w(TAG, "Failed to rename", e);
13566                return false;
13567            }
13568
13569            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13570                Slog.w(TAG, "Failed to restorecon");
13571                return false;
13572            }
13573
13574            // Reflect the rename internally
13575            codeFile = afterCodeFile;
13576            resourceFile = afterCodeFile;
13577
13578            // Reflect the rename in scanned details
13579            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13580            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13581                    afterCodeFile, pkg.baseCodePath));
13582            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13583                    afterCodeFile, pkg.splitCodePaths));
13584
13585            // Reflect the rename in app info
13586            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13587            pkg.setApplicationInfoCodePath(pkg.codePath);
13588            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13589            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13590            pkg.setApplicationInfoResourcePath(pkg.codePath);
13591            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13592            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13593
13594            return true;
13595        }
13596
13597        int doPostInstall(int status, int uid) {
13598            if (status != PackageManager.INSTALL_SUCCEEDED) {
13599                cleanUp();
13600            }
13601            return status;
13602        }
13603
13604        @Override
13605        String getCodePath() {
13606            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13607        }
13608
13609        @Override
13610        String getResourcePath() {
13611            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13612        }
13613
13614        private boolean cleanUp() {
13615            if (codeFile == null || !codeFile.exists()) {
13616                return false;
13617            }
13618
13619            removeCodePathLI(codeFile);
13620
13621            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13622                resourceFile.delete();
13623            }
13624
13625            return true;
13626        }
13627
13628        void cleanUpResourcesLI() {
13629            // Try enumerating all code paths before deleting
13630            List<String> allCodePaths = Collections.EMPTY_LIST;
13631            if (codeFile != null && codeFile.exists()) {
13632                try {
13633                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13634                    allCodePaths = pkg.getAllCodePaths();
13635                } catch (PackageParserException e) {
13636                    // Ignored; we tried our best
13637                }
13638            }
13639
13640            cleanUp();
13641            removeDexFiles(allCodePaths, instructionSets);
13642        }
13643
13644        boolean doPostDeleteLI(boolean delete) {
13645            // XXX err, shouldn't we respect the delete flag?
13646            cleanUpResourcesLI();
13647            return true;
13648        }
13649    }
13650
13651    private boolean isAsecExternal(String cid) {
13652        final String asecPath = PackageHelper.getSdFilesystem(cid);
13653        return !asecPath.startsWith(mAsecInternalPath);
13654    }
13655
13656    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13657            PackageManagerException {
13658        if (copyRet < 0) {
13659            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13660                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13661                throw new PackageManagerException(copyRet, message);
13662            }
13663        }
13664    }
13665
13666    /**
13667     * Extract the MountService "container ID" from the full code path of an
13668     * .apk.
13669     */
13670    static String cidFromCodePath(String fullCodePath) {
13671        int eidx = fullCodePath.lastIndexOf("/");
13672        String subStr1 = fullCodePath.substring(0, eidx);
13673        int sidx = subStr1.lastIndexOf("/");
13674        return subStr1.substring(sidx+1, eidx);
13675    }
13676
13677    /**
13678     * Logic to handle installation of ASEC applications, including copying and
13679     * renaming logic.
13680     */
13681    class AsecInstallArgs extends InstallArgs {
13682        static final String RES_FILE_NAME = "pkg.apk";
13683        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13684
13685        String cid;
13686        String packagePath;
13687        String resourcePath;
13688
13689        /** New install */
13690        AsecInstallArgs(InstallParams params) {
13691            super(params.origin, params.move, params.observer, params.installFlags,
13692                    params.installerPackageName, params.volumeUuid,
13693                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13694                    params.grantedRuntimePermissions,
13695                    params.traceMethod, params.traceCookie, params.certificates);
13696        }
13697
13698        /** Existing install */
13699        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13700                        boolean isExternal, boolean isForwardLocked) {
13701            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13702              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13703                    instructionSets, null, null, null, 0, null /*certificates*/);
13704            // Hackily pretend we're still looking at a full code path
13705            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13706                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13707            }
13708
13709            // Extract cid from fullCodePath
13710            int eidx = fullCodePath.lastIndexOf("/");
13711            String subStr1 = fullCodePath.substring(0, eidx);
13712            int sidx = subStr1.lastIndexOf("/");
13713            cid = subStr1.substring(sidx+1, eidx);
13714            setMountPath(subStr1);
13715        }
13716
13717        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13718            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13719              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13720                    instructionSets, null, null, null, 0, null /*certificates*/);
13721            this.cid = cid;
13722            setMountPath(PackageHelper.getSdDir(cid));
13723        }
13724
13725        void createCopyFile() {
13726            cid = mInstallerService.allocateExternalStageCidLegacy();
13727        }
13728
13729        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13730            if (origin.staged && origin.cid != null) {
13731                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13732                cid = origin.cid;
13733                setMountPath(PackageHelper.getSdDir(cid));
13734                return PackageManager.INSTALL_SUCCEEDED;
13735            }
13736
13737            if (temp) {
13738                createCopyFile();
13739            } else {
13740                /*
13741                 * Pre-emptively destroy the container since it's destroyed if
13742                 * copying fails due to it existing anyway.
13743                 */
13744                PackageHelper.destroySdDir(cid);
13745            }
13746
13747            final String newMountPath = imcs.copyPackageToContainer(
13748                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13749                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13750
13751            if (newMountPath != null) {
13752                setMountPath(newMountPath);
13753                return PackageManager.INSTALL_SUCCEEDED;
13754            } else {
13755                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13756            }
13757        }
13758
13759        @Override
13760        String getCodePath() {
13761            return packagePath;
13762        }
13763
13764        @Override
13765        String getResourcePath() {
13766            return resourcePath;
13767        }
13768
13769        int doPreInstall(int status) {
13770            if (status != PackageManager.INSTALL_SUCCEEDED) {
13771                // Destroy container
13772                PackageHelper.destroySdDir(cid);
13773            } else {
13774                boolean mounted = PackageHelper.isContainerMounted(cid);
13775                if (!mounted) {
13776                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13777                            Process.SYSTEM_UID);
13778                    if (newMountPath != null) {
13779                        setMountPath(newMountPath);
13780                    } else {
13781                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13782                    }
13783                }
13784            }
13785            return status;
13786        }
13787
13788        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13789            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13790            String newMountPath = null;
13791            if (PackageHelper.isContainerMounted(cid)) {
13792                // Unmount the container
13793                if (!PackageHelper.unMountSdDir(cid)) {
13794                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13795                    return false;
13796                }
13797            }
13798            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13799                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13800                        " which might be stale. Will try to clean up.");
13801                // Clean up the stale container and proceed to recreate.
13802                if (!PackageHelper.destroySdDir(newCacheId)) {
13803                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13804                    return false;
13805                }
13806                // Successfully cleaned up stale container. Try to rename again.
13807                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13808                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13809                            + " inspite of cleaning it up.");
13810                    return false;
13811                }
13812            }
13813            if (!PackageHelper.isContainerMounted(newCacheId)) {
13814                Slog.w(TAG, "Mounting container " + newCacheId);
13815                newMountPath = PackageHelper.mountSdDir(newCacheId,
13816                        getEncryptKey(), Process.SYSTEM_UID);
13817            } else {
13818                newMountPath = PackageHelper.getSdDir(newCacheId);
13819            }
13820            if (newMountPath == null) {
13821                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13822                return false;
13823            }
13824            Log.i(TAG, "Succesfully renamed " + cid +
13825                    " to " + newCacheId +
13826                    " at new path: " + newMountPath);
13827            cid = newCacheId;
13828
13829            final File beforeCodeFile = new File(packagePath);
13830            setMountPath(newMountPath);
13831            final File afterCodeFile = new File(packagePath);
13832
13833            // Reflect the rename in scanned details
13834            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13835            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13836                    afterCodeFile, pkg.baseCodePath));
13837            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13838                    afterCodeFile, pkg.splitCodePaths));
13839
13840            // Reflect the rename in app info
13841            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13842            pkg.setApplicationInfoCodePath(pkg.codePath);
13843            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13844            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13845            pkg.setApplicationInfoResourcePath(pkg.codePath);
13846            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13847            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13848
13849            return true;
13850        }
13851
13852        private void setMountPath(String mountPath) {
13853            final File mountFile = new File(mountPath);
13854
13855            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13856            if (monolithicFile.exists()) {
13857                packagePath = monolithicFile.getAbsolutePath();
13858                if (isFwdLocked()) {
13859                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13860                } else {
13861                    resourcePath = packagePath;
13862                }
13863            } else {
13864                packagePath = mountFile.getAbsolutePath();
13865                resourcePath = packagePath;
13866            }
13867        }
13868
13869        int doPostInstall(int status, int uid) {
13870            if (status != PackageManager.INSTALL_SUCCEEDED) {
13871                cleanUp();
13872            } else {
13873                final int groupOwner;
13874                final String protectedFile;
13875                if (isFwdLocked()) {
13876                    groupOwner = UserHandle.getSharedAppGid(uid);
13877                    protectedFile = RES_FILE_NAME;
13878                } else {
13879                    groupOwner = -1;
13880                    protectedFile = null;
13881                }
13882
13883                if (uid < Process.FIRST_APPLICATION_UID
13884                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13885                    Slog.e(TAG, "Failed to finalize " + cid);
13886                    PackageHelper.destroySdDir(cid);
13887                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13888                }
13889
13890                boolean mounted = PackageHelper.isContainerMounted(cid);
13891                if (!mounted) {
13892                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13893                }
13894            }
13895            return status;
13896        }
13897
13898        private void cleanUp() {
13899            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13900
13901            // Destroy secure container
13902            PackageHelper.destroySdDir(cid);
13903        }
13904
13905        private List<String> getAllCodePaths() {
13906            final File codeFile = new File(getCodePath());
13907            if (codeFile != null && codeFile.exists()) {
13908                try {
13909                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13910                    return pkg.getAllCodePaths();
13911                } catch (PackageParserException e) {
13912                    // Ignored; we tried our best
13913                }
13914            }
13915            return Collections.EMPTY_LIST;
13916        }
13917
13918        void cleanUpResourcesLI() {
13919            // Enumerate all code paths before deleting
13920            cleanUpResourcesLI(getAllCodePaths());
13921        }
13922
13923        private void cleanUpResourcesLI(List<String> allCodePaths) {
13924            cleanUp();
13925            removeDexFiles(allCodePaths, instructionSets);
13926        }
13927
13928        String getPackageName() {
13929            return getAsecPackageName(cid);
13930        }
13931
13932        boolean doPostDeleteLI(boolean delete) {
13933            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13934            final List<String> allCodePaths = getAllCodePaths();
13935            boolean mounted = PackageHelper.isContainerMounted(cid);
13936            if (mounted) {
13937                // Unmount first
13938                if (PackageHelper.unMountSdDir(cid)) {
13939                    mounted = false;
13940                }
13941            }
13942            if (!mounted && delete) {
13943                cleanUpResourcesLI(allCodePaths);
13944            }
13945            return !mounted;
13946        }
13947
13948        @Override
13949        int doPreCopy() {
13950            if (isFwdLocked()) {
13951                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13952                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13953                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13954                }
13955            }
13956
13957            return PackageManager.INSTALL_SUCCEEDED;
13958        }
13959
13960        @Override
13961        int doPostCopy(int uid) {
13962            if (isFwdLocked()) {
13963                if (uid < Process.FIRST_APPLICATION_UID
13964                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13965                                RES_FILE_NAME)) {
13966                    Slog.e(TAG, "Failed to finalize " + cid);
13967                    PackageHelper.destroySdDir(cid);
13968                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13969                }
13970            }
13971
13972            return PackageManager.INSTALL_SUCCEEDED;
13973        }
13974    }
13975
13976    /**
13977     * Logic to handle movement of existing installed applications.
13978     */
13979    class MoveInstallArgs extends InstallArgs {
13980        private File codeFile;
13981        private File resourceFile;
13982
13983        /** New install */
13984        MoveInstallArgs(InstallParams params) {
13985            super(params.origin, params.move, params.observer, params.installFlags,
13986                    params.installerPackageName, params.volumeUuid,
13987                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13988                    params.grantedRuntimePermissions,
13989                    params.traceMethod, params.traceCookie, params.certificates);
13990        }
13991
13992        int copyApk(IMediaContainerService imcs, boolean temp) {
13993            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13994                    + move.fromUuid + " to " + move.toUuid);
13995            synchronized (mInstaller) {
13996                try {
13997                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13998                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13999                } catch (InstallerException e) {
14000                    Slog.w(TAG, "Failed to move app", e);
14001                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14002                }
14003            }
14004
14005            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
14006            resourceFile = codeFile;
14007            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14008
14009            return PackageManager.INSTALL_SUCCEEDED;
14010        }
14011
14012        int doPreInstall(int status) {
14013            if (status != PackageManager.INSTALL_SUCCEEDED) {
14014                cleanUp(move.toUuid);
14015            }
14016            return status;
14017        }
14018
14019        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14020            if (status != PackageManager.INSTALL_SUCCEEDED) {
14021                cleanUp(move.toUuid);
14022                return false;
14023            }
14024
14025            // Reflect the move in app info
14026            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14027            pkg.setApplicationInfoCodePath(pkg.codePath);
14028            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14029            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14030            pkg.setApplicationInfoResourcePath(pkg.codePath);
14031            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14032            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14033
14034            return true;
14035        }
14036
14037        int doPostInstall(int status, int uid) {
14038            if (status == PackageManager.INSTALL_SUCCEEDED) {
14039                cleanUp(move.fromUuid);
14040            } else {
14041                cleanUp(move.toUuid);
14042            }
14043            return status;
14044        }
14045
14046        @Override
14047        String getCodePath() {
14048            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14049        }
14050
14051        @Override
14052        String getResourcePath() {
14053            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14054        }
14055
14056        private boolean cleanUp(String volumeUuid) {
14057            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14058                    move.dataAppName);
14059            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14060            final int[] userIds = sUserManager.getUserIds();
14061            synchronized (mInstallLock) {
14062                // Clean up both app data and code
14063                // All package moves are frozen until finished
14064                for (int userId : userIds) {
14065                    try {
14066                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14067                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14068                    } catch (InstallerException e) {
14069                        Slog.w(TAG, String.valueOf(e));
14070                    }
14071                }
14072                removeCodePathLI(codeFile);
14073            }
14074            return true;
14075        }
14076
14077        void cleanUpResourcesLI() {
14078            throw new UnsupportedOperationException();
14079        }
14080
14081        boolean doPostDeleteLI(boolean delete) {
14082            throw new UnsupportedOperationException();
14083        }
14084    }
14085
14086    static String getAsecPackageName(String packageCid) {
14087        int idx = packageCid.lastIndexOf("-");
14088        if (idx == -1) {
14089            return packageCid;
14090        }
14091        return packageCid.substring(0, idx);
14092    }
14093
14094    // Utility method used to create code paths based on package name and available index.
14095    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14096        String idxStr = "";
14097        int idx = 1;
14098        // Fall back to default value of idx=1 if prefix is not
14099        // part of oldCodePath
14100        if (oldCodePath != null) {
14101            String subStr = oldCodePath;
14102            // Drop the suffix right away
14103            if (suffix != null && subStr.endsWith(suffix)) {
14104                subStr = subStr.substring(0, subStr.length() - suffix.length());
14105            }
14106            // If oldCodePath already contains prefix find out the
14107            // ending index to either increment or decrement.
14108            int sidx = subStr.lastIndexOf(prefix);
14109            if (sidx != -1) {
14110                subStr = subStr.substring(sidx + prefix.length());
14111                if (subStr != null) {
14112                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14113                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14114                    }
14115                    try {
14116                        idx = Integer.parseInt(subStr);
14117                        if (idx <= 1) {
14118                            idx++;
14119                        } else {
14120                            idx--;
14121                        }
14122                    } catch(NumberFormatException e) {
14123                    }
14124                }
14125            }
14126        }
14127        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14128        return prefix + idxStr;
14129    }
14130
14131    private File getNextCodePath(File targetDir, String packageName) {
14132        int suffix = 1;
14133        File result;
14134        do {
14135            result = new File(targetDir, packageName + "-" + suffix);
14136            suffix++;
14137        } while (result.exists());
14138        return result;
14139    }
14140
14141    // Utility method that returns the relative package path with respect
14142    // to the installation directory. Like say for /data/data/com.test-1.apk
14143    // string com.test-1 is returned.
14144    static String deriveCodePathName(String codePath) {
14145        if (codePath == null) {
14146            return null;
14147        }
14148        final File codeFile = new File(codePath);
14149        final String name = codeFile.getName();
14150        if (codeFile.isDirectory()) {
14151            return name;
14152        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14153            final int lastDot = name.lastIndexOf('.');
14154            return name.substring(0, lastDot);
14155        } else {
14156            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14157            return null;
14158        }
14159    }
14160
14161    static class PackageInstalledInfo {
14162        String name;
14163        int uid;
14164        // The set of users that originally had this package installed.
14165        int[] origUsers;
14166        // The set of users that now have this package installed.
14167        int[] newUsers;
14168        PackageParser.Package pkg;
14169        int returnCode;
14170        String returnMsg;
14171        PackageRemovedInfo removedInfo;
14172        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14173
14174        public void setError(int code, String msg) {
14175            setReturnCode(code);
14176            setReturnMessage(msg);
14177            Slog.w(TAG, msg);
14178        }
14179
14180        public void setError(String msg, PackageParserException e) {
14181            setReturnCode(e.error);
14182            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14183            Slog.w(TAG, msg, e);
14184        }
14185
14186        public void setError(String msg, PackageManagerException e) {
14187            returnCode = e.error;
14188            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14189            Slog.w(TAG, msg, e);
14190        }
14191
14192        public void setReturnCode(int returnCode) {
14193            this.returnCode = returnCode;
14194            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14195            for (int i = 0; i < childCount; i++) {
14196                addedChildPackages.valueAt(i).returnCode = returnCode;
14197            }
14198        }
14199
14200        private void setReturnMessage(String returnMsg) {
14201            this.returnMsg = returnMsg;
14202            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14203            for (int i = 0; i < childCount; i++) {
14204                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14205            }
14206        }
14207
14208        // In some error cases we want to convey more info back to the observer
14209        String origPackage;
14210        String origPermission;
14211    }
14212
14213    /*
14214     * Install a non-existing package.
14215     */
14216    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14217            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14218            PackageInstalledInfo res) {
14219        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14220
14221        // Remember this for later, in case we need to rollback this install
14222        String pkgName = pkg.packageName;
14223
14224        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14225
14226        synchronized(mPackages) {
14227            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14228                // A package with the same name is already installed, though
14229                // it has been renamed to an older name.  The package we
14230                // are trying to install should be installed as an update to
14231                // the existing one, but that has not been requested, so bail.
14232                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14233                        + " without first uninstalling package running as "
14234                        + mSettings.mRenamedPackages.get(pkgName));
14235                return;
14236            }
14237            if (mPackages.containsKey(pkgName)) {
14238                // Don't allow installation over an existing package with the same name.
14239                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14240                        + " without first uninstalling.");
14241                return;
14242            }
14243        }
14244
14245        try {
14246            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14247                    System.currentTimeMillis(), user);
14248
14249            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14250
14251            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14252                prepareAppDataAfterInstallLIF(newPackage);
14253
14254            } else {
14255                // Remove package from internal structures, but keep around any
14256                // data that might have already existed
14257                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14258                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14259            }
14260        } catch (PackageManagerException e) {
14261            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14262        }
14263
14264        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14265    }
14266
14267    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14268        // Can't rotate keys during boot or if sharedUser.
14269        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14270                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14271            return false;
14272        }
14273        // app is using upgradeKeySets; make sure all are valid
14274        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14275        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14276        for (int i = 0; i < upgradeKeySets.length; i++) {
14277            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14278                Slog.wtf(TAG, "Package "
14279                         + (oldPs.name != null ? oldPs.name : "<null>")
14280                         + " contains upgrade-key-set reference to unknown key-set: "
14281                         + upgradeKeySets[i]
14282                         + " reverting to signatures check.");
14283                return false;
14284            }
14285        }
14286        return true;
14287    }
14288
14289    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14290        // Upgrade keysets are being used.  Determine if new package has a superset of the
14291        // required keys.
14292        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14293        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14294        for (int i = 0; i < upgradeKeySets.length; i++) {
14295            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14296            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14297                return true;
14298            }
14299        }
14300        return false;
14301    }
14302
14303    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14304        try (DigestInputStream digestStream =
14305                new DigestInputStream(new FileInputStream(file), digest)) {
14306            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14307        }
14308    }
14309
14310    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14311            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14312        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14313
14314        final PackageParser.Package oldPackage;
14315        final String pkgName = pkg.packageName;
14316        final int[] allUsers;
14317        final int[] installedUsers;
14318
14319        synchronized(mPackages) {
14320            oldPackage = mPackages.get(pkgName);
14321            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14322
14323            // don't allow upgrade to target a release SDK from a pre-release SDK
14324            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14325                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14326            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14327                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14328            if (oldTargetsPreRelease
14329                    && !newTargetsPreRelease
14330                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14331                Slog.w(TAG, "Can't install package targeting released sdk");
14332                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14333                return;
14334            }
14335
14336            // don't allow an upgrade from full to ephemeral
14337            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14338            if (isEphemeral && !oldIsEphemeral) {
14339                // can't downgrade from full to ephemeral
14340                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14341                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14342                return;
14343            }
14344
14345            // verify signatures are valid
14346            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14347            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14348                if (!checkUpgradeKeySetLP(ps, pkg)) {
14349                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14350                            "New package not signed by keys specified by upgrade-keysets: "
14351                                    + pkgName);
14352                    return;
14353                }
14354            } else {
14355                // default to original signature matching
14356                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14357                        != PackageManager.SIGNATURE_MATCH) {
14358                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14359                            "New package has a different signature: " + pkgName);
14360                    return;
14361                }
14362            }
14363
14364            // don't allow a system upgrade unless the upgrade hash matches
14365            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14366                byte[] digestBytes = null;
14367                try {
14368                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14369                    updateDigest(digest, new File(pkg.baseCodePath));
14370                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14371                        for (String path : pkg.splitCodePaths) {
14372                            updateDigest(digest, new File(path));
14373                        }
14374                    }
14375                    digestBytes = digest.digest();
14376                } catch (NoSuchAlgorithmException | IOException e) {
14377                    res.setError(INSTALL_FAILED_INVALID_APK,
14378                            "Could not compute hash: " + pkgName);
14379                    return;
14380                }
14381                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14382                    res.setError(INSTALL_FAILED_INVALID_APK,
14383                            "New package fails restrict-update check: " + pkgName);
14384                    return;
14385                }
14386                // retain upgrade restriction
14387                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14388            }
14389
14390            // Check for shared user id changes
14391            String invalidPackageName =
14392                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14393            if (invalidPackageName != null) {
14394                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14395                        "Package " + invalidPackageName + " tried to change user "
14396                                + oldPackage.mSharedUserId);
14397                return;
14398            }
14399
14400            // In case of rollback, remember per-user/profile install state
14401            allUsers = sUserManager.getUserIds();
14402            installedUsers = ps.queryInstalledUsers(allUsers, true);
14403        }
14404
14405        // Update what is removed
14406        res.removedInfo = new PackageRemovedInfo();
14407        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14408        res.removedInfo.removedPackage = oldPackage.packageName;
14409        res.removedInfo.isUpdate = true;
14410        res.removedInfo.origUsers = installedUsers;
14411        final int childCount = (oldPackage.childPackages != null)
14412                ? oldPackage.childPackages.size() : 0;
14413        for (int i = 0; i < childCount; i++) {
14414            boolean childPackageUpdated = false;
14415            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14416            if (res.addedChildPackages != null) {
14417                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14418                if (childRes != null) {
14419                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14420                    childRes.removedInfo.removedPackage = childPkg.packageName;
14421                    childRes.removedInfo.isUpdate = true;
14422                    childPackageUpdated = true;
14423                }
14424            }
14425            if (!childPackageUpdated) {
14426                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14427                childRemovedRes.removedPackage = childPkg.packageName;
14428                childRemovedRes.isUpdate = false;
14429                childRemovedRes.dataRemoved = true;
14430                synchronized (mPackages) {
14431                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14432                    if (childPs != null) {
14433                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14434                    }
14435                }
14436                if (res.removedInfo.removedChildPackages == null) {
14437                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14438                }
14439                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14440            }
14441        }
14442
14443        boolean sysPkg = (isSystemApp(oldPackage));
14444        if (sysPkg) {
14445            // Set the system/privileged flags as needed
14446            final boolean privileged =
14447                    (oldPackage.applicationInfo.privateFlags
14448                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14449            final int systemPolicyFlags = policyFlags
14450                    | PackageParser.PARSE_IS_SYSTEM
14451                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14452
14453            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14454                    user, allUsers, installerPackageName, res);
14455        } else {
14456            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14457                    user, allUsers, installerPackageName, res);
14458        }
14459    }
14460
14461    public List<String> getPreviousCodePaths(String packageName) {
14462        final PackageSetting ps = mSettings.mPackages.get(packageName);
14463        final List<String> result = new ArrayList<String>();
14464        if (ps != null && ps.oldCodePaths != null) {
14465            result.addAll(ps.oldCodePaths);
14466        }
14467        return result;
14468    }
14469
14470    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14471            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14472            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14473        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14474                + deletedPackage);
14475
14476        String pkgName = deletedPackage.packageName;
14477        boolean deletedPkg = true;
14478        boolean addedPkg = false;
14479        boolean updatedSettings = false;
14480        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14481        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14482                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14483
14484        final long origUpdateTime = (pkg.mExtras != null)
14485                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14486
14487        // First delete the existing package while retaining the data directory
14488        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14489                res.removedInfo, true, pkg)) {
14490            // If the existing package wasn't successfully deleted
14491            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14492            deletedPkg = false;
14493        } else {
14494            // Successfully deleted the old package; proceed with replace.
14495
14496            // If deleted package lived in a container, give users a chance to
14497            // relinquish resources before killing.
14498            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14499                if (DEBUG_INSTALL) {
14500                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14501                }
14502                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14503                final ArrayList<String> pkgList = new ArrayList<String>(1);
14504                pkgList.add(deletedPackage.applicationInfo.packageName);
14505                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14506            }
14507
14508            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14509                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14510            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14511
14512            try {
14513                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14514                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14515                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14516
14517                // Update the in-memory copy of the previous code paths.
14518                PackageSetting ps = mSettings.mPackages.get(pkgName);
14519                if (!killApp) {
14520                    if (ps.oldCodePaths == null) {
14521                        ps.oldCodePaths = new ArraySet<>();
14522                    }
14523                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14524                    if (deletedPackage.splitCodePaths != null) {
14525                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14526                    }
14527                } else {
14528                    ps.oldCodePaths = null;
14529                }
14530                if (ps.childPackageNames != null) {
14531                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14532                        final String childPkgName = ps.childPackageNames.get(i);
14533                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14534                        childPs.oldCodePaths = ps.oldCodePaths;
14535                    }
14536                }
14537                prepareAppDataAfterInstallLIF(newPackage);
14538                addedPkg = true;
14539            } catch (PackageManagerException e) {
14540                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14541            }
14542        }
14543
14544        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14545            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14546
14547            // Revert all internal state mutations and added folders for the failed install
14548            if (addedPkg) {
14549                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14550                        res.removedInfo, true, null);
14551            }
14552
14553            // Restore the old package
14554            if (deletedPkg) {
14555                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14556                File restoreFile = new File(deletedPackage.codePath);
14557                // Parse old package
14558                boolean oldExternal = isExternal(deletedPackage);
14559                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14560                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14561                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14562                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14563                try {
14564                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14565                            null);
14566                } catch (PackageManagerException e) {
14567                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14568                            + e.getMessage());
14569                    return;
14570                }
14571
14572                synchronized (mPackages) {
14573                    // Ensure the installer package name up to date
14574                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14575
14576                    // Update permissions for restored package
14577                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14578
14579                    mSettings.writeLPr();
14580                }
14581
14582                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14583            }
14584        } else {
14585            synchronized (mPackages) {
14586                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14587                if (ps != null) {
14588                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14589                    if (res.removedInfo.removedChildPackages != null) {
14590                        final int childCount = res.removedInfo.removedChildPackages.size();
14591                        // Iterate in reverse as we may modify the collection
14592                        for (int i = childCount - 1; i >= 0; i--) {
14593                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14594                            if (res.addedChildPackages.containsKey(childPackageName)) {
14595                                res.removedInfo.removedChildPackages.removeAt(i);
14596                            } else {
14597                                PackageRemovedInfo childInfo = res.removedInfo
14598                                        .removedChildPackages.valueAt(i);
14599                                childInfo.removedForAllUsers = mPackages.get(
14600                                        childInfo.removedPackage) == null;
14601                            }
14602                        }
14603                    }
14604                }
14605            }
14606        }
14607    }
14608
14609    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14610            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14611            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14612        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14613                + ", old=" + deletedPackage);
14614
14615        final boolean disabledSystem;
14616
14617        // Remove existing system package
14618        removePackageLI(deletedPackage, true);
14619
14620        synchronized (mPackages) {
14621            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14622        }
14623        if (!disabledSystem) {
14624            // We didn't need to disable the .apk as a current system package,
14625            // which means we are replacing another update that is already
14626            // installed.  We need to make sure to delete the older one's .apk.
14627            res.removedInfo.args = createInstallArgsForExisting(0,
14628                    deletedPackage.applicationInfo.getCodePath(),
14629                    deletedPackage.applicationInfo.getResourcePath(),
14630                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14631        } else {
14632            res.removedInfo.args = null;
14633        }
14634
14635        // Successfully disabled the old package. Now proceed with re-installation
14636        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14637                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14638        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14639
14640        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14641        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14642                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14643
14644        PackageParser.Package newPackage = null;
14645        try {
14646            // Add the package to the internal data structures
14647            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14648
14649            // Set the update and install times
14650            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14651            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14652                    System.currentTimeMillis());
14653
14654            // Update the package dynamic state if succeeded
14655            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14656                // Now that the install succeeded make sure we remove data
14657                // directories for any child package the update removed.
14658                final int deletedChildCount = (deletedPackage.childPackages != null)
14659                        ? deletedPackage.childPackages.size() : 0;
14660                final int newChildCount = (newPackage.childPackages != null)
14661                        ? newPackage.childPackages.size() : 0;
14662                for (int i = 0; i < deletedChildCount; i++) {
14663                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14664                    boolean childPackageDeleted = true;
14665                    for (int j = 0; j < newChildCount; j++) {
14666                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14667                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14668                            childPackageDeleted = false;
14669                            break;
14670                        }
14671                    }
14672                    if (childPackageDeleted) {
14673                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14674                                deletedChildPkg.packageName);
14675                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14676                            PackageRemovedInfo removedChildRes = res.removedInfo
14677                                    .removedChildPackages.get(deletedChildPkg.packageName);
14678                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14679                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14680                        }
14681                    }
14682                }
14683
14684                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14685                prepareAppDataAfterInstallLIF(newPackage);
14686            }
14687        } catch (PackageManagerException e) {
14688            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14689            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14690        }
14691
14692        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14693            // Re installation failed. Restore old information
14694            // Remove new pkg information
14695            if (newPackage != null) {
14696                removeInstalledPackageLI(newPackage, true);
14697            }
14698            // Add back the old system package
14699            try {
14700                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14701            } catch (PackageManagerException e) {
14702                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14703            }
14704
14705            synchronized (mPackages) {
14706                if (disabledSystem) {
14707                    enableSystemPackageLPw(deletedPackage);
14708                }
14709
14710                // Ensure the installer package name up to date
14711                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14712
14713                // Update permissions for restored package
14714                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14715
14716                mSettings.writeLPr();
14717            }
14718
14719            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14720                    + " after failed upgrade");
14721        }
14722    }
14723
14724    /**
14725     * Checks whether the parent or any of the child packages have a change shared
14726     * user. For a package to be a valid update the shred users of the parent and
14727     * the children should match. We may later support changing child shared users.
14728     * @param oldPkg The updated package.
14729     * @param newPkg The update package.
14730     * @return The shared user that change between the versions.
14731     */
14732    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14733            PackageParser.Package newPkg) {
14734        // Check parent shared user
14735        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14736            return newPkg.packageName;
14737        }
14738        // Check child shared users
14739        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14740        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14741        for (int i = 0; i < newChildCount; i++) {
14742            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14743            // If this child was present, did it have the same shared user?
14744            for (int j = 0; j < oldChildCount; j++) {
14745                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14746                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14747                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14748                    return newChildPkg.packageName;
14749                }
14750            }
14751        }
14752        return null;
14753    }
14754
14755    private void removeNativeBinariesLI(PackageSetting ps) {
14756        // Remove the lib path for the parent package
14757        if (ps != null) {
14758            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14759            // Remove the lib path for the child packages
14760            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14761            for (int i = 0; i < childCount; i++) {
14762                PackageSetting childPs = null;
14763                synchronized (mPackages) {
14764                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14765                }
14766                if (childPs != null) {
14767                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14768                            .legacyNativeLibraryPathString);
14769                }
14770            }
14771        }
14772    }
14773
14774    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14775        // Enable the parent package
14776        mSettings.enableSystemPackageLPw(pkg.packageName);
14777        // Enable the child packages
14778        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14779        for (int i = 0; i < childCount; i++) {
14780            PackageParser.Package childPkg = pkg.childPackages.get(i);
14781            mSettings.enableSystemPackageLPw(childPkg.packageName);
14782        }
14783    }
14784
14785    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14786            PackageParser.Package newPkg) {
14787        // Disable the parent package (parent always replaced)
14788        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14789        // Disable the child packages
14790        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14791        for (int i = 0; i < childCount; i++) {
14792            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14793            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14794            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14795        }
14796        return disabled;
14797    }
14798
14799    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14800            String installerPackageName) {
14801        // Enable the parent package
14802        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14803        // Enable the child packages
14804        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14805        for (int i = 0; i < childCount; i++) {
14806            PackageParser.Package childPkg = pkg.childPackages.get(i);
14807            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14808        }
14809    }
14810
14811    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14812        // Collect all used permissions in the UID
14813        ArraySet<String> usedPermissions = new ArraySet<>();
14814        final int packageCount = su.packages.size();
14815        for (int i = 0; i < packageCount; i++) {
14816            PackageSetting ps = su.packages.valueAt(i);
14817            if (ps.pkg == null) {
14818                continue;
14819            }
14820            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14821            for (int j = 0; j < requestedPermCount; j++) {
14822                String permission = ps.pkg.requestedPermissions.get(j);
14823                BasePermission bp = mSettings.mPermissions.get(permission);
14824                if (bp != null) {
14825                    usedPermissions.add(permission);
14826                }
14827            }
14828        }
14829
14830        PermissionsState permissionsState = su.getPermissionsState();
14831        // Prune install permissions
14832        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14833        final int installPermCount = installPermStates.size();
14834        for (int i = installPermCount - 1; i >= 0;  i--) {
14835            PermissionState permissionState = installPermStates.get(i);
14836            if (!usedPermissions.contains(permissionState.getName())) {
14837                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14838                if (bp != null) {
14839                    permissionsState.revokeInstallPermission(bp);
14840                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14841                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14842                }
14843            }
14844        }
14845
14846        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14847
14848        // Prune runtime permissions
14849        for (int userId : allUserIds) {
14850            List<PermissionState> runtimePermStates = permissionsState
14851                    .getRuntimePermissionStates(userId);
14852            final int runtimePermCount = runtimePermStates.size();
14853            for (int i = runtimePermCount - 1; i >= 0; i--) {
14854                PermissionState permissionState = runtimePermStates.get(i);
14855                if (!usedPermissions.contains(permissionState.getName())) {
14856                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14857                    if (bp != null) {
14858                        permissionsState.revokeRuntimePermission(bp, userId);
14859                        permissionsState.updatePermissionFlags(bp, userId,
14860                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14861                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14862                                runtimePermissionChangedUserIds, userId);
14863                    }
14864                }
14865            }
14866        }
14867
14868        return runtimePermissionChangedUserIds;
14869    }
14870
14871    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14872            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14873        // Update the parent package setting
14874        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14875                res, user);
14876        // Update the child packages setting
14877        final int childCount = (newPackage.childPackages != null)
14878                ? newPackage.childPackages.size() : 0;
14879        for (int i = 0; i < childCount; i++) {
14880            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14881            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14882            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14883                    childRes.origUsers, childRes, user);
14884        }
14885    }
14886
14887    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14888            String installerPackageName, int[] allUsers, int[] installedForUsers,
14889            PackageInstalledInfo res, UserHandle user) {
14890        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14891
14892        String pkgName = newPackage.packageName;
14893        synchronized (mPackages) {
14894            //write settings. the installStatus will be incomplete at this stage.
14895            //note that the new package setting would have already been
14896            //added to mPackages. It hasn't been persisted yet.
14897            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14898            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14899            mSettings.writeLPr();
14900            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14901        }
14902
14903        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14904        synchronized (mPackages) {
14905            updatePermissionsLPw(newPackage.packageName, newPackage,
14906                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14907                            ? UPDATE_PERMISSIONS_ALL : 0));
14908            // For system-bundled packages, we assume that installing an upgraded version
14909            // of the package implies that the user actually wants to run that new code,
14910            // so we enable the package.
14911            PackageSetting ps = mSettings.mPackages.get(pkgName);
14912            final int userId = user.getIdentifier();
14913            if (ps != null) {
14914                if (isSystemApp(newPackage)) {
14915                    if (DEBUG_INSTALL) {
14916                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14917                    }
14918                    // Enable system package for requested users
14919                    if (res.origUsers != null) {
14920                        for (int origUserId : res.origUsers) {
14921                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14922                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14923                                        origUserId, installerPackageName);
14924                            }
14925                        }
14926                    }
14927                    // Also convey the prior install/uninstall state
14928                    if (allUsers != null && installedForUsers != null) {
14929                        for (int currentUserId : allUsers) {
14930                            final boolean installed = ArrayUtils.contains(
14931                                    installedForUsers, currentUserId);
14932                            if (DEBUG_INSTALL) {
14933                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14934                            }
14935                            ps.setInstalled(installed, currentUserId);
14936                        }
14937                        // these install state changes will be persisted in the
14938                        // upcoming call to mSettings.writeLPr().
14939                    }
14940                }
14941                // It's implied that when a user requests installation, they want the app to be
14942                // installed and enabled.
14943                if (userId != UserHandle.USER_ALL) {
14944                    ps.setInstalled(true, userId);
14945                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14946                }
14947            }
14948            res.name = pkgName;
14949            res.uid = newPackage.applicationInfo.uid;
14950            res.pkg = newPackage;
14951            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14952            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14953            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14954            //to update install status
14955            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14956            mSettings.writeLPr();
14957            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14958        }
14959
14960        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14961    }
14962
14963    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14964        try {
14965            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14966            installPackageLI(args, res);
14967        } finally {
14968            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14969        }
14970    }
14971
14972    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14973        final int installFlags = args.installFlags;
14974        final String installerPackageName = args.installerPackageName;
14975        final String volumeUuid = args.volumeUuid;
14976        final File tmpPackageFile = new File(args.getCodePath());
14977        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14978        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14979                || (args.volumeUuid != null));
14980        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14981        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14982        boolean replace = false;
14983        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14984        if (args.move != null) {
14985            // moving a complete application; perform an initial scan on the new install location
14986            scanFlags |= SCAN_INITIAL;
14987        }
14988        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14989            scanFlags |= SCAN_DONT_KILL_APP;
14990        }
14991
14992        // Result object to be returned
14993        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14994
14995        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14996
14997        // Sanity check
14998        if (ephemeral && (forwardLocked || onExternal)) {
14999            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
15000                    + " external=" + onExternal);
15001            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15002            return;
15003        }
15004
15005        // Retrieve PackageSettings and parse package
15006        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15007                | PackageParser.PARSE_ENFORCE_CODE
15008                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15009                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15010                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15011                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15012        PackageParser pp = new PackageParser();
15013        pp.setSeparateProcesses(mSeparateProcesses);
15014        pp.setDisplayMetrics(mMetrics);
15015
15016        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15017        final PackageParser.Package pkg;
15018        try {
15019            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15020        } catch (PackageParserException e) {
15021            res.setError("Failed parse during installPackageLI", e);
15022            return;
15023        } finally {
15024            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15025        }
15026
15027        // If we are installing a clustered package add results for the children
15028        if (pkg.childPackages != null) {
15029            synchronized (mPackages) {
15030                final int childCount = pkg.childPackages.size();
15031                for (int i = 0; i < childCount; i++) {
15032                    PackageParser.Package childPkg = pkg.childPackages.get(i);
15033                    PackageInstalledInfo childRes = new PackageInstalledInfo();
15034                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15035                    childRes.pkg = childPkg;
15036                    childRes.name = childPkg.packageName;
15037                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15038                    if (childPs != null) {
15039                        childRes.origUsers = childPs.queryInstalledUsers(
15040                                sUserManager.getUserIds(), true);
15041                    }
15042                    if ((mPackages.containsKey(childPkg.packageName))) {
15043                        childRes.removedInfo = new PackageRemovedInfo();
15044                        childRes.removedInfo.removedPackage = childPkg.packageName;
15045                    }
15046                    if (res.addedChildPackages == null) {
15047                        res.addedChildPackages = new ArrayMap<>();
15048                    }
15049                    res.addedChildPackages.put(childPkg.packageName, childRes);
15050                }
15051            }
15052        }
15053
15054        // If package doesn't declare API override, mark that we have an install
15055        // time CPU ABI override.
15056        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15057            pkg.cpuAbiOverride = args.abiOverride;
15058        }
15059
15060        String pkgName = res.name = pkg.packageName;
15061        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15062            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15063                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15064                return;
15065            }
15066        }
15067
15068        try {
15069            // either use what we've been given or parse directly from the APK
15070            if (args.certificates != null) {
15071                try {
15072                    PackageParser.populateCertificates(pkg, args.certificates);
15073                } catch (PackageParserException e) {
15074                    // there was something wrong with the certificates we were given;
15075                    // try to pull them from the APK
15076                    PackageParser.collectCertificates(pkg, parseFlags);
15077                }
15078            } else {
15079                PackageParser.collectCertificates(pkg, parseFlags);
15080            }
15081        } catch (PackageParserException e) {
15082            res.setError("Failed collect during installPackageLI", e);
15083            return;
15084        }
15085
15086        // Get rid of all references to package scan path via parser.
15087        pp = null;
15088        String oldCodePath = null;
15089        boolean systemApp = false;
15090        synchronized (mPackages) {
15091            // Check if installing already existing package
15092            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15093                String oldName = mSettings.mRenamedPackages.get(pkgName);
15094                if (pkg.mOriginalPackages != null
15095                        && pkg.mOriginalPackages.contains(oldName)
15096                        && mPackages.containsKey(oldName)) {
15097                    // This package is derived from an original package,
15098                    // and this device has been updating from that original
15099                    // name.  We must continue using the original name, so
15100                    // rename the new package here.
15101                    pkg.setPackageName(oldName);
15102                    pkgName = pkg.packageName;
15103                    replace = true;
15104                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15105                            + oldName + " pkgName=" + pkgName);
15106                } else if (mPackages.containsKey(pkgName)) {
15107                    // This package, under its official name, already exists
15108                    // on the device; we should replace it.
15109                    replace = true;
15110                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15111                }
15112
15113                // Child packages are installed through the parent package
15114                if (pkg.parentPackage != null) {
15115                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15116                            "Package " + pkg.packageName + " is child of package "
15117                                    + pkg.parentPackage.parentPackage + ". Child packages "
15118                                    + "can be updated only through the parent package.");
15119                    return;
15120                }
15121
15122                if (replace) {
15123                    // Prevent apps opting out from runtime permissions
15124                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15125                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15126                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15127                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15128                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15129                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15130                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15131                                        + " doesn't support runtime permissions but the old"
15132                                        + " target SDK " + oldTargetSdk + " does.");
15133                        return;
15134                    }
15135
15136                    // Prevent installing of child packages
15137                    if (oldPackage.parentPackage != null) {
15138                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15139                                "Package " + pkg.packageName + " is child of package "
15140                                        + oldPackage.parentPackage + ". Child packages "
15141                                        + "can be updated only through the parent package.");
15142                        return;
15143                    }
15144                }
15145            }
15146
15147            PackageSetting ps = mSettings.mPackages.get(pkgName);
15148            if (ps != null) {
15149                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15150
15151                // Quick sanity check that we're signed correctly if updating;
15152                // we'll check this again later when scanning, but we want to
15153                // bail early here before tripping over redefined permissions.
15154                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15155                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15156                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15157                                + pkg.packageName + " upgrade keys do not match the "
15158                                + "previously installed version");
15159                        return;
15160                    }
15161                } else {
15162                    try {
15163                        verifySignaturesLP(ps, pkg);
15164                    } catch (PackageManagerException e) {
15165                        res.setError(e.error, e.getMessage());
15166                        return;
15167                    }
15168                }
15169
15170                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15171                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15172                    systemApp = (ps.pkg.applicationInfo.flags &
15173                            ApplicationInfo.FLAG_SYSTEM) != 0;
15174                }
15175                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15176            }
15177
15178            // Check whether the newly-scanned package wants to define an already-defined perm
15179            int N = pkg.permissions.size();
15180            for (int i = N-1; i >= 0; i--) {
15181                PackageParser.Permission perm = pkg.permissions.get(i);
15182                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15183                if (bp != null) {
15184                    // If the defining package is signed with our cert, it's okay.  This
15185                    // also includes the "updating the same package" case, of course.
15186                    // "updating same package" could also involve key-rotation.
15187                    final boolean sigsOk;
15188                    if (bp.sourcePackage.equals(pkg.packageName)
15189                            && (bp.packageSetting instanceof PackageSetting)
15190                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15191                                    scanFlags))) {
15192                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15193                    } else {
15194                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15195                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15196                    }
15197                    if (!sigsOk) {
15198                        // If the owning package is the system itself, we log but allow
15199                        // install to proceed; we fail the install on all other permission
15200                        // redefinitions.
15201                        if (!bp.sourcePackage.equals("android")) {
15202                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15203                                    + pkg.packageName + " attempting to redeclare permission "
15204                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15205                            res.origPermission = perm.info.name;
15206                            res.origPackage = bp.sourcePackage;
15207                            return;
15208                        } else {
15209                            Slog.w(TAG, "Package " + pkg.packageName
15210                                    + " attempting to redeclare system permission "
15211                                    + perm.info.name + "; ignoring new declaration");
15212                            pkg.permissions.remove(i);
15213                        }
15214                    }
15215                }
15216            }
15217        }
15218
15219        if (systemApp) {
15220            if (onExternal) {
15221                // Abort update; system app can't be replaced with app on sdcard
15222                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15223                        "Cannot install updates to system apps on sdcard");
15224                return;
15225            } else if (ephemeral) {
15226                // Abort update; system app can't be replaced with an ephemeral app
15227                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15228                        "Cannot update a system app with an ephemeral app");
15229                return;
15230            }
15231        }
15232
15233        if (args.move != null) {
15234            // We did an in-place move, so dex is ready to roll
15235            scanFlags |= SCAN_NO_DEX;
15236            scanFlags |= SCAN_MOVE;
15237
15238            synchronized (mPackages) {
15239                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15240                if (ps == null) {
15241                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15242                            "Missing settings for moved package " + pkgName);
15243                }
15244
15245                // We moved the entire application as-is, so bring over the
15246                // previously derived ABI information.
15247                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15248                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15249            }
15250
15251        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15252            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15253            scanFlags |= SCAN_NO_DEX;
15254
15255            try {
15256                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15257                    args.abiOverride : pkg.cpuAbiOverride);
15258                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15259                        true /* extract libs */);
15260            } catch (PackageManagerException pme) {
15261                Slog.e(TAG, "Error deriving application ABI", pme);
15262                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15263                return;
15264            }
15265
15266            // Shared libraries for the package need to be updated.
15267            synchronized (mPackages) {
15268                try {
15269                    updateSharedLibrariesLPw(pkg, null);
15270                } catch (PackageManagerException e) {
15271                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15272                }
15273            }
15274            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15275            // Do not run PackageDexOptimizer through the local performDexOpt
15276            // method because `pkg` may not be in `mPackages` yet.
15277            //
15278            // Also, don't fail application installs if the dexopt step fails.
15279            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15280                    null /* instructionSets */, false /* checkProfiles */,
15281                    getCompilerFilterForReason(REASON_INSTALL),
15282                    getOrCreateCompilerPackageStats(pkg));
15283            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15284
15285            // Notify BackgroundDexOptService that the package has been changed.
15286            // If this is an update of a package which used to fail to compile,
15287            // BDOS will remove it from its blacklist.
15288            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15289        }
15290
15291        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15292            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15293            return;
15294        }
15295
15296        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15297
15298        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15299                "installPackageLI")) {
15300            if (replace) {
15301                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15302                        installerPackageName, res);
15303            } else {
15304                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15305                        args.user, installerPackageName, volumeUuid, res);
15306            }
15307        }
15308        synchronized (mPackages) {
15309            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15310            if (ps != null) {
15311                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15312            }
15313
15314            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15315            for (int i = 0; i < childCount; i++) {
15316                PackageParser.Package childPkg = pkg.childPackages.get(i);
15317                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15318                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15319                if (childPs != null) {
15320                    childRes.newUsers = childPs.queryInstalledUsers(
15321                            sUserManager.getUserIds(), true);
15322                }
15323            }
15324        }
15325    }
15326
15327    private void startIntentFilterVerifications(int userId, boolean replacing,
15328            PackageParser.Package pkg) {
15329        if (mIntentFilterVerifierComponent == null) {
15330            Slog.w(TAG, "No IntentFilter verification will not be done as "
15331                    + "there is no IntentFilterVerifier available!");
15332            return;
15333        }
15334
15335        final int verifierUid = getPackageUid(
15336                mIntentFilterVerifierComponent.getPackageName(),
15337                MATCH_DEBUG_TRIAGED_MISSING,
15338                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15339
15340        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15341        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15342        mHandler.sendMessage(msg);
15343
15344        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15345        for (int i = 0; i < childCount; i++) {
15346            PackageParser.Package childPkg = pkg.childPackages.get(i);
15347            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15348            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15349            mHandler.sendMessage(msg);
15350        }
15351    }
15352
15353    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15354            PackageParser.Package pkg) {
15355        int size = pkg.activities.size();
15356        if (size == 0) {
15357            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15358                    "No activity, so no need to verify any IntentFilter!");
15359            return;
15360        }
15361
15362        final boolean hasDomainURLs = hasDomainURLs(pkg);
15363        if (!hasDomainURLs) {
15364            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15365                    "No domain URLs, so no need to verify any IntentFilter!");
15366            return;
15367        }
15368
15369        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15370                + " if any IntentFilter from the " + size
15371                + " Activities needs verification ...");
15372
15373        int count = 0;
15374        final String packageName = pkg.packageName;
15375
15376        synchronized (mPackages) {
15377            // If this is a new install and we see that we've already run verification for this
15378            // package, we have nothing to do: it means the state was restored from backup.
15379            if (!replacing) {
15380                IntentFilterVerificationInfo ivi =
15381                        mSettings.getIntentFilterVerificationLPr(packageName);
15382                if (ivi != null) {
15383                    if (DEBUG_DOMAIN_VERIFICATION) {
15384                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15385                                + ivi.getStatusString());
15386                    }
15387                    return;
15388                }
15389            }
15390
15391            // If any filters need to be verified, then all need to be.
15392            boolean needToVerify = false;
15393            for (PackageParser.Activity a : pkg.activities) {
15394                for (ActivityIntentInfo filter : a.intents) {
15395                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15396                        if (DEBUG_DOMAIN_VERIFICATION) {
15397                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15398                        }
15399                        needToVerify = true;
15400                        break;
15401                    }
15402                }
15403            }
15404
15405            if (needToVerify) {
15406                final int verificationId = mIntentFilterVerificationToken++;
15407                for (PackageParser.Activity a : pkg.activities) {
15408                    for (ActivityIntentInfo filter : a.intents) {
15409                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15410                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15411                                    "Verification needed for IntentFilter:" + filter.toString());
15412                            mIntentFilterVerifier.addOneIntentFilterVerification(
15413                                    verifierUid, userId, verificationId, filter, packageName);
15414                            count++;
15415                        }
15416                    }
15417                }
15418            }
15419        }
15420
15421        if (count > 0) {
15422            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15423                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15424                    +  " for userId:" + userId);
15425            mIntentFilterVerifier.startVerifications(userId);
15426        } else {
15427            if (DEBUG_DOMAIN_VERIFICATION) {
15428                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15429            }
15430        }
15431    }
15432
15433    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15434        final ComponentName cn  = filter.activity.getComponentName();
15435        final String packageName = cn.getPackageName();
15436
15437        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15438                packageName);
15439        if (ivi == null) {
15440            return true;
15441        }
15442        int status = ivi.getStatus();
15443        switch (status) {
15444            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15445            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15446                return true;
15447
15448            default:
15449                // Nothing to do
15450                return false;
15451        }
15452    }
15453
15454    private static boolean isMultiArch(ApplicationInfo info) {
15455        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15456    }
15457
15458    private static boolean isExternal(PackageParser.Package pkg) {
15459        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15460    }
15461
15462    private static boolean isExternal(PackageSetting ps) {
15463        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15464    }
15465
15466    private static boolean isEphemeral(PackageParser.Package pkg) {
15467        return pkg.applicationInfo.isEphemeralApp();
15468    }
15469
15470    private static boolean isEphemeral(PackageSetting ps) {
15471        return ps.pkg != null && isEphemeral(ps.pkg);
15472    }
15473
15474    private static boolean isSystemApp(PackageParser.Package pkg) {
15475        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15476    }
15477
15478    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15479        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15480    }
15481
15482    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15483        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15484    }
15485
15486    private static boolean isSystemApp(PackageSetting ps) {
15487        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15488    }
15489
15490    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15491        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15492    }
15493
15494    private int packageFlagsToInstallFlags(PackageSetting ps) {
15495        int installFlags = 0;
15496        if (isEphemeral(ps)) {
15497            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15498        }
15499        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15500            // This existing package was an external ASEC install when we have
15501            // the external flag without a UUID
15502            installFlags |= PackageManager.INSTALL_EXTERNAL;
15503        }
15504        if (ps.isForwardLocked()) {
15505            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15506        }
15507        return installFlags;
15508    }
15509
15510    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15511        if (isExternal(pkg)) {
15512            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15513                return StorageManager.UUID_PRIMARY_PHYSICAL;
15514            } else {
15515                return pkg.volumeUuid;
15516            }
15517        } else {
15518            return StorageManager.UUID_PRIVATE_INTERNAL;
15519        }
15520    }
15521
15522    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15523        if (isExternal(pkg)) {
15524            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15525                return mSettings.getExternalVersion();
15526            } else {
15527                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15528            }
15529        } else {
15530            return mSettings.getInternalVersion();
15531        }
15532    }
15533
15534    private void deleteTempPackageFiles() {
15535        final FilenameFilter filter = new FilenameFilter() {
15536            public boolean accept(File dir, String name) {
15537                return name.startsWith("vmdl") && name.endsWith(".tmp");
15538            }
15539        };
15540        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15541            file.delete();
15542        }
15543    }
15544
15545    @Override
15546    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15547            int flags) {
15548        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15549                flags);
15550    }
15551
15552    @Override
15553    public void deletePackage(final String packageName,
15554            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15555        mContext.enforceCallingOrSelfPermission(
15556                android.Manifest.permission.DELETE_PACKAGES, null);
15557        Preconditions.checkNotNull(packageName);
15558        Preconditions.checkNotNull(observer);
15559        final int uid = Binder.getCallingUid();
15560        if (!isOrphaned(packageName)
15561                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15562            try {
15563                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15564                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15565                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15566                observer.onUserActionRequired(intent);
15567            } catch (RemoteException re) {
15568            }
15569            return;
15570        }
15571        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15572        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15573        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15574            mContext.enforceCallingOrSelfPermission(
15575                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15576                    "deletePackage for user " + userId);
15577        }
15578
15579        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15580            try {
15581                observer.onPackageDeleted(packageName,
15582                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15583            } catch (RemoteException re) {
15584            }
15585            return;
15586        }
15587
15588        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15589            try {
15590                observer.onPackageDeleted(packageName,
15591                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15592            } catch (RemoteException re) {
15593            }
15594            return;
15595        }
15596
15597        if (DEBUG_REMOVE) {
15598            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15599                    + " deleteAllUsers: " + deleteAllUsers );
15600        }
15601        // Queue up an async operation since the package deletion may take a little while.
15602        mHandler.post(new Runnable() {
15603            public void run() {
15604                mHandler.removeCallbacks(this);
15605                int returnCode;
15606                if (!deleteAllUsers) {
15607                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15608                } else {
15609                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15610                    // If nobody is blocking uninstall, proceed with delete for all users
15611                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15612                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15613                    } else {
15614                        // Otherwise uninstall individually for users with blockUninstalls=false
15615                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15616                        for (int userId : users) {
15617                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15618                                returnCode = deletePackageX(packageName, userId, userFlags);
15619                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15620                                    Slog.w(TAG, "Package delete failed for user " + userId
15621                                            + ", returnCode " + returnCode);
15622                                }
15623                            }
15624                        }
15625                        // The app has only been marked uninstalled for certain users.
15626                        // We still need to report that delete was blocked
15627                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15628                    }
15629                }
15630                try {
15631                    observer.onPackageDeleted(packageName, returnCode, null);
15632                } catch (RemoteException e) {
15633                    Log.i(TAG, "Observer no longer exists.");
15634                } //end catch
15635            } //end run
15636        });
15637    }
15638
15639    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15640        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15641              || callingUid == Process.SYSTEM_UID) {
15642            return true;
15643        }
15644        final int callingUserId = UserHandle.getUserId(callingUid);
15645        // If the caller installed the pkgName, then allow it to silently uninstall.
15646        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15647            return true;
15648        }
15649
15650        // Allow package verifier to silently uninstall.
15651        if (mRequiredVerifierPackage != null &&
15652                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15653            return true;
15654        }
15655
15656        // Allow package uninstaller to silently uninstall.
15657        if (mRequiredUninstallerPackage != null &&
15658                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15659            return true;
15660        }
15661
15662        // Allow storage manager to silently uninstall.
15663        if (mStorageManagerPackage != null &&
15664                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
15665            return true;
15666        }
15667        return false;
15668    }
15669
15670    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15671        int[] result = EMPTY_INT_ARRAY;
15672        for (int userId : userIds) {
15673            if (getBlockUninstallForUser(packageName, userId)) {
15674                result = ArrayUtils.appendInt(result, userId);
15675            }
15676        }
15677        return result;
15678    }
15679
15680    @Override
15681    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15682        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15683    }
15684
15685    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15686        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15687                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15688        try {
15689            if (dpm != null) {
15690                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15691                        /* callingUserOnly =*/ false);
15692                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15693                        : deviceOwnerComponentName.getPackageName();
15694                // Does the package contains the device owner?
15695                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15696                // this check is probably not needed, since DO should be registered as a device
15697                // admin on some user too. (Original bug for this: b/17657954)
15698                if (packageName.equals(deviceOwnerPackageName)) {
15699                    return true;
15700                }
15701                // Does it contain a device admin for any user?
15702                int[] users;
15703                if (userId == UserHandle.USER_ALL) {
15704                    users = sUserManager.getUserIds();
15705                } else {
15706                    users = new int[]{userId};
15707                }
15708                for (int i = 0; i < users.length; ++i) {
15709                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15710                        return true;
15711                    }
15712                }
15713            }
15714        } catch (RemoteException e) {
15715        }
15716        return false;
15717    }
15718
15719    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15720        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15721    }
15722
15723    /**
15724     *  This method is an internal method that could be get invoked either
15725     *  to delete an installed package or to clean up a failed installation.
15726     *  After deleting an installed package, a broadcast is sent to notify any
15727     *  listeners that the package has been removed. For cleaning up a failed
15728     *  installation, the broadcast is not necessary since the package's
15729     *  installation wouldn't have sent the initial broadcast either
15730     *  The key steps in deleting a package are
15731     *  deleting the package information in internal structures like mPackages,
15732     *  deleting the packages base directories through installd
15733     *  updating mSettings to reflect current status
15734     *  persisting settings for later use
15735     *  sending a broadcast if necessary
15736     */
15737    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15738        final PackageRemovedInfo info = new PackageRemovedInfo();
15739        final boolean res;
15740
15741        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15742                ? UserHandle.USER_ALL : userId;
15743
15744        if (isPackageDeviceAdmin(packageName, removeUser)) {
15745            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15746            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15747        }
15748
15749        PackageSetting uninstalledPs = null;
15750
15751        // for the uninstall-updates case and restricted profiles, remember the per-
15752        // user handle installed state
15753        int[] allUsers;
15754        synchronized (mPackages) {
15755            uninstalledPs = mSettings.mPackages.get(packageName);
15756            if (uninstalledPs == null) {
15757                Slog.w(TAG, "Not removing non-existent package " + packageName);
15758                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15759            }
15760            allUsers = sUserManager.getUserIds();
15761            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15762        }
15763
15764        final int freezeUser;
15765        if (isUpdatedSystemApp(uninstalledPs)
15766                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15767            // We're downgrading a system app, which will apply to all users, so
15768            // freeze them all during the downgrade
15769            freezeUser = UserHandle.USER_ALL;
15770        } else {
15771            freezeUser = removeUser;
15772        }
15773
15774        synchronized (mInstallLock) {
15775            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15776            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15777                    deleteFlags, "deletePackageX")) {
15778                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15779                        deleteFlags | REMOVE_CHATTY, info, true, null);
15780            }
15781            synchronized (mPackages) {
15782                if (res) {
15783                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15784                }
15785            }
15786        }
15787
15788        if (res) {
15789            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15790            info.sendPackageRemovedBroadcasts(killApp);
15791            info.sendSystemPackageUpdatedBroadcasts();
15792            info.sendSystemPackageAppearedBroadcasts();
15793        }
15794        // Force a gc here.
15795        Runtime.getRuntime().gc();
15796        // Delete the resources here after sending the broadcast to let
15797        // other processes clean up before deleting resources.
15798        if (info.args != null) {
15799            synchronized (mInstallLock) {
15800                info.args.doPostDeleteLI(true);
15801            }
15802        }
15803
15804        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15805    }
15806
15807    class PackageRemovedInfo {
15808        String removedPackage;
15809        int uid = -1;
15810        int removedAppId = -1;
15811        int[] origUsers;
15812        int[] removedUsers = null;
15813        boolean isRemovedPackageSystemUpdate = false;
15814        boolean isUpdate;
15815        boolean dataRemoved;
15816        boolean removedForAllUsers;
15817        // Clean up resources deleted packages.
15818        InstallArgs args = null;
15819        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15820        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15821
15822        void sendPackageRemovedBroadcasts(boolean killApp) {
15823            sendPackageRemovedBroadcastInternal(killApp);
15824            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15825            for (int i = 0; i < childCount; i++) {
15826                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15827                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15828            }
15829        }
15830
15831        void sendSystemPackageUpdatedBroadcasts() {
15832            if (isRemovedPackageSystemUpdate) {
15833                sendSystemPackageUpdatedBroadcastsInternal();
15834                final int childCount = (removedChildPackages != null)
15835                        ? removedChildPackages.size() : 0;
15836                for (int i = 0; i < childCount; i++) {
15837                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15838                    if (childInfo.isRemovedPackageSystemUpdate) {
15839                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15840                    }
15841                }
15842            }
15843        }
15844
15845        void sendSystemPackageAppearedBroadcasts() {
15846            final int packageCount = (appearedChildPackages != null)
15847                    ? appearedChildPackages.size() : 0;
15848            for (int i = 0; i < packageCount; i++) {
15849                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15850                for (int userId : installedInfo.newUsers) {
15851                    sendPackageAddedForUser(installedInfo.name, true,
15852                            UserHandle.getAppId(installedInfo.uid), userId);
15853                }
15854            }
15855        }
15856
15857        private void sendSystemPackageUpdatedBroadcastsInternal() {
15858            Bundle extras = new Bundle(2);
15859            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15860            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15861            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15862                    extras, 0, null, null, null);
15863            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15864                    extras, 0, null, null, null);
15865            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15866                    null, 0, removedPackage, null, null);
15867        }
15868
15869        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15870            Bundle extras = new Bundle(2);
15871            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15872            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15873            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15874            if (isUpdate || isRemovedPackageSystemUpdate) {
15875                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15876            }
15877            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15878            if (removedPackage != null) {
15879                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15880                        extras, 0, null, null, removedUsers);
15881                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15882                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15883                            removedPackage, extras, 0, null, null, removedUsers);
15884                }
15885            }
15886            if (removedAppId >= 0) {
15887                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15888                        removedUsers);
15889            }
15890        }
15891    }
15892
15893    /*
15894     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15895     * flag is not set, the data directory is removed as well.
15896     * make sure this flag is set for partially installed apps. If not its meaningless to
15897     * delete a partially installed application.
15898     */
15899    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15900            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15901        String packageName = ps.name;
15902        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15903        // Retrieve object to delete permissions for shared user later on
15904        final PackageParser.Package deletedPkg;
15905        final PackageSetting deletedPs;
15906        // reader
15907        synchronized (mPackages) {
15908            deletedPkg = mPackages.get(packageName);
15909            deletedPs = mSettings.mPackages.get(packageName);
15910            if (outInfo != null) {
15911                outInfo.removedPackage = packageName;
15912                outInfo.removedUsers = deletedPs != null
15913                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15914                        : null;
15915            }
15916        }
15917
15918        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15919
15920        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15921            final PackageParser.Package resolvedPkg;
15922            if (deletedPkg != null) {
15923                resolvedPkg = deletedPkg;
15924            } else {
15925                // We don't have a parsed package when it lives on an ejected
15926                // adopted storage device, so fake something together
15927                resolvedPkg = new PackageParser.Package(ps.name);
15928                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15929            }
15930            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15931                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15932            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15933            if (outInfo != null) {
15934                outInfo.dataRemoved = true;
15935            }
15936            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15937        }
15938
15939        // writer
15940        synchronized (mPackages) {
15941            if (deletedPs != null) {
15942                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15943                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15944                    clearDefaultBrowserIfNeeded(packageName);
15945                    if (outInfo != null) {
15946                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15947                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15948                    }
15949                    updatePermissionsLPw(deletedPs.name, null, 0);
15950                    if (deletedPs.sharedUser != null) {
15951                        // Remove permissions associated with package. Since runtime
15952                        // permissions are per user we have to kill the removed package
15953                        // or packages running under the shared user of the removed
15954                        // package if revoking the permissions requested only by the removed
15955                        // package is successful and this causes a change in gids.
15956                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15957                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15958                                    userId);
15959                            if (userIdToKill == UserHandle.USER_ALL
15960                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15961                                // If gids changed for this user, kill all affected packages.
15962                                mHandler.post(new Runnable() {
15963                                    @Override
15964                                    public void run() {
15965                                        // This has to happen with no lock held.
15966                                        killApplication(deletedPs.name, deletedPs.appId,
15967                                                KILL_APP_REASON_GIDS_CHANGED);
15968                                    }
15969                                });
15970                                break;
15971                            }
15972                        }
15973                    }
15974                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15975                }
15976                // make sure to preserve per-user disabled state if this removal was just
15977                // a downgrade of a system app to the factory package
15978                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15979                    if (DEBUG_REMOVE) {
15980                        Slog.d(TAG, "Propagating install state across downgrade");
15981                    }
15982                    for (int userId : allUserHandles) {
15983                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15984                        if (DEBUG_REMOVE) {
15985                            Slog.d(TAG, "    user " + userId + " => " + installed);
15986                        }
15987                        ps.setInstalled(installed, userId);
15988                    }
15989                }
15990            }
15991            // can downgrade to reader
15992            if (writeSettings) {
15993                // Save settings now
15994                mSettings.writeLPr();
15995            }
15996        }
15997        if (outInfo != null) {
15998            // A user ID was deleted here. Go through all users and remove it
15999            // from KeyStore.
16000            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
16001        }
16002    }
16003
16004    static boolean locationIsPrivileged(File path) {
16005        try {
16006            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16007                    .getCanonicalPath();
16008            return path.getCanonicalPath().startsWith(privilegedAppDir);
16009        } catch (IOException e) {
16010            Slog.e(TAG, "Unable to access code path " + path);
16011        }
16012        return false;
16013    }
16014
16015    /*
16016     * Tries to delete system package.
16017     */
16018    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16019            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16020            boolean writeSettings) {
16021        if (deletedPs.parentPackageName != null) {
16022            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16023            return false;
16024        }
16025
16026        final boolean applyUserRestrictions
16027                = (allUserHandles != null) && (outInfo.origUsers != null);
16028        final PackageSetting disabledPs;
16029        // Confirm if the system package has been updated
16030        // An updated system app can be deleted. This will also have to restore
16031        // the system pkg from system partition
16032        // reader
16033        synchronized (mPackages) {
16034            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16035        }
16036
16037        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16038                + " disabledPs=" + disabledPs);
16039
16040        if (disabledPs == null) {
16041            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16042            return false;
16043        } else if (DEBUG_REMOVE) {
16044            Slog.d(TAG, "Deleting system pkg from data partition");
16045        }
16046
16047        if (DEBUG_REMOVE) {
16048            if (applyUserRestrictions) {
16049                Slog.d(TAG, "Remembering install states:");
16050                for (int userId : allUserHandles) {
16051                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16052                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
16053                }
16054            }
16055        }
16056
16057        // Delete the updated package
16058        outInfo.isRemovedPackageSystemUpdate = true;
16059        if (outInfo.removedChildPackages != null) {
16060            final int childCount = (deletedPs.childPackageNames != null)
16061                    ? deletedPs.childPackageNames.size() : 0;
16062            for (int i = 0; i < childCount; i++) {
16063                String childPackageName = deletedPs.childPackageNames.get(i);
16064                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16065                        .contains(childPackageName)) {
16066                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16067                            childPackageName);
16068                    if (childInfo != null) {
16069                        childInfo.isRemovedPackageSystemUpdate = true;
16070                    }
16071                }
16072            }
16073        }
16074
16075        if (disabledPs.versionCode < deletedPs.versionCode) {
16076            // Delete data for downgrades
16077            flags &= ~PackageManager.DELETE_KEEP_DATA;
16078        } else {
16079            // Preserve data by setting flag
16080            flags |= PackageManager.DELETE_KEEP_DATA;
16081        }
16082
16083        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16084                outInfo, writeSettings, disabledPs.pkg);
16085        if (!ret) {
16086            return false;
16087        }
16088
16089        // writer
16090        synchronized (mPackages) {
16091            // Reinstate the old system package
16092            enableSystemPackageLPw(disabledPs.pkg);
16093            // Remove any native libraries from the upgraded package.
16094            removeNativeBinariesLI(deletedPs);
16095        }
16096
16097        // Install the system package
16098        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16099        int parseFlags = mDefParseFlags
16100                | PackageParser.PARSE_MUST_BE_APK
16101                | PackageParser.PARSE_IS_SYSTEM
16102                | PackageParser.PARSE_IS_SYSTEM_DIR;
16103        if (locationIsPrivileged(disabledPs.codePath)) {
16104            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16105        }
16106
16107        final PackageParser.Package newPkg;
16108        try {
16109            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16110        } catch (PackageManagerException e) {
16111            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16112                    + e.getMessage());
16113            return false;
16114        }
16115        try {
16116            // update shared libraries for the newly re-installed system package
16117            updateSharedLibrariesLPw(newPkg, null);
16118        } catch (PackageManagerException e) {
16119            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16120        }
16121
16122        prepareAppDataAfterInstallLIF(newPkg);
16123
16124        // writer
16125        synchronized (mPackages) {
16126            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16127
16128            // Propagate the permissions state as we do not want to drop on the floor
16129            // runtime permissions. The update permissions method below will take
16130            // care of removing obsolete permissions and grant install permissions.
16131            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16132            updatePermissionsLPw(newPkg.packageName, newPkg,
16133                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16134
16135            if (applyUserRestrictions) {
16136                if (DEBUG_REMOVE) {
16137                    Slog.d(TAG, "Propagating install state across reinstall");
16138                }
16139                for (int userId : allUserHandles) {
16140                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16141                    if (DEBUG_REMOVE) {
16142                        Slog.d(TAG, "    user " + userId + " => " + installed);
16143                    }
16144                    ps.setInstalled(installed, userId);
16145
16146                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16147                }
16148                // Regardless of writeSettings we need to ensure that this restriction
16149                // state propagation is persisted
16150                mSettings.writeAllUsersPackageRestrictionsLPr();
16151            }
16152            // can downgrade to reader here
16153            if (writeSettings) {
16154                mSettings.writeLPr();
16155            }
16156        }
16157        return true;
16158    }
16159
16160    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16161            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16162            PackageRemovedInfo outInfo, boolean writeSettings,
16163            PackageParser.Package replacingPackage) {
16164        synchronized (mPackages) {
16165            if (outInfo != null) {
16166                outInfo.uid = ps.appId;
16167            }
16168
16169            if (outInfo != null && outInfo.removedChildPackages != null) {
16170                final int childCount = (ps.childPackageNames != null)
16171                        ? ps.childPackageNames.size() : 0;
16172                for (int i = 0; i < childCount; i++) {
16173                    String childPackageName = ps.childPackageNames.get(i);
16174                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16175                    if (childPs == null) {
16176                        return false;
16177                    }
16178                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16179                            childPackageName);
16180                    if (childInfo != null) {
16181                        childInfo.uid = childPs.appId;
16182                    }
16183                }
16184            }
16185        }
16186
16187        // Delete package data from internal structures and also remove data if flag is set
16188        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16189
16190        // Delete the child packages data
16191        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16192        for (int i = 0; i < childCount; i++) {
16193            PackageSetting childPs;
16194            synchronized (mPackages) {
16195                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16196            }
16197            if (childPs != null) {
16198                PackageRemovedInfo childOutInfo = (outInfo != null
16199                        && outInfo.removedChildPackages != null)
16200                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16201                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16202                        && (replacingPackage != null
16203                        && !replacingPackage.hasChildPackage(childPs.name))
16204                        ? flags & ~DELETE_KEEP_DATA : flags;
16205                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16206                        deleteFlags, writeSettings);
16207            }
16208        }
16209
16210        // Delete application code and resources only for parent packages
16211        if (ps.parentPackageName == null) {
16212            if (deleteCodeAndResources && (outInfo != null)) {
16213                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16214                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16215                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16216            }
16217        }
16218
16219        return true;
16220    }
16221
16222    @Override
16223    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16224            int userId) {
16225        mContext.enforceCallingOrSelfPermission(
16226                android.Manifest.permission.DELETE_PACKAGES, null);
16227        synchronized (mPackages) {
16228            PackageSetting ps = mSettings.mPackages.get(packageName);
16229            if (ps == null) {
16230                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16231                return false;
16232            }
16233            if (!ps.getInstalled(userId)) {
16234                // Can't block uninstall for an app that is not installed or enabled.
16235                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16236                return false;
16237            }
16238            ps.setBlockUninstall(blockUninstall, userId);
16239            mSettings.writePackageRestrictionsLPr(userId);
16240        }
16241        return true;
16242    }
16243
16244    @Override
16245    public boolean getBlockUninstallForUser(String packageName, int userId) {
16246        synchronized (mPackages) {
16247            PackageSetting ps = mSettings.mPackages.get(packageName);
16248            if (ps == null) {
16249                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16250                return false;
16251            }
16252            return ps.getBlockUninstall(userId);
16253        }
16254    }
16255
16256    @Override
16257    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16258        int callingUid = Binder.getCallingUid();
16259        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16260            throw new SecurityException(
16261                    "setRequiredForSystemUser can only be run by the system or root");
16262        }
16263        synchronized (mPackages) {
16264            PackageSetting ps = mSettings.mPackages.get(packageName);
16265            if (ps == null) {
16266                Log.w(TAG, "Package doesn't exist: " + packageName);
16267                return false;
16268            }
16269            if (systemUserApp) {
16270                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16271            } else {
16272                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16273            }
16274            mSettings.writeLPr();
16275        }
16276        return true;
16277    }
16278
16279    /*
16280     * This method handles package deletion in general
16281     */
16282    private boolean deletePackageLIF(String packageName, UserHandle user,
16283            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16284            PackageRemovedInfo outInfo, boolean writeSettings,
16285            PackageParser.Package replacingPackage) {
16286        if (packageName == null) {
16287            Slog.w(TAG, "Attempt to delete null packageName.");
16288            return false;
16289        }
16290
16291        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16292
16293        PackageSetting ps;
16294
16295        synchronized (mPackages) {
16296            ps = mSettings.mPackages.get(packageName);
16297            if (ps == null) {
16298                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16299                return false;
16300            }
16301
16302            if (ps.parentPackageName != null && (!isSystemApp(ps)
16303                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16304                if (DEBUG_REMOVE) {
16305                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16306                            + ((user == null) ? UserHandle.USER_ALL : user));
16307                }
16308                final int removedUserId = (user != null) ? user.getIdentifier()
16309                        : UserHandle.USER_ALL;
16310                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16311                    return false;
16312                }
16313                markPackageUninstalledForUserLPw(ps, user);
16314                scheduleWritePackageRestrictionsLocked(user);
16315                return true;
16316            }
16317        }
16318
16319        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16320                && user.getIdentifier() != UserHandle.USER_ALL)) {
16321            // The caller is asking that the package only be deleted for a single
16322            // user.  To do this, we just mark its uninstalled state and delete
16323            // its data. If this is a system app, we only allow this to happen if
16324            // they have set the special DELETE_SYSTEM_APP which requests different
16325            // semantics than normal for uninstalling system apps.
16326            markPackageUninstalledForUserLPw(ps, user);
16327
16328            if (!isSystemApp(ps)) {
16329                // Do not uninstall the APK if an app should be cached
16330                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16331                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16332                    // Other user still have this package installed, so all
16333                    // we need to do is clear this user's data and save that
16334                    // it is uninstalled.
16335                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16336                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16337                        return false;
16338                    }
16339                    scheduleWritePackageRestrictionsLocked(user);
16340                    return true;
16341                } else {
16342                    // We need to set it back to 'installed' so the uninstall
16343                    // broadcasts will be sent correctly.
16344                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16345                    ps.setInstalled(true, user.getIdentifier());
16346                }
16347            } else {
16348                // This is a system app, so we assume that the
16349                // other users still have this package installed, so all
16350                // we need to do is clear this user's data and save that
16351                // it is uninstalled.
16352                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16353                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16354                    return false;
16355                }
16356                scheduleWritePackageRestrictionsLocked(user);
16357                return true;
16358            }
16359        }
16360
16361        // If we are deleting a composite package for all users, keep track
16362        // of result for each child.
16363        if (ps.childPackageNames != null && outInfo != null) {
16364            synchronized (mPackages) {
16365                final int childCount = ps.childPackageNames.size();
16366                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16367                for (int i = 0; i < childCount; i++) {
16368                    String childPackageName = ps.childPackageNames.get(i);
16369                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16370                    childInfo.removedPackage = childPackageName;
16371                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16372                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16373                    if (childPs != null) {
16374                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16375                    }
16376                }
16377            }
16378        }
16379
16380        boolean ret = false;
16381        if (isSystemApp(ps)) {
16382            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16383            // When an updated system application is deleted we delete the existing resources
16384            // as well and fall back to existing code in system partition
16385            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16386        } else {
16387            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16388            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16389                    outInfo, writeSettings, replacingPackage);
16390        }
16391
16392        // Take a note whether we deleted the package for all users
16393        if (outInfo != null) {
16394            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16395            if (outInfo.removedChildPackages != null) {
16396                synchronized (mPackages) {
16397                    final int childCount = outInfo.removedChildPackages.size();
16398                    for (int i = 0; i < childCount; i++) {
16399                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16400                        if (childInfo != null) {
16401                            childInfo.removedForAllUsers = mPackages.get(
16402                                    childInfo.removedPackage) == null;
16403                        }
16404                    }
16405                }
16406            }
16407            // If we uninstalled an update to a system app there may be some
16408            // child packages that appeared as they are declared in the system
16409            // app but were not declared in the update.
16410            if (isSystemApp(ps)) {
16411                synchronized (mPackages) {
16412                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16413                    final int childCount = (updatedPs.childPackageNames != null)
16414                            ? updatedPs.childPackageNames.size() : 0;
16415                    for (int i = 0; i < childCount; i++) {
16416                        String childPackageName = updatedPs.childPackageNames.get(i);
16417                        if (outInfo.removedChildPackages == null
16418                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16419                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16420                            if (childPs == null) {
16421                                continue;
16422                            }
16423                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16424                            installRes.name = childPackageName;
16425                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16426                            installRes.pkg = mPackages.get(childPackageName);
16427                            installRes.uid = childPs.pkg.applicationInfo.uid;
16428                            if (outInfo.appearedChildPackages == null) {
16429                                outInfo.appearedChildPackages = new ArrayMap<>();
16430                            }
16431                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16432                        }
16433                    }
16434                }
16435            }
16436        }
16437
16438        return ret;
16439    }
16440
16441    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16442        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16443                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16444        for (int nextUserId : userIds) {
16445            if (DEBUG_REMOVE) {
16446                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16447            }
16448            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16449                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16450                    false /*hidden*/, false /*suspended*/, null, null, null,
16451                    false /*blockUninstall*/,
16452                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16453        }
16454    }
16455
16456    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16457            PackageRemovedInfo outInfo) {
16458        final PackageParser.Package pkg;
16459        synchronized (mPackages) {
16460            pkg = mPackages.get(ps.name);
16461        }
16462
16463        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16464                : new int[] {userId};
16465        for (int nextUserId : userIds) {
16466            if (DEBUG_REMOVE) {
16467                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16468                        + nextUserId);
16469            }
16470
16471            destroyAppDataLIF(pkg, userId,
16472                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16473            destroyAppProfilesLIF(pkg, userId);
16474            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16475            schedulePackageCleaning(ps.name, nextUserId, false);
16476            synchronized (mPackages) {
16477                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16478                    scheduleWritePackageRestrictionsLocked(nextUserId);
16479                }
16480                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16481            }
16482        }
16483
16484        if (outInfo != null) {
16485            outInfo.removedPackage = ps.name;
16486            outInfo.removedAppId = ps.appId;
16487            outInfo.removedUsers = userIds;
16488        }
16489
16490        return true;
16491    }
16492
16493    private final class ClearStorageConnection implements ServiceConnection {
16494        IMediaContainerService mContainerService;
16495
16496        @Override
16497        public void onServiceConnected(ComponentName name, IBinder service) {
16498            synchronized (this) {
16499                mContainerService = IMediaContainerService.Stub.asInterface(service);
16500                notifyAll();
16501            }
16502        }
16503
16504        @Override
16505        public void onServiceDisconnected(ComponentName name) {
16506        }
16507    }
16508
16509    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16510        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16511
16512        final boolean mounted;
16513        if (Environment.isExternalStorageEmulated()) {
16514            mounted = true;
16515        } else {
16516            final String status = Environment.getExternalStorageState();
16517
16518            mounted = status.equals(Environment.MEDIA_MOUNTED)
16519                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16520        }
16521
16522        if (!mounted) {
16523            return;
16524        }
16525
16526        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16527        int[] users;
16528        if (userId == UserHandle.USER_ALL) {
16529            users = sUserManager.getUserIds();
16530        } else {
16531            users = new int[] { userId };
16532        }
16533        final ClearStorageConnection conn = new ClearStorageConnection();
16534        if (mContext.bindServiceAsUser(
16535                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16536            try {
16537                for (int curUser : users) {
16538                    long timeout = SystemClock.uptimeMillis() + 5000;
16539                    synchronized (conn) {
16540                        long now;
16541                        while (conn.mContainerService == null &&
16542                                (now = SystemClock.uptimeMillis()) < timeout) {
16543                            try {
16544                                conn.wait(timeout - now);
16545                            } catch (InterruptedException e) {
16546                            }
16547                        }
16548                    }
16549                    if (conn.mContainerService == null) {
16550                        return;
16551                    }
16552
16553                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16554                    clearDirectory(conn.mContainerService,
16555                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16556                    if (allData) {
16557                        clearDirectory(conn.mContainerService,
16558                                userEnv.buildExternalStorageAppDataDirs(packageName));
16559                        clearDirectory(conn.mContainerService,
16560                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16561                    }
16562                }
16563            } finally {
16564                mContext.unbindService(conn);
16565            }
16566        }
16567    }
16568
16569    @Override
16570    public void clearApplicationProfileData(String packageName) {
16571        enforceSystemOrRoot("Only the system can clear all profile data");
16572
16573        final PackageParser.Package pkg;
16574        synchronized (mPackages) {
16575            pkg = mPackages.get(packageName);
16576        }
16577
16578        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16579            synchronized (mInstallLock) {
16580                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16581                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16582                        true /* removeBaseMarker */);
16583            }
16584        }
16585    }
16586
16587    @Override
16588    public void clearApplicationUserData(final String packageName,
16589            final IPackageDataObserver observer, final int userId) {
16590        mContext.enforceCallingOrSelfPermission(
16591                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16592
16593        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16594                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16595
16596        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16597            throw new SecurityException("Cannot clear data for a protected package: "
16598                    + packageName);
16599        }
16600        // Queue up an async operation since the package deletion may take a little while.
16601        mHandler.post(new Runnable() {
16602            public void run() {
16603                mHandler.removeCallbacks(this);
16604                final boolean succeeded;
16605                try (PackageFreezer freezer = freezePackage(packageName,
16606                        "clearApplicationUserData")) {
16607                    synchronized (mInstallLock) {
16608                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16609                    }
16610                    clearExternalStorageDataSync(packageName, userId, true);
16611                }
16612                if (succeeded) {
16613                    // invoke DeviceStorageMonitor's update method to clear any notifications
16614                    DeviceStorageMonitorInternal dsm = LocalServices
16615                            .getService(DeviceStorageMonitorInternal.class);
16616                    if (dsm != null) {
16617                        dsm.checkMemory();
16618                    }
16619                }
16620                if(observer != null) {
16621                    try {
16622                        observer.onRemoveCompleted(packageName, succeeded);
16623                    } catch (RemoteException e) {
16624                        Log.i(TAG, "Observer no longer exists.");
16625                    }
16626                } //end if observer
16627            } //end run
16628        });
16629    }
16630
16631    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16632        if (packageName == null) {
16633            Slog.w(TAG, "Attempt to delete null packageName.");
16634            return false;
16635        }
16636
16637        // Try finding details about the requested package
16638        PackageParser.Package pkg;
16639        synchronized (mPackages) {
16640            pkg = mPackages.get(packageName);
16641            if (pkg == null) {
16642                final PackageSetting ps = mSettings.mPackages.get(packageName);
16643                if (ps != null) {
16644                    pkg = ps.pkg;
16645                }
16646            }
16647
16648            if (pkg == null) {
16649                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16650                return false;
16651            }
16652
16653            PackageSetting ps = (PackageSetting) pkg.mExtras;
16654            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16655        }
16656
16657        clearAppDataLIF(pkg, userId,
16658                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16659
16660        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16661        removeKeystoreDataIfNeeded(userId, appId);
16662
16663        UserManagerInternal umInternal = getUserManagerInternal();
16664        final int flags;
16665        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16666            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16667        } else if (umInternal.isUserRunning(userId)) {
16668            flags = StorageManager.FLAG_STORAGE_DE;
16669        } else {
16670            flags = 0;
16671        }
16672        prepareAppDataContentsLIF(pkg, userId, flags);
16673
16674        return true;
16675    }
16676
16677    /**
16678     * Reverts user permission state changes (permissions and flags) in
16679     * all packages for a given user.
16680     *
16681     * @param userId The device user for which to do a reset.
16682     */
16683    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16684        final int packageCount = mPackages.size();
16685        for (int i = 0; i < packageCount; i++) {
16686            PackageParser.Package pkg = mPackages.valueAt(i);
16687            PackageSetting ps = (PackageSetting) pkg.mExtras;
16688            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16689        }
16690    }
16691
16692    private void resetNetworkPolicies(int userId) {
16693        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16694    }
16695
16696    /**
16697     * Reverts user permission state changes (permissions and flags).
16698     *
16699     * @param ps The package for which to reset.
16700     * @param userId The device user for which to do a reset.
16701     */
16702    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16703            final PackageSetting ps, final int userId) {
16704        if (ps.pkg == null) {
16705            return;
16706        }
16707
16708        // These are flags that can change base on user actions.
16709        final int userSettableMask = FLAG_PERMISSION_USER_SET
16710                | FLAG_PERMISSION_USER_FIXED
16711                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16712                | FLAG_PERMISSION_REVIEW_REQUIRED;
16713
16714        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16715                | FLAG_PERMISSION_POLICY_FIXED;
16716
16717        boolean writeInstallPermissions = false;
16718        boolean writeRuntimePermissions = false;
16719
16720        final int permissionCount = ps.pkg.requestedPermissions.size();
16721        for (int i = 0; i < permissionCount; i++) {
16722            String permission = ps.pkg.requestedPermissions.get(i);
16723
16724            BasePermission bp = mSettings.mPermissions.get(permission);
16725            if (bp == null) {
16726                continue;
16727            }
16728
16729            // If shared user we just reset the state to which only this app contributed.
16730            if (ps.sharedUser != null) {
16731                boolean used = false;
16732                final int packageCount = ps.sharedUser.packages.size();
16733                for (int j = 0; j < packageCount; j++) {
16734                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16735                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16736                            && pkg.pkg.requestedPermissions.contains(permission)) {
16737                        used = true;
16738                        break;
16739                    }
16740                }
16741                if (used) {
16742                    continue;
16743                }
16744            }
16745
16746            PermissionsState permissionsState = ps.getPermissionsState();
16747
16748            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16749
16750            // Always clear the user settable flags.
16751            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16752                    bp.name) != null;
16753            // If permission review is enabled and this is a legacy app, mark the
16754            // permission as requiring a review as this is the initial state.
16755            int flags = 0;
16756            if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
16757                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16758                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16759            }
16760            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16761                if (hasInstallState) {
16762                    writeInstallPermissions = true;
16763                } else {
16764                    writeRuntimePermissions = true;
16765                }
16766            }
16767
16768            // Below is only runtime permission handling.
16769            if (!bp.isRuntime()) {
16770                continue;
16771            }
16772
16773            // Never clobber system or policy.
16774            if ((oldFlags & policyOrSystemFlags) != 0) {
16775                continue;
16776            }
16777
16778            // If this permission was granted by default, make sure it is.
16779            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16780                if (permissionsState.grantRuntimePermission(bp, userId)
16781                        != PERMISSION_OPERATION_FAILURE) {
16782                    writeRuntimePermissions = true;
16783                }
16784            // If permission review is enabled the permissions for a legacy apps
16785            // are represented as constantly granted runtime ones, so don't revoke.
16786            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16787                // Otherwise, reset the permission.
16788                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16789                switch (revokeResult) {
16790                    case PERMISSION_OPERATION_SUCCESS:
16791                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16792                        writeRuntimePermissions = true;
16793                        final int appId = ps.appId;
16794                        mHandler.post(new Runnable() {
16795                            @Override
16796                            public void run() {
16797                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16798                            }
16799                        });
16800                    } break;
16801                }
16802            }
16803        }
16804
16805        // Synchronously write as we are taking permissions away.
16806        if (writeRuntimePermissions) {
16807            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16808        }
16809
16810        // Synchronously write as we are taking permissions away.
16811        if (writeInstallPermissions) {
16812            mSettings.writeLPr();
16813        }
16814    }
16815
16816    /**
16817     * Remove entries from the keystore daemon. Will only remove it if the
16818     * {@code appId} is valid.
16819     */
16820    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16821        if (appId < 0) {
16822            return;
16823        }
16824
16825        final KeyStore keyStore = KeyStore.getInstance();
16826        if (keyStore != null) {
16827            if (userId == UserHandle.USER_ALL) {
16828                for (final int individual : sUserManager.getUserIds()) {
16829                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16830                }
16831            } else {
16832                keyStore.clearUid(UserHandle.getUid(userId, appId));
16833            }
16834        } else {
16835            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16836        }
16837    }
16838
16839    @Override
16840    public void deleteApplicationCacheFiles(final String packageName,
16841            final IPackageDataObserver observer) {
16842        final int userId = UserHandle.getCallingUserId();
16843        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16844    }
16845
16846    @Override
16847    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16848            final IPackageDataObserver observer) {
16849        mContext.enforceCallingOrSelfPermission(
16850                android.Manifest.permission.DELETE_CACHE_FILES, null);
16851        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16852                /* requireFullPermission= */ true, /* checkShell= */ false,
16853                "delete application cache files");
16854
16855        final PackageParser.Package pkg;
16856        synchronized (mPackages) {
16857            pkg = mPackages.get(packageName);
16858        }
16859
16860        // Queue up an async operation since the package deletion may take a little while.
16861        mHandler.post(new Runnable() {
16862            public void run() {
16863                synchronized (mInstallLock) {
16864                    final int flags = StorageManager.FLAG_STORAGE_DE
16865                            | StorageManager.FLAG_STORAGE_CE;
16866                    // We're only clearing cache files, so we don't care if the
16867                    // app is unfrozen and still able to run
16868                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16869                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16870                }
16871                clearExternalStorageDataSync(packageName, userId, false);
16872                if (observer != null) {
16873                    try {
16874                        observer.onRemoveCompleted(packageName, true);
16875                    } catch (RemoteException e) {
16876                        Log.i(TAG, "Observer no longer exists.");
16877                    }
16878                }
16879            }
16880        });
16881    }
16882
16883    @Override
16884    public void getPackageSizeInfo(final String packageName, int userHandle,
16885            final IPackageStatsObserver observer) {
16886        mContext.enforceCallingOrSelfPermission(
16887                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16888        if (packageName == null) {
16889            throw new IllegalArgumentException("Attempt to get size of null packageName");
16890        }
16891
16892        PackageStats stats = new PackageStats(packageName, userHandle);
16893
16894        /*
16895         * Queue up an async operation since the package measurement may take a
16896         * little while.
16897         */
16898        Message msg = mHandler.obtainMessage(INIT_COPY);
16899        msg.obj = new MeasureParams(stats, observer);
16900        mHandler.sendMessage(msg);
16901    }
16902
16903    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16904        final PackageSetting ps;
16905        synchronized (mPackages) {
16906            ps = mSettings.mPackages.get(packageName);
16907            if (ps == null) {
16908                Slog.w(TAG, "Failed to find settings for " + packageName);
16909                return false;
16910            }
16911        }
16912
16913        final String[] packageNames = { packageName };
16914        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
16915        final String[] codePaths = { ps.codePathString };
16916
16917        try {
16918            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
16919                    ps.appId, ceDataInodes, codePaths, stats);
16920
16921            // For now, ignore code size of packages on system partition
16922            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16923                stats.codeSize = 0;
16924            }
16925
16926            // External clients expect these to be tracked separately
16927            stats.dataSize -= stats.cacheSize;
16928
16929        } catch (InstallerException e) {
16930            Slog.w(TAG, String.valueOf(e));
16931            return false;
16932        }
16933
16934        return true;
16935    }
16936
16937    private int getUidTargetSdkVersionLockedLPr(int uid) {
16938        Object obj = mSettings.getUserIdLPr(uid);
16939        if (obj instanceof SharedUserSetting) {
16940            final SharedUserSetting sus = (SharedUserSetting) obj;
16941            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16942            final Iterator<PackageSetting> it = sus.packages.iterator();
16943            while (it.hasNext()) {
16944                final PackageSetting ps = it.next();
16945                if (ps.pkg != null) {
16946                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16947                    if (v < vers) vers = v;
16948                }
16949            }
16950            return vers;
16951        } else if (obj instanceof PackageSetting) {
16952            final PackageSetting ps = (PackageSetting) obj;
16953            if (ps.pkg != null) {
16954                return ps.pkg.applicationInfo.targetSdkVersion;
16955            }
16956        }
16957        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16958    }
16959
16960    @Override
16961    public void addPreferredActivity(IntentFilter filter, int match,
16962            ComponentName[] set, ComponentName activity, int userId) {
16963        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16964                "Adding preferred");
16965    }
16966
16967    private void addPreferredActivityInternal(IntentFilter filter, int match,
16968            ComponentName[] set, ComponentName activity, boolean always, int userId,
16969            String opname) {
16970        // writer
16971        int callingUid = Binder.getCallingUid();
16972        enforceCrossUserPermission(callingUid, userId,
16973                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16974        if (filter.countActions() == 0) {
16975            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16976            return;
16977        }
16978        synchronized (mPackages) {
16979            if (mContext.checkCallingOrSelfPermission(
16980                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16981                    != PackageManager.PERMISSION_GRANTED) {
16982                if (getUidTargetSdkVersionLockedLPr(callingUid)
16983                        < Build.VERSION_CODES.FROYO) {
16984                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16985                            + callingUid);
16986                    return;
16987                }
16988                mContext.enforceCallingOrSelfPermission(
16989                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16990            }
16991
16992            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16993            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16994                    + userId + ":");
16995            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16996            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16997            scheduleWritePackageRestrictionsLocked(userId);
16998            postPreferredActivityChangedBroadcast(userId);
16999        }
17000    }
17001
17002    private void postPreferredActivityChangedBroadcast(int userId) {
17003        mHandler.post(() -> {
17004            final IActivityManager am = ActivityManagerNative.getDefault();
17005            if (am == null) {
17006                return;
17007            }
17008
17009            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
17010            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17011            try {
17012                am.broadcastIntent(null, intent, null, null,
17013                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
17014                        null, false, false, userId);
17015            } catch (RemoteException e) {
17016            }
17017        });
17018    }
17019
17020    @Override
17021    public void replacePreferredActivity(IntentFilter filter, int match,
17022            ComponentName[] set, ComponentName activity, int userId) {
17023        if (filter.countActions() != 1) {
17024            throw new IllegalArgumentException(
17025                    "replacePreferredActivity expects filter to have only 1 action.");
17026        }
17027        if (filter.countDataAuthorities() != 0
17028                || filter.countDataPaths() != 0
17029                || filter.countDataSchemes() > 1
17030                || filter.countDataTypes() != 0) {
17031            throw new IllegalArgumentException(
17032                    "replacePreferredActivity expects filter to have no data authorities, " +
17033                    "paths, or types; and at most one scheme.");
17034        }
17035
17036        final int callingUid = Binder.getCallingUid();
17037        enforceCrossUserPermission(callingUid, userId,
17038                true /* requireFullPermission */, false /* checkShell */,
17039                "replace preferred activity");
17040        synchronized (mPackages) {
17041            if (mContext.checkCallingOrSelfPermission(
17042                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17043                    != PackageManager.PERMISSION_GRANTED) {
17044                if (getUidTargetSdkVersionLockedLPr(callingUid)
17045                        < Build.VERSION_CODES.FROYO) {
17046                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17047                            + Binder.getCallingUid());
17048                    return;
17049                }
17050                mContext.enforceCallingOrSelfPermission(
17051                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17052            }
17053
17054            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17055            if (pir != null) {
17056                // Get all of the existing entries that exactly match this filter.
17057                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17058                if (existing != null && existing.size() == 1) {
17059                    PreferredActivity cur = existing.get(0);
17060                    if (DEBUG_PREFERRED) {
17061                        Slog.i(TAG, "Checking replace of preferred:");
17062                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17063                        if (!cur.mPref.mAlways) {
17064                            Slog.i(TAG, "  -- CUR; not mAlways!");
17065                        } else {
17066                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
17067                            Slog.i(TAG, "  -- CUR: mSet="
17068                                    + Arrays.toString(cur.mPref.mSetComponents));
17069                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
17070                            Slog.i(TAG, "  -- NEW: mMatch="
17071                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
17072                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
17073                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
17074                        }
17075                    }
17076                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17077                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17078                            && cur.mPref.sameSet(set)) {
17079                        // Setting the preferred activity to what it happens to be already
17080                        if (DEBUG_PREFERRED) {
17081                            Slog.i(TAG, "Replacing with same preferred activity "
17082                                    + cur.mPref.mShortComponent + " for user "
17083                                    + userId + ":");
17084                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17085                        }
17086                        return;
17087                    }
17088                }
17089
17090                if (existing != null) {
17091                    if (DEBUG_PREFERRED) {
17092                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17093                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17094                    }
17095                    for (int i = 0; i < existing.size(); i++) {
17096                        PreferredActivity pa = existing.get(i);
17097                        if (DEBUG_PREFERRED) {
17098                            Slog.i(TAG, "Removing existing preferred activity "
17099                                    + pa.mPref.mComponent + ":");
17100                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17101                        }
17102                        pir.removeFilter(pa);
17103                    }
17104                }
17105            }
17106            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17107                    "Replacing preferred");
17108        }
17109    }
17110
17111    @Override
17112    public void clearPackagePreferredActivities(String packageName) {
17113        final int uid = Binder.getCallingUid();
17114        // writer
17115        synchronized (mPackages) {
17116            PackageParser.Package pkg = mPackages.get(packageName);
17117            if (pkg == null || pkg.applicationInfo.uid != uid) {
17118                if (mContext.checkCallingOrSelfPermission(
17119                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17120                        != PackageManager.PERMISSION_GRANTED) {
17121                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17122                            < Build.VERSION_CODES.FROYO) {
17123                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17124                                + Binder.getCallingUid());
17125                        return;
17126                    }
17127                    mContext.enforceCallingOrSelfPermission(
17128                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17129                }
17130            }
17131
17132            int user = UserHandle.getCallingUserId();
17133            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17134                scheduleWritePackageRestrictionsLocked(user);
17135            }
17136        }
17137    }
17138
17139    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17140    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17141        ArrayList<PreferredActivity> removed = null;
17142        boolean changed = false;
17143        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17144            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17145            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17146            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17147                continue;
17148            }
17149            Iterator<PreferredActivity> it = pir.filterIterator();
17150            while (it.hasNext()) {
17151                PreferredActivity pa = it.next();
17152                // Mark entry for removal only if it matches the package name
17153                // and the entry is of type "always".
17154                if (packageName == null ||
17155                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17156                                && pa.mPref.mAlways)) {
17157                    if (removed == null) {
17158                        removed = new ArrayList<PreferredActivity>();
17159                    }
17160                    removed.add(pa);
17161                }
17162            }
17163            if (removed != null) {
17164                for (int j=0; j<removed.size(); j++) {
17165                    PreferredActivity pa = removed.get(j);
17166                    pir.removeFilter(pa);
17167                }
17168                changed = true;
17169            }
17170        }
17171        if (changed) {
17172            postPreferredActivityChangedBroadcast(userId);
17173        }
17174        return changed;
17175    }
17176
17177    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17178    private void clearIntentFilterVerificationsLPw(int userId) {
17179        final int packageCount = mPackages.size();
17180        for (int i = 0; i < packageCount; i++) {
17181            PackageParser.Package pkg = mPackages.valueAt(i);
17182            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17183        }
17184    }
17185
17186    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17187    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17188        if (userId == UserHandle.USER_ALL) {
17189            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17190                    sUserManager.getUserIds())) {
17191                for (int oneUserId : sUserManager.getUserIds()) {
17192                    scheduleWritePackageRestrictionsLocked(oneUserId);
17193                }
17194            }
17195        } else {
17196            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17197                scheduleWritePackageRestrictionsLocked(userId);
17198            }
17199        }
17200    }
17201
17202    void clearDefaultBrowserIfNeeded(String packageName) {
17203        for (int oneUserId : sUserManager.getUserIds()) {
17204            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17205            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17206            if (packageName.equals(defaultBrowserPackageName)) {
17207                setDefaultBrowserPackageName(null, oneUserId);
17208            }
17209        }
17210    }
17211
17212    @Override
17213    public void resetApplicationPreferences(int userId) {
17214        mContext.enforceCallingOrSelfPermission(
17215                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17216        final long identity = Binder.clearCallingIdentity();
17217        // writer
17218        try {
17219            synchronized (mPackages) {
17220                clearPackagePreferredActivitiesLPw(null, userId);
17221                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17222                // TODO: We have to reset the default SMS and Phone. This requires
17223                // significant refactoring to keep all default apps in the package
17224                // manager (cleaner but more work) or have the services provide
17225                // callbacks to the package manager to request a default app reset.
17226                applyFactoryDefaultBrowserLPw(userId);
17227                clearIntentFilterVerificationsLPw(userId);
17228                primeDomainVerificationsLPw(userId);
17229                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17230                scheduleWritePackageRestrictionsLocked(userId);
17231            }
17232            resetNetworkPolicies(userId);
17233        } finally {
17234            Binder.restoreCallingIdentity(identity);
17235        }
17236    }
17237
17238    @Override
17239    public int getPreferredActivities(List<IntentFilter> outFilters,
17240            List<ComponentName> outActivities, String packageName) {
17241
17242        int num = 0;
17243        final int userId = UserHandle.getCallingUserId();
17244        // reader
17245        synchronized (mPackages) {
17246            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17247            if (pir != null) {
17248                final Iterator<PreferredActivity> it = pir.filterIterator();
17249                while (it.hasNext()) {
17250                    final PreferredActivity pa = it.next();
17251                    if (packageName == null
17252                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17253                                    && pa.mPref.mAlways)) {
17254                        if (outFilters != null) {
17255                            outFilters.add(new IntentFilter(pa));
17256                        }
17257                        if (outActivities != null) {
17258                            outActivities.add(pa.mPref.mComponent);
17259                        }
17260                    }
17261                }
17262            }
17263        }
17264
17265        return num;
17266    }
17267
17268    @Override
17269    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17270            int userId) {
17271        int callingUid = Binder.getCallingUid();
17272        if (callingUid != Process.SYSTEM_UID) {
17273            throw new SecurityException(
17274                    "addPersistentPreferredActivity can only be run by the system");
17275        }
17276        if (filter.countActions() == 0) {
17277            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17278            return;
17279        }
17280        synchronized (mPackages) {
17281            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17282                    ":");
17283            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17284            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17285                    new PersistentPreferredActivity(filter, activity));
17286            scheduleWritePackageRestrictionsLocked(userId);
17287            postPreferredActivityChangedBroadcast(userId);
17288        }
17289    }
17290
17291    @Override
17292    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17293        int callingUid = Binder.getCallingUid();
17294        if (callingUid != Process.SYSTEM_UID) {
17295            throw new SecurityException(
17296                    "clearPackagePersistentPreferredActivities can only be run by the system");
17297        }
17298        ArrayList<PersistentPreferredActivity> removed = null;
17299        boolean changed = false;
17300        synchronized (mPackages) {
17301            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17302                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17303                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17304                        .valueAt(i);
17305                if (userId != thisUserId) {
17306                    continue;
17307                }
17308                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17309                while (it.hasNext()) {
17310                    PersistentPreferredActivity ppa = it.next();
17311                    // Mark entry for removal only if it matches the package name.
17312                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17313                        if (removed == null) {
17314                            removed = new ArrayList<PersistentPreferredActivity>();
17315                        }
17316                        removed.add(ppa);
17317                    }
17318                }
17319                if (removed != null) {
17320                    for (int j=0; j<removed.size(); j++) {
17321                        PersistentPreferredActivity ppa = removed.get(j);
17322                        ppir.removeFilter(ppa);
17323                    }
17324                    changed = true;
17325                }
17326            }
17327
17328            if (changed) {
17329                scheduleWritePackageRestrictionsLocked(userId);
17330                postPreferredActivityChangedBroadcast(userId);
17331            }
17332        }
17333    }
17334
17335    /**
17336     * Common machinery for picking apart a restored XML blob and passing
17337     * it to a caller-supplied functor to be applied to the running system.
17338     */
17339    private void restoreFromXml(XmlPullParser parser, int userId,
17340            String expectedStartTag, BlobXmlRestorer functor)
17341            throws IOException, XmlPullParserException {
17342        int type;
17343        while ((type = parser.next()) != XmlPullParser.START_TAG
17344                && type != XmlPullParser.END_DOCUMENT) {
17345        }
17346        if (type != XmlPullParser.START_TAG) {
17347            // oops didn't find a start tag?!
17348            if (DEBUG_BACKUP) {
17349                Slog.e(TAG, "Didn't find start tag during restore");
17350            }
17351            return;
17352        }
17353Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17354        // this is supposed to be TAG_PREFERRED_BACKUP
17355        if (!expectedStartTag.equals(parser.getName())) {
17356            if (DEBUG_BACKUP) {
17357                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17358            }
17359            return;
17360        }
17361
17362        // skip interfering stuff, then we're aligned with the backing implementation
17363        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17364Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17365        functor.apply(parser, userId);
17366    }
17367
17368    private interface BlobXmlRestorer {
17369        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17370    }
17371
17372    /**
17373     * Non-Binder method, support for the backup/restore mechanism: write the
17374     * full set of preferred activities in its canonical XML format.  Returns the
17375     * XML output as a byte array, or null if there is none.
17376     */
17377    @Override
17378    public byte[] getPreferredActivityBackup(int userId) {
17379        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17380            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17381        }
17382
17383        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17384        try {
17385            final XmlSerializer serializer = new FastXmlSerializer();
17386            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17387            serializer.startDocument(null, true);
17388            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17389
17390            synchronized (mPackages) {
17391                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17392            }
17393
17394            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17395            serializer.endDocument();
17396            serializer.flush();
17397        } catch (Exception e) {
17398            if (DEBUG_BACKUP) {
17399                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17400            }
17401            return null;
17402        }
17403
17404        return dataStream.toByteArray();
17405    }
17406
17407    @Override
17408    public void restorePreferredActivities(byte[] backup, int userId) {
17409        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17410            throw new SecurityException("Only the system may call restorePreferredActivities()");
17411        }
17412
17413        try {
17414            final XmlPullParser parser = Xml.newPullParser();
17415            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17416            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17417                    new BlobXmlRestorer() {
17418                        @Override
17419                        public void apply(XmlPullParser parser, int userId)
17420                                throws XmlPullParserException, IOException {
17421                            synchronized (mPackages) {
17422                                mSettings.readPreferredActivitiesLPw(parser, userId);
17423                            }
17424                        }
17425                    } );
17426        } catch (Exception e) {
17427            if (DEBUG_BACKUP) {
17428                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17429            }
17430        }
17431    }
17432
17433    /**
17434     * Non-Binder method, support for the backup/restore mechanism: write the
17435     * default browser (etc) settings in its canonical XML format.  Returns the default
17436     * browser XML representation as a byte array, or null if there is none.
17437     */
17438    @Override
17439    public byte[] getDefaultAppsBackup(int userId) {
17440        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17441            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17442        }
17443
17444        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17445        try {
17446            final XmlSerializer serializer = new FastXmlSerializer();
17447            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17448            serializer.startDocument(null, true);
17449            serializer.startTag(null, TAG_DEFAULT_APPS);
17450
17451            synchronized (mPackages) {
17452                mSettings.writeDefaultAppsLPr(serializer, userId);
17453            }
17454
17455            serializer.endTag(null, TAG_DEFAULT_APPS);
17456            serializer.endDocument();
17457            serializer.flush();
17458        } catch (Exception e) {
17459            if (DEBUG_BACKUP) {
17460                Slog.e(TAG, "Unable to write default apps for backup", e);
17461            }
17462            return null;
17463        }
17464
17465        return dataStream.toByteArray();
17466    }
17467
17468    @Override
17469    public void restoreDefaultApps(byte[] backup, int userId) {
17470        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17471            throw new SecurityException("Only the system may call restoreDefaultApps()");
17472        }
17473
17474        try {
17475            final XmlPullParser parser = Xml.newPullParser();
17476            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17477            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17478                    new BlobXmlRestorer() {
17479                        @Override
17480                        public void apply(XmlPullParser parser, int userId)
17481                                throws XmlPullParserException, IOException {
17482                            synchronized (mPackages) {
17483                                mSettings.readDefaultAppsLPw(parser, userId);
17484                            }
17485                        }
17486                    } );
17487        } catch (Exception e) {
17488            if (DEBUG_BACKUP) {
17489                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17490            }
17491        }
17492    }
17493
17494    @Override
17495    public byte[] getIntentFilterVerificationBackup(int userId) {
17496        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17497            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17498        }
17499
17500        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17501        try {
17502            final XmlSerializer serializer = new FastXmlSerializer();
17503            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17504            serializer.startDocument(null, true);
17505            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17506
17507            synchronized (mPackages) {
17508                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17509            }
17510
17511            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17512            serializer.endDocument();
17513            serializer.flush();
17514        } catch (Exception e) {
17515            if (DEBUG_BACKUP) {
17516                Slog.e(TAG, "Unable to write default apps for backup", e);
17517            }
17518            return null;
17519        }
17520
17521        return dataStream.toByteArray();
17522    }
17523
17524    @Override
17525    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17526        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17527            throw new SecurityException("Only the system may call restorePreferredActivities()");
17528        }
17529
17530        try {
17531            final XmlPullParser parser = Xml.newPullParser();
17532            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17533            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17534                    new BlobXmlRestorer() {
17535                        @Override
17536                        public void apply(XmlPullParser parser, int userId)
17537                                throws XmlPullParserException, IOException {
17538                            synchronized (mPackages) {
17539                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17540                                mSettings.writeLPr();
17541                            }
17542                        }
17543                    } );
17544        } catch (Exception e) {
17545            if (DEBUG_BACKUP) {
17546                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17547            }
17548        }
17549    }
17550
17551    @Override
17552    public byte[] getPermissionGrantBackup(int userId) {
17553        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17554            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17555        }
17556
17557        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17558        try {
17559            final XmlSerializer serializer = new FastXmlSerializer();
17560            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17561            serializer.startDocument(null, true);
17562            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17563
17564            synchronized (mPackages) {
17565                serializeRuntimePermissionGrantsLPr(serializer, userId);
17566            }
17567
17568            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17569            serializer.endDocument();
17570            serializer.flush();
17571        } catch (Exception e) {
17572            if (DEBUG_BACKUP) {
17573                Slog.e(TAG, "Unable to write default apps for backup", e);
17574            }
17575            return null;
17576        }
17577
17578        return dataStream.toByteArray();
17579    }
17580
17581    @Override
17582    public void restorePermissionGrants(byte[] backup, int userId) {
17583        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17584            throw new SecurityException("Only the system may call restorePermissionGrants()");
17585        }
17586
17587        try {
17588            final XmlPullParser parser = Xml.newPullParser();
17589            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17590            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17591                    new BlobXmlRestorer() {
17592                        @Override
17593                        public void apply(XmlPullParser parser, int userId)
17594                                throws XmlPullParserException, IOException {
17595                            synchronized (mPackages) {
17596                                processRestoredPermissionGrantsLPr(parser, userId);
17597                            }
17598                        }
17599                    } );
17600        } catch (Exception e) {
17601            if (DEBUG_BACKUP) {
17602                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17603            }
17604        }
17605    }
17606
17607    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17608            throws IOException {
17609        serializer.startTag(null, TAG_ALL_GRANTS);
17610
17611        final int N = mSettings.mPackages.size();
17612        for (int i = 0; i < N; i++) {
17613            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17614            boolean pkgGrantsKnown = false;
17615
17616            PermissionsState packagePerms = ps.getPermissionsState();
17617
17618            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17619                final int grantFlags = state.getFlags();
17620                // only look at grants that are not system/policy fixed
17621                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17622                    final boolean isGranted = state.isGranted();
17623                    // And only back up the user-twiddled state bits
17624                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17625                        final String packageName = mSettings.mPackages.keyAt(i);
17626                        if (!pkgGrantsKnown) {
17627                            serializer.startTag(null, TAG_GRANT);
17628                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17629                            pkgGrantsKnown = true;
17630                        }
17631
17632                        final boolean userSet =
17633                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17634                        final boolean userFixed =
17635                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17636                        final boolean revoke =
17637                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17638
17639                        serializer.startTag(null, TAG_PERMISSION);
17640                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17641                        if (isGranted) {
17642                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17643                        }
17644                        if (userSet) {
17645                            serializer.attribute(null, ATTR_USER_SET, "true");
17646                        }
17647                        if (userFixed) {
17648                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17649                        }
17650                        if (revoke) {
17651                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17652                        }
17653                        serializer.endTag(null, TAG_PERMISSION);
17654                    }
17655                }
17656            }
17657
17658            if (pkgGrantsKnown) {
17659                serializer.endTag(null, TAG_GRANT);
17660            }
17661        }
17662
17663        serializer.endTag(null, TAG_ALL_GRANTS);
17664    }
17665
17666    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17667            throws XmlPullParserException, IOException {
17668        String pkgName = null;
17669        int outerDepth = parser.getDepth();
17670        int type;
17671        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17672                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17673            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17674                continue;
17675            }
17676
17677            final String tagName = parser.getName();
17678            if (tagName.equals(TAG_GRANT)) {
17679                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17680                if (DEBUG_BACKUP) {
17681                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17682                }
17683            } else if (tagName.equals(TAG_PERMISSION)) {
17684
17685                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17686                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17687
17688                int newFlagSet = 0;
17689                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17690                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17691                }
17692                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17693                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17694                }
17695                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17696                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17697                }
17698                if (DEBUG_BACKUP) {
17699                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17700                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17701                }
17702                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17703                if (ps != null) {
17704                    // Already installed so we apply the grant immediately
17705                    if (DEBUG_BACKUP) {
17706                        Slog.v(TAG, "        + already installed; applying");
17707                    }
17708                    PermissionsState perms = ps.getPermissionsState();
17709                    BasePermission bp = mSettings.mPermissions.get(permName);
17710                    if (bp != null) {
17711                        if (isGranted) {
17712                            perms.grantRuntimePermission(bp, userId);
17713                        }
17714                        if (newFlagSet != 0) {
17715                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17716                        }
17717                    }
17718                } else {
17719                    // Need to wait for post-restore install to apply the grant
17720                    if (DEBUG_BACKUP) {
17721                        Slog.v(TAG, "        - not yet installed; saving for later");
17722                    }
17723                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17724                            isGranted, newFlagSet, userId);
17725                }
17726            } else {
17727                PackageManagerService.reportSettingsProblem(Log.WARN,
17728                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17729                XmlUtils.skipCurrentTag(parser);
17730            }
17731        }
17732
17733        scheduleWriteSettingsLocked();
17734        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17735    }
17736
17737    @Override
17738    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17739            int sourceUserId, int targetUserId, int flags) {
17740        mContext.enforceCallingOrSelfPermission(
17741                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17742        int callingUid = Binder.getCallingUid();
17743        enforceOwnerRights(ownerPackage, callingUid);
17744        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17745        if (intentFilter.countActions() == 0) {
17746            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17747            return;
17748        }
17749        synchronized (mPackages) {
17750            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17751                    ownerPackage, targetUserId, flags);
17752            CrossProfileIntentResolver resolver =
17753                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17754            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17755            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17756            if (existing != null) {
17757                int size = existing.size();
17758                for (int i = 0; i < size; i++) {
17759                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17760                        return;
17761                    }
17762                }
17763            }
17764            resolver.addFilter(newFilter);
17765            scheduleWritePackageRestrictionsLocked(sourceUserId);
17766        }
17767    }
17768
17769    @Override
17770    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17771        mContext.enforceCallingOrSelfPermission(
17772                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17773        int callingUid = Binder.getCallingUid();
17774        enforceOwnerRights(ownerPackage, callingUid);
17775        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17776        synchronized (mPackages) {
17777            CrossProfileIntentResolver resolver =
17778                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17779            ArraySet<CrossProfileIntentFilter> set =
17780                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17781            for (CrossProfileIntentFilter filter : set) {
17782                if (filter.getOwnerPackage().equals(ownerPackage)) {
17783                    resolver.removeFilter(filter);
17784                }
17785            }
17786            scheduleWritePackageRestrictionsLocked(sourceUserId);
17787        }
17788    }
17789
17790    // Enforcing that callingUid is owning pkg on userId
17791    private void enforceOwnerRights(String pkg, int callingUid) {
17792        // The system owns everything.
17793        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17794            return;
17795        }
17796        int callingUserId = UserHandle.getUserId(callingUid);
17797        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17798        if (pi == null) {
17799            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17800                    + callingUserId);
17801        }
17802        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17803            throw new SecurityException("Calling uid " + callingUid
17804                    + " does not own package " + pkg);
17805        }
17806    }
17807
17808    @Override
17809    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17810        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17811    }
17812
17813    private Intent getHomeIntent() {
17814        Intent intent = new Intent(Intent.ACTION_MAIN);
17815        intent.addCategory(Intent.CATEGORY_HOME);
17816        intent.addCategory(Intent.CATEGORY_DEFAULT);
17817        return intent;
17818    }
17819
17820    private IntentFilter getHomeFilter() {
17821        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17822        filter.addCategory(Intent.CATEGORY_HOME);
17823        filter.addCategory(Intent.CATEGORY_DEFAULT);
17824        return filter;
17825    }
17826
17827    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17828            int userId) {
17829        Intent intent  = getHomeIntent();
17830        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17831                PackageManager.GET_META_DATA, userId);
17832        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17833                true, false, false, userId);
17834
17835        allHomeCandidates.clear();
17836        if (list != null) {
17837            for (ResolveInfo ri : list) {
17838                allHomeCandidates.add(ri);
17839            }
17840        }
17841        return (preferred == null || preferred.activityInfo == null)
17842                ? null
17843                : new ComponentName(preferred.activityInfo.packageName,
17844                        preferred.activityInfo.name);
17845    }
17846
17847    @Override
17848    public void setHomeActivity(ComponentName comp, int userId) {
17849        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17850        getHomeActivitiesAsUser(homeActivities, userId);
17851
17852        boolean found = false;
17853
17854        final int size = homeActivities.size();
17855        final ComponentName[] set = new ComponentName[size];
17856        for (int i = 0; i < size; i++) {
17857            final ResolveInfo candidate = homeActivities.get(i);
17858            final ActivityInfo info = candidate.activityInfo;
17859            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17860            set[i] = activityName;
17861            if (!found && activityName.equals(comp)) {
17862                found = true;
17863            }
17864        }
17865        if (!found) {
17866            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17867                    + userId);
17868        }
17869        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17870                set, comp, userId);
17871    }
17872
17873    private @Nullable String getSetupWizardPackageName() {
17874        final Intent intent = new Intent(Intent.ACTION_MAIN);
17875        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17876
17877        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17878                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17879                        | MATCH_DISABLED_COMPONENTS,
17880                UserHandle.myUserId());
17881        if (matches.size() == 1) {
17882            return matches.get(0).getComponentInfo().packageName;
17883        } else {
17884            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17885                    + ": matches=" + matches);
17886            return null;
17887        }
17888    }
17889
17890    private @Nullable String getStorageManagerPackageName() {
17891        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
17892
17893        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17894                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17895                        | MATCH_DISABLED_COMPONENTS,
17896                UserHandle.myUserId());
17897        if (matches.size() == 1) {
17898            return matches.get(0).getComponentInfo().packageName;
17899        } else {
17900            Slog.e(TAG, "There should probably be exactly one storage manager; found "
17901                    + matches.size() + ": matches=" + matches);
17902            return null;
17903        }
17904    }
17905
17906    @Override
17907    public void setApplicationEnabledSetting(String appPackageName,
17908            int newState, int flags, int userId, String callingPackage) {
17909        if (!sUserManager.exists(userId)) return;
17910        if (callingPackage == null) {
17911            callingPackage = Integer.toString(Binder.getCallingUid());
17912        }
17913        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17914    }
17915
17916    @Override
17917    public void setComponentEnabledSetting(ComponentName componentName,
17918            int newState, int flags, int userId) {
17919        if (!sUserManager.exists(userId)) return;
17920        setEnabledSetting(componentName.getPackageName(),
17921                componentName.getClassName(), newState, flags, userId, null);
17922    }
17923
17924    private void setEnabledSetting(final String packageName, String className, int newState,
17925            final int flags, int userId, String callingPackage) {
17926        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17927              || newState == COMPONENT_ENABLED_STATE_ENABLED
17928              || newState == COMPONENT_ENABLED_STATE_DISABLED
17929              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17930              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17931            throw new IllegalArgumentException("Invalid new component state: "
17932                    + newState);
17933        }
17934        PackageSetting pkgSetting;
17935        final int uid = Binder.getCallingUid();
17936        final int permission;
17937        if (uid == Process.SYSTEM_UID) {
17938            permission = PackageManager.PERMISSION_GRANTED;
17939        } else {
17940            permission = mContext.checkCallingOrSelfPermission(
17941                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17942        }
17943        enforceCrossUserPermission(uid, userId,
17944                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17945        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17946        boolean sendNow = false;
17947        boolean isApp = (className == null);
17948        String componentName = isApp ? packageName : className;
17949        int packageUid = -1;
17950        ArrayList<String> components;
17951
17952        // writer
17953        synchronized (mPackages) {
17954            pkgSetting = mSettings.mPackages.get(packageName);
17955            if (pkgSetting == null) {
17956                if (className == null) {
17957                    throw new IllegalArgumentException("Unknown package: " + packageName);
17958                }
17959                throw new IllegalArgumentException(
17960                        "Unknown component: " + packageName + "/" + className);
17961            }
17962        }
17963
17964        // Limit who can change which apps
17965        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17966            // Don't allow apps that don't have permission to modify other apps
17967            if (!allowedByPermission) {
17968                throw new SecurityException(
17969                        "Permission Denial: attempt to change component state from pid="
17970                        + Binder.getCallingPid()
17971                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17972            }
17973            // Don't allow changing protected packages.
17974            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17975                throw new SecurityException("Cannot disable a protected package: " + packageName);
17976            }
17977        }
17978
17979        synchronized (mPackages) {
17980            if (uid == Process.SHELL_UID) {
17981                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17982                int oldState = pkgSetting.getEnabled(userId);
17983                if (className == null
17984                    &&
17985                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17986                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17987                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17988                    &&
17989                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17990                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17991                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17992                    // ok
17993                } else {
17994                    throw new SecurityException(
17995                            "Shell cannot change component state for " + packageName + "/"
17996                            + className + " to " + newState);
17997                }
17998            }
17999            if (className == null) {
18000                // We're dealing with an application/package level state change
18001                if (pkgSetting.getEnabled(userId) == newState) {
18002                    // Nothing to do
18003                    return;
18004                }
18005                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
18006                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
18007                    // Don't care about who enables an app.
18008                    callingPackage = null;
18009                }
18010                pkgSetting.setEnabled(newState, userId, callingPackage);
18011                // pkgSetting.pkg.mSetEnabled = newState;
18012            } else {
18013                // We're dealing with a component level state change
18014                // First, verify that this is a valid class name.
18015                PackageParser.Package pkg = pkgSetting.pkg;
18016                if (pkg == null || !pkg.hasComponentClassName(className)) {
18017                    if (pkg != null &&
18018                            pkg.applicationInfo.targetSdkVersion >=
18019                                    Build.VERSION_CODES.JELLY_BEAN) {
18020                        throw new IllegalArgumentException("Component class " + className
18021                                + " does not exist in " + packageName);
18022                    } else {
18023                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18024                                + className + " does not exist in " + packageName);
18025                    }
18026                }
18027                switch (newState) {
18028                case COMPONENT_ENABLED_STATE_ENABLED:
18029                    if (!pkgSetting.enableComponentLPw(className, userId)) {
18030                        return;
18031                    }
18032                    break;
18033                case COMPONENT_ENABLED_STATE_DISABLED:
18034                    if (!pkgSetting.disableComponentLPw(className, userId)) {
18035                        return;
18036                    }
18037                    break;
18038                case COMPONENT_ENABLED_STATE_DEFAULT:
18039                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
18040                        return;
18041                    }
18042                    break;
18043                default:
18044                    Slog.e(TAG, "Invalid new component state: " + newState);
18045                    return;
18046                }
18047            }
18048            scheduleWritePackageRestrictionsLocked(userId);
18049            components = mPendingBroadcasts.get(userId, packageName);
18050            final boolean newPackage = components == null;
18051            if (newPackage) {
18052                components = new ArrayList<String>();
18053            }
18054            if (!components.contains(componentName)) {
18055                components.add(componentName);
18056            }
18057            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18058                sendNow = true;
18059                // Purge entry from pending broadcast list if another one exists already
18060                // since we are sending one right away.
18061                mPendingBroadcasts.remove(userId, packageName);
18062            } else {
18063                if (newPackage) {
18064                    mPendingBroadcasts.put(userId, packageName, components);
18065                }
18066                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18067                    // Schedule a message
18068                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18069                }
18070            }
18071        }
18072
18073        long callingId = Binder.clearCallingIdentity();
18074        try {
18075            if (sendNow) {
18076                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18077                sendPackageChangedBroadcast(packageName,
18078                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18079            }
18080        } finally {
18081            Binder.restoreCallingIdentity(callingId);
18082        }
18083    }
18084
18085    @Override
18086    public void flushPackageRestrictionsAsUser(int userId) {
18087        if (!sUserManager.exists(userId)) {
18088            return;
18089        }
18090        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18091                false /* checkShell */, "flushPackageRestrictions");
18092        synchronized (mPackages) {
18093            mSettings.writePackageRestrictionsLPr(userId);
18094            mDirtyUsers.remove(userId);
18095            if (mDirtyUsers.isEmpty()) {
18096                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18097            }
18098        }
18099    }
18100
18101    private void sendPackageChangedBroadcast(String packageName,
18102            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18103        if (DEBUG_INSTALL)
18104            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18105                    + componentNames);
18106        Bundle extras = new Bundle(4);
18107        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18108        String nameList[] = new String[componentNames.size()];
18109        componentNames.toArray(nameList);
18110        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18111        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18112        extras.putInt(Intent.EXTRA_UID, packageUid);
18113        // If this is not reporting a change of the overall package, then only send it
18114        // to registered receivers.  We don't want to launch a swath of apps for every
18115        // little component state change.
18116        final int flags = !componentNames.contains(packageName)
18117                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18118        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18119                new int[] {UserHandle.getUserId(packageUid)});
18120    }
18121
18122    @Override
18123    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18124        if (!sUserManager.exists(userId)) return;
18125        final int uid = Binder.getCallingUid();
18126        final int permission = mContext.checkCallingOrSelfPermission(
18127                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18128        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18129        enforceCrossUserPermission(uid, userId,
18130                true /* requireFullPermission */, true /* checkShell */, "stop package");
18131        // writer
18132        synchronized (mPackages) {
18133            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18134                    allowedByPermission, uid, userId)) {
18135                scheduleWritePackageRestrictionsLocked(userId);
18136            }
18137        }
18138    }
18139
18140    @Override
18141    public String getInstallerPackageName(String packageName) {
18142        // reader
18143        synchronized (mPackages) {
18144            return mSettings.getInstallerPackageNameLPr(packageName);
18145        }
18146    }
18147
18148    public boolean isOrphaned(String packageName) {
18149        // reader
18150        synchronized (mPackages) {
18151            return mSettings.isOrphaned(packageName);
18152        }
18153    }
18154
18155    @Override
18156    public int getApplicationEnabledSetting(String packageName, int userId) {
18157        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18158        int uid = Binder.getCallingUid();
18159        enforceCrossUserPermission(uid, userId,
18160                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18161        // reader
18162        synchronized (mPackages) {
18163            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18164        }
18165    }
18166
18167    @Override
18168    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18169        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18170        int uid = Binder.getCallingUid();
18171        enforceCrossUserPermission(uid, userId,
18172                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18173        // reader
18174        synchronized (mPackages) {
18175            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18176        }
18177    }
18178
18179    @Override
18180    public void enterSafeMode() {
18181        enforceSystemOrRoot("Only the system can request entering safe mode");
18182
18183        if (!mSystemReady) {
18184            mSafeMode = true;
18185        }
18186    }
18187
18188    @Override
18189    public void systemReady() {
18190        mSystemReady = true;
18191
18192        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18193        // disabled after already being started.
18194        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18195                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18196
18197        // Read the compatibilty setting when the system is ready.
18198        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18199                mContext.getContentResolver(),
18200                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18201        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18202        if (DEBUG_SETTINGS) {
18203            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18204        }
18205
18206        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18207
18208        synchronized (mPackages) {
18209            // Verify that all of the preferred activity components actually
18210            // exist.  It is possible for applications to be updated and at
18211            // that point remove a previously declared activity component that
18212            // had been set as a preferred activity.  We try to clean this up
18213            // the next time we encounter that preferred activity, but it is
18214            // possible for the user flow to never be able to return to that
18215            // situation so here we do a sanity check to make sure we haven't
18216            // left any junk around.
18217            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18218            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18219                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18220                removed.clear();
18221                for (PreferredActivity pa : pir.filterSet()) {
18222                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18223                        removed.add(pa);
18224                    }
18225                }
18226                if (removed.size() > 0) {
18227                    for (int r=0; r<removed.size(); r++) {
18228                        PreferredActivity pa = removed.get(r);
18229                        Slog.w(TAG, "Removing dangling preferred activity: "
18230                                + pa.mPref.mComponent);
18231                        pir.removeFilter(pa);
18232                    }
18233                    mSettings.writePackageRestrictionsLPr(
18234                            mSettings.mPreferredActivities.keyAt(i));
18235                }
18236            }
18237
18238            for (int userId : UserManagerService.getInstance().getUserIds()) {
18239                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18240                    grantPermissionsUserIds = ArrayUtils.appendInt(
18241                            grantPermissionsUserIds, userId);
18242                }
18243            }
18244        }
18245        sUserManager.systemReady();
18246
18247        // If we upgraded grant all default permissions before kicking off.
18248        for (int userId : grantPermissionsUserIds) {
18249            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18250        }
18251
18252        // If we did not grant default permissions, we preload from this the
18253        // default permission exceptions lazily to ensure we don't hit the
18254        // disk on a new user creation.
18255        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18256            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18257        }
18258
18259        // Kick off any messages waiting for system ready
18260        if (mPostSystemReadyMessages != null) {
18261            for (Message msg : mPostSystemReadyMessages) {
18262                msg.sendToTarget();
18263            }
18264            mPostSystemReadyMessages = null;
18265        }
18266
18267        // Watch for external volumes that come and go over time
18268        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18269        storage.registerListener(mStorageListener);
18270
18271        mInstallerService.systemReady();
18272        mPackageDexOptimizer.systemReady();
18273
18274        MountServiceInternal mountServiceInternal = LocalServices.getService(
18275                MountServiceInternal.class);
18276        mountServiceInternal.addExternalStoragePolicy(
18277                new MountServiceInternal.ExternalStorageMountPolicy() {
18278            @Override
18279            public int getMountMode(int uid, String packageName) {
18280                if (Process.isIsolated(uid)) {
18281                    return Zygote.MOUNT_EXTERNAL_NONE;
18282                }
18283                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18284                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18285                }
18286                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18287                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18288                }
18289                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18290                    return Zygote.MOUNT_EXTERNAL_READ;
18291                }
18292                return Zygote.MOUNT_EXTERNAL_WRITE;
18293            }
18294
18295            @Override
18296            public boolean hasExternalStorage(int uid, String packageName) {
18297                return true;
18298            }
18299        });
18300
18301        // Now that we're mostly running, clean up stale users and apps
18302        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18303        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18304    }
18305
18306    @Override
18307    public boolean isSafeMode() {
18308        return mSafeMode;
18309    }
18310
18311    @Override
18312    public boolean hasSystemUidErrors() {
18313        return mHasSystemUidErrors;
18314    }
18315
18316    static String arrayToString(int[] array) {
18317        StringBuffer buf = new StringBuffer(128);
18318        buf.append('[');
18319        if (array != null) {
18320            for (int i=0; i<array.length; i++) {
18321                if (i > 0) buf.append(", ");
18322                buf.append(array[i]);
18323            }
18324        }
18325        buf.append(']');
18326        return buf.toString();
18327    }
18328
18329    static class DumpState {
18330        public static final int DUMP_LIBS = 1 << 0;
18331        public static final int DUMP_FEATURES = 1 << 1;
18332        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18333        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18334        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18335        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18336        public static final int DUMP_PERMISSIONS = 1 << 6;
18337        public static final int DUMP_PACKAGES = 1 << 7;
18338        public static final int DUMP_SHARED_USERS = 1 << 8;
18339        public static final int DUMP_MESSAGES = 1 << 9;
18340        public static final int DUMP_PROVIDERS = 1 << 10;
18341        public static final int DUMP_VERIFIERS = 1 << 11;
18342        public static final int DUMP_PREFERRED = 1 << 12;
18343        public static final int DUMP_PREFERRED_XML = 1 << 13;
18344        public static final int DUMP_KEYSETS = 1 << 14;
18345        public static final int DUMP_VERSION = 1 << 15;
18346        public static final int DUMP_INSTALLS = 1 << 16;
18347        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18348        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18349        public static final int DUMP_FROZEN = 1 << 19;
18350        public static final int DUMP_DEXOPT = 1 << 20;
18351        public static final int DUMP_COMPILER_STATS = 1 << 21;
18352
18353        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18354
18355        private int mTypes;
18356
18357        private int mOptions;
18358
18359        private boolean mTitlePrinted;
18360
18361        private SharedUserSetting mSharedUser;
18362
18363        public boolean isDumping(int type) {
18364            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18365                return true;
18366            }
18367
18368            return (mTypes & type) != 0;
18369        }
18370
18371        public void setDump(int type) {
18372            mTypes |= type;
18373        }
18374
18375        public boolean isOptionEnabled(int option) {
18376            return (mOptions & option) != 0;
18377        }
18378
18379        public void setOptionEnabled(int option) {
18380            mOptions |= option;
18381        }
18382
18383        public boolean onTitlePrinted() {
18384            final boolean printed = mTitlePrinted;
18385            mTitlePrinted = true;
18386            return printed;
18387        }
18388
18389        public boolean getTitlePrinted() {
18390            return mTitlePrinted;
18391        }
18392
18393        public void setTitlePrinted(boolean enabled) {
18394            mTitlePrinted = enabled;
18395        }
18396
18397        public SharedUserSetting getSharedUser() {
18398            return mSharedUser;
18399        }
18400
18401        public void setSharedUser(SharedUserSetting user) {
18402            mSharedUser = user;
18403        }
18404    }
18405
18406    @Override
18407    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18408            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18409        (new PackageManagerShellCommand(this)).exec(
18410                this, in, out, err, args, resultReceiver);
18411    }
18412
18413    @Override
18414    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18415        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18416                != PackageManager.PERMISSION_GRANTED) {
18417            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18418                    + Binder.getCallingPid()
18419                    + ", uid=" + Binder.getCallingUid()
18420                    + " without permission "
18421                    + android.Manifest.permission.DUMP);
18422            return;
18423        }
18424
18425        DumpState dumpState = new DumpState();
18426        boolean fullPreferred = false;
18427        boolean checkin = false;
18428
18429        String packageName = null;
18430        ArraySet<String> permissionNames = null;
18431
18432        int opti = 0;
18433        while (opti < args.length) {
18434            String opt = args[opti];
18435            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18436                break;
18437            }
18438            opti++;
18439
18440            if ("-a".equals(opt)) {
18441                // Right now we only know how to print all.
18442            } else if ("-h".equals(opt)) {
18443                pw.println("Package manager dump options:");
18444                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18445                pw.println("    --checkin: dump for a checkin");
18446                pw.println("    -f: print details of intent filters");
18447                pw.println("    -h: print this help");
18448                pw.println("  cmd may be one of:");
18449                pw.println("    l[ibraries]: list known shared libraries");
18450                pw.println("    f[eatures]: list device features");
18451                pw.println("    k[eysets]: print known keysets");
18452                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18453                pw.println("    perm[issions]: dump permissions");
18454                pw.println("    permission [name ...]: dump declaration and use of given permission");
18455                pw.println("    pref[erred]: print preferred package settings");
18456                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18457                pw.println("    prov[iders]: dump content providers");
18458                pw.println("    p[ackages]: dump installed packages");
18459                pw.println("    s[hared-users]: dump shared user IDs");
18460                pw.println("    m[essages]: print collected runtime messages");
18461                pw.println("    v[erifiers]: print package verifier info");
18462                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18463                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18464                pw.println("    version: print database version info");
18465                pw.println("    write: write current settings now");
18466                pw.println("    installs: details about install sessions");
18467                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18468                pw.println("    dexopt: dump dexopt state");
18469                pw.println("    compiler-stats: dump compiler statistics");
18470                pw.println("    <package.name>: info about given package");
18471                return;
18472            } else if ("--checkin".equals(opt)) {
18473                checkin = true;
18474            } else if ("-f".equals(opt)) {
18475                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18476            } else {
18477                pw.println("Unknown argument: " + opt + "; use -h for help");
18478            }
18479        }
18480
18481        // Is the caller requesting to dump a particular piece of data?
18482        if (opti < args.length) {
18483            String cmd = args[opti];
18484            opti++;
18485            // Is this a package name?
18486            if ("android".equals(cmd) || cmd.contains(".")) {
18487                packageName = cmd;
18488                // When dumping a single package, we always dump all of its
18489                // filter information since the amount of data will be reasonable.
18490                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18491            } else if ("check-permission".equals(cmd)) {
18492                if (opti >= args.length) {
18493                    pw.println("Error: check-permission missing permission argument");
18494                    return;
18495                }
18496                String perm = args[opti];
18497                opti++;
18498                if (opti >= args.length) {
18499                    pw.println("Error: check-permission missing package argument");
18500                    return;
18501                }
18502                String pkg = args[opti];
18503                opti++;
18504                int user = UserHandle.getUserId(Binder.getCallingUid());
18505                if (opti < args.length) {
18506                    try {
18507                        user = Integer.parseInt(args[opti]);
18508                    } catch (NumberFormatException e) {
18509                        pw.println("Error: check-permission user argument is not a number: "
18510                                + args[opti]);
18511                        return;
18512                    }
18513                }
18514                pw.println(checkPermission(perm, pkg, user));
18515                return;
18516            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18517                dumpState.setDump(DumpState.DUMP_LIBS);
18518            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18519                dumpState.setDump(DumpState.DUMP_FEATURES);
18520            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18521                if (opti >= args.length) {
18522                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18523                            | DumpState.DUMP_SERVICE_RESOLVERS
18524                            | DumpState.DUMP_RECEIVER_RESOLVERS
18525                            | DumpState.DUMP_CONTENT_RESOLVERS);
18526                } else {
18527                    while (opti < args.length) {
18528                        String name = args[opti];
18529                        if ("a".equals(name) || "activity".equals(name)) {
18530                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18531                        } else if ("s".equals(name) || "service".equals(name)) {
18532                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18533                        } else if ("r".equals(name) || "receiver".equals(name)) {
18534                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18535                        } else if ("c".equals(name) || "content".equals(name)) {
18536                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18537                        } else {
18538                            pw.println("Error: unknown resolver table type: " + name);
18539                            return;
18540                        }
18541                        opti++;
18542                    }
18543                }
18544            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18545                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18546            } else if ("permission".equals(cmd)) {
18547                if (opti >= args.length) {
18548                    pw.println("Error: permission requires permission name");
18549                    return;
18550                }
18551                permissionNames = new ArraySet<>();
18552                while (opti < args.length) {
18553                    permissionNames.add(args[opti]);
18554                    opti++;
18555                }
18556                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18557                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18558            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18559                dumpState.setDump(DumpState.DUMP_PREFERRED);
18560            } else if ("preferred-xml".equals(cmd)) {
18561                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18562                if (opti < args.length && "--full".equals(args[opti])) {
18563                    fullPreferred = true;
18564                    opti++;
18565                }
18566            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18567                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18568            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18569                dumpState.setDump(DumpState.DUMP_PACKAGES);
18570            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18571                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18572            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18573                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18574            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18575                dumpState.setDump(DumpState.DUMP_MESSAGES);
18576            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18577                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18578            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18579                    || "intent-filter-verifiers".equals(cmd)) {
18580                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18581            } else if ("version".equals(cmd)) {
18582                dumpState.setDump(DumpState.DUMP_VERSION);
18583            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18584                dumpState.setDump(DumpState.DUMP_KEYSETS);
18585            } else if ("installs".equals(cmd)) {
18586                dumpState.setDump(DumpState.DUMP_INSTALLS);
18587            } else if ("frozen".equals(cmd)) {
18588                dumpState.setDump(DumpState.DUMP_FROZEN);
18589            } else if ("dexopt".equals(cmd)) {
18590                dumpState.setDump(DumpState.DUMP_DEXOPT);
18591            } else if ("compiler-stats".equals(cmd)) {
18592                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18593            } else if ("write".equals(cmd)) {
18594                synchronized (mPackages) {
18595                    mSettings.writeLPr();
18596                    pw.println("Settings written.");
18597                    return;
18598                }
18599            }
18600        }
18601
18602        if (checkin) {
18603            pw.println("vers,1");
18604        }
18605
18606        // reader
18607        synchronized (mPackages) {
18608            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18609                if (!checkin) {
18610                    if (dumpState.onTitlePrinted())
18611                        pw.println();
18612                    pw.println("Database versions:");
18613                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18614                }
18615            }
18616
18617            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18618                if (!checkin) {
18619                    if (dumpState.onTitlePrinted())
18620                        pw.println();
18621                    pw.println("Verifiers:");
18622                    pw.print("  Required: ");
18623                    pw.print(mRequiredVerifierPackage);
18624                    pw.print(" (uid=");
18625                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18626                            UserHandle.USER_SYSTEM));
18627                    pw.println(")");
18628                } else if (mRequiredVerifierPackage != null) {
18629                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18630                    pw.print(",");
18631                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18632                            UserHandle.USER_SYSTEM));
18633                }
18634            }
18635
18636            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18637                    packageName == null) {
18638                if (mIntentFilterVerifierComponent != null) {
18639                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18640                    if (!checkin) {
18641                        if (dumpState.onTitlePrinted())
18642                            pw.println();
18643                        pw.println("Intent Filter Verifier:");
18644                        pw.print("  Using: ");
18645                        pw.print(verifierPackageName);
18646                        pw.print(" (uid=");
18647                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18648                                UserHandle.USER_SYSTEM));
18649                        pw.println(")");
18650                    } else if (verifierPackageName != null) {
18651                        pw.print("ifv,"); pw.print(verifierPackageName);
18652                        pw.print(",");
18653                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18654                                UserHandle.USER_SYSTEM));
18655                    }
18656                } else {
18657                    pw.println();
18658                    pw.println("No Intent Filter Verifier available!");
18659                }
18660            }
18661
18662            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18663                boolean printedHeader = false;
18664                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18665                while (it.hasNext()) {
18666                    String name = it.next();
18667                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18668                    if (!checkin) {
18669                        if (!printedHeader) {
18670                            if (dumpState.onTitlePrinted())
18671                                pw.println();
18672                            pw.println("Libraries:");
18673                            printedHeader = true;
18674                        }
18675                        pw.print("  ");
18676                    } else {
18677                        pw.print("lib,");
18678                    }
18679                    pw.print(name);
18680                    if (!checkin) {
18681                        pw.print(" -> ");
18682                    }
18683                    if (ent.path != null) {
18684                        if (!checkin) {
18685                            pw.print("(jar) ");
18686                            pw.print(ent.path);
18687                        } else {
18688                            pw.print(",jar,");
18689                            pw.print(ent.path);
18690                        }
18691                    } else {
18692                        if (!checkin) {
18693                            pw.print("(apk) ");
18694                            pw.print(ent.apk);
18695                        } else {
18696                            pw.print(",apk,");
18697                            pw.print(ent.apk);
18698                        }
18699                    }
18700                    pw.println();
18701                }
18702            }
18703
18704            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18705                if (dumpState.onTitlePrinted())
18706                    pw.println();
18707                if (!checkin) {
18708                    pw.println("Features:");
18709                }
18710
18711                for (FeatureInfo feat : mAvailableFeatures.values()) {
18712                    if (checkin) {
18713                        pw.print("feat,");
18714                        pw.print(feat.name);
18715                        pw.print(",");
18716                        pw.println(feat.version);
18717                    } else {
18718                        pw.print("  ");
18719                        pw.print(feat.name);
18720                        if (feat.version > 0) {
18721                            pw.print(" version=");
18722                            pw.print(feat.version);
18723                        }
18724                        pw.println();
18725                    }
18726                }
18727            }
18728
18729            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18730                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18731                        : "Activity Resolver Table:", "  ", packageName,
18732                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18733                    dumpState.setTitlePrinted(true);
18734                }
18735            }
18736            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18737                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18738                        : "Receiver Resolver Table:", "  ", packageName,
18739                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18740                    dumpState.setTitlePrinted(true);
18741                }
18742            }
18743            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18744                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18745                        : "Service Resolver Table:", "  ", packageName,
18746                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18747                    dumpState.setTitlePrinted(true);
18748                }
18749            }
18750            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18751                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18752                        : "Provider Resolver Table:", "  ", packageName,
18753                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18754                    dumpState.setTitlePrinted(true);
18755                }
18756            }
18757
18758            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18759                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18760                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18761                    int user = mSettings.mPreferredActivities.keyAt(i);
18762                    if (pir.dump(pw,
18763                            dumpState.getTitlePrinted()
18764                                ? "\nPreferred Activities User " + user + ":"
18765                                : "Preferred Activities User " + user + ":", "  ",
18766                            packageName, true, false)) {
18767                        dumpState.setTitlePrinted(true);
18768                    }
18769                }
18770            }
18771
18772            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18773                pw.flush();
18774                FileOutputStream fout = new FileOutputStream(fd);
18775                BufferedOutputStream str = new BufferedOutputStream(fout);
18776                XmlSerializer serializer = new FastXmlSerializer();
18777                try {
18778                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18779                    serializer.startDocument(null, true);
18780                    serializer.setFeature(
18781                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18782                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18783                    serializer.endDocument();
18784                    serializer.flush();
18785                } catch (IllegalArgumentException e) {
18786                    pw.println("Failed writing: " + e);
18787                } catch (IllegalStateException e) {
18788                    pw.println("Failed writing: " + e);
18789                } catch (IOException e) {
18790                    pw.println("Failed writing: " + e);
18791                }
18792            }
18793
18794            if (!checkin
18795                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18796                    && packageName == null) {
18797                pw.println();
18798                int count = mSettings.mPackages.size();
18799                if (count == 0) {
18800                    pw.println("No applications!");
18801                    pw.println();
18802                } else {
18803                    final String prefix = "  ";
18804                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18805                    if (allPackageSettings.size() == 0) {
18806                        pw.println("No domain preferred apps!");
18807                        pw.println();
18808                    } else {
18809                        pw.println("App verification status:");
18810                        pw.println();
18811                        count = 0;
18812                        for (PackageSetting ps : allPackageSettings) {
18813                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18814                            if (ivi == null || ivi.getPackageName() == null) continue;
18815                            pw.println(prefix + "Package: " + ivi.getPackageName());
18816                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18817                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18818                            pw.println();
18819                            count++;
18820                        }
18821                        if (count == 0) {
18822                            pw.println(prefix + "No app verification established.");
18823                            pw.println();
18824                        }
18825                        for (int userId : sUserManager.getUserIds()) {
18826                            pw.println("App linkages for user " + userId + ":");
18827                            pw.println();
18828                            count = 0;
18829                            for (PackageSetting ps : allPackageSettings) {
18830                                final long status = ps.getDomainVerificationStatusForUser(userId);
18831                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18832                                    continue;
18833                                }
18834                                pw.println(prefix + "Package: " + ps.name);
18835                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18836                                String statusStr = IntentFilterVerificationInfo.
18837                                        getStatusStringFromValue(status);
18838                                pw.println(prefix + "Status:  " + statusStr);
18839                                pw.println();
18840                                count++;
18841                            }
18842                            if (count == 0) {
18843                                pw.println(prefix + "No configured app linkages.");
18844                                pw.println();
18845                            }
18846                        }
18847                    }
18848                }
18849            }
18850
18851            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18852                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18853                if (packageName == null && permissionNames == null) {
18854                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18855                        if (iperm == 0) {
18856                            if (dumpState.onTitlePrinted())
18857                                pw.println();
18858                            pw.println("AppOp Permissions:");
18859                        }
18860                        pw.print("  AppOp Permission ");
18861                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18862                        pw.println(":");
18863                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18864                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18865                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18866                        }
18867                    }
18868                }
18869            }
18870
18871            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18872                boolean printedSomething = false;
18873                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18874                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18875                        continue;
18876                    }
18877                    if (!printedSomething) {
18878                        if (dumpState.onTitlePrinted())
18879                            pw.println();
18880                        pw.println("Registered ContentProviders:");
18881                        printedSomething = true;
18882                    }
18883                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18884                    pw.print("    "); pw.println(p.toString());
18885                }
18886                printedSomething = false;
18887                for (Map.Entry<String, PackageParser.Provider> entry :
18888                        mProvidersByAuthority.entrySet()) {
18889                    PackageParser.Provider p = entry.getValue();
18890                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18891                        continue;
18892                    }
18893                    if (!printedSomething) {
18894                        if (dumpState.onTitlePrinted())
18895                            pw.println();
18896                        pw.println("ContentProvider Authorities:");
18897                        printedSomething = true;
18898                    }
18899                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18900                    pw.print("    "); pw.println(p.toString());
18901                    if (p.info != null && p.info.applicationInfo != null) {
18902                        final String appInfo = p.info.applicationInfo.toString();
18903                        pw.print("      applicationInfo="); pw.println(appInfo);
18904                    }
18905                }
18906            }
18907
18908            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18909                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18910            }
18911
18912            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18913                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18914            }
18915
18916            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18917                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18918            }
18919
18920            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18921                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18922            }
18923
18924            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18925                // XXX should handle packageName != null by dumping only install data that
18926                // the given package is involved with.
18927                if (dumpState.onTitlePrinted()) pw.println();
18928                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18929            }
18930
18931            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18932                // XXX should handle packageName != null by dumping only install data that
18933                // the given package is involved with.
18934                if (dumpState.onTitlePrinted()) pw.println();
18935
18936                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18937                ipw.println();
18938                ipw.println("Frozen packages:");
18939                ipw.increaseIndent();
18940                if (mFrozenPackages.size() == 0) {
18941                    ipw.println("(none)");
18942                } else {
18943                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18944                        ipw.println(mFrozenPackages.valueAt(i));
18945                    }
18946                }
18947                ipw.decreaseIndent();
18948            }
18949
18950            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18951                if (dumpState.onTitlePrinted()) pw.println();
18952                dumpDexoptStateLPr(pw, packageName);
18953            }
18954
18955            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
18956                if (dumpState.onTitlePrinted()) pw.println();
18957                dumpCompilerStatsLPr(pw, packageName);
18958            }
18959
18960            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18961                if (dumpState.onTitlePrinted()) pw.println();
18962                mSettings.dumpReadMessagesLPr(pw, dumpState);
18963
18964                pw.println();
18965                pw.println("Package warning messages:");
18966                BufferedReader in = null;
18967                String line = null;
18968                try {
18969                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18970                    while ((line = in.readLine()) != null) {
18971                        if (line.contains("ignored: updated version")) continue;
18972                        pw.println(line);
18973                    }
18974                } catch (IOException ignored) {
18975                } finally {
18976                    IoUtils.closeQuietly(in);
18977                }
18978            }
18979
18980            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18981                BufferedReader in = null;
18982                String line = null;
18983                try {
18984                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18985                    while ((line = in.readLine()) != null) {
18986                        if (line.contains("ignored: updated version")) continue;
18987                        pw.print("msg,");
18988                        pw.println(line);
18989                    }
18990                } catch (IOException ignored) {
18991                } finally {
18992                    IoUtils.closeQuietly(in);
18993                }
18994            }
18995        }
18996    }
18997
18998    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18999        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19000        ipw.println();
19001        ipw.println("Dexopt state:");
19002        ipw.increaseIndent();
19003        Collection<PackageParser.Package> packages = null;
19004        if (packageName != null) {
19005            PackageParser.Package targetPackage = mPackages.get(packageName);
19006            if (targetPackage != null) {
19007                packages = Collections.singletonList(targetPackage);
19008            } else {
19009                ipw.println("Unable to find package: " + packageName);
19010                return;
19011            }
19012        } else {
19013            packages = mPackages.values();
19014        }
19015
19016        for (PackageParser.Package pkg : packages) {
19017            ipw.println("[" + pkg.packageName + "]");
19018            ipw.increaseIndent();
19019            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19020            ipw.decreaseIndent();
19021        }
19022    }
19023
19024    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19025        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19026        ipw.println();
19027        ipw.println("Compiler stats:");
19028        ipw.increaseIndent();
19029        Collection<PackageParser.Package> packages = null;
19030        if (packageName != null) {
19031            PackageParser.Package targetPackage = mPackages.get(packageName);
19032            if (targetPackage != null) {
19033                packages = Collections.singletonList(targetPackage);
19034            } else {
19035                ipw.println("Unable to find package: " + packageName);
19036                return;
19037            }
19038        } else {
19039            packages = mPackages.values();
19040        }
19041
19042        for (PackageParser.Package pkg : packages) {
19043            ipw.println("[" + pkg.packageName + "]");
19044            ipw.increaseIndent();
19045
19046            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19047            if (stats == null) {
19048                ipw.println("(No recorded stats)");
19049            } else {
19050                stats.dump(ipw);
19051            }
19052            ipw.decreaseIndent();
19053        }
19054    }
19055
19056    private String dumpDomainString(String packageName) {
19057        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19058                .getList();
19059        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19060
19061        ArraySet<String> result = new ArraySet<>();
19062        if (iviList.size() > 0) {
19063            for (IntentFilterVerificationInfo ivi : iviList) {
19064                for (String host : ivi.getDomains()) {
19065                    result.add(host);
19066                }
19067            }
19068        }
19069        if (filters != null && filters.size() > 0) {
19070            for (IntentFilter filter : filters) {
19071                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19072                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19073                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19074                    result.addAll(filter.getHostsList());
19075                }
19076            }
19077        }
19078
19079        StringBuilder sb = new StringBuilder(result.size() * 16);
19080        for (String domain : result) {
19081            if (sb.length() > 0) sb.append(" ");
19082            sb.append(domain);
19083        }
19084        return sb.toString();
19085    }
19086
19087    // ------- apps on sdcard specific code -------
19088    static final boolean DEBUG_SD_INSTALL = false;
19089
19090    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19091
19092    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19093
19094    private boolean mMediaMounted = false;
19095
19096    static String getEncryptKey() {
19097        try {
19098            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19099                    SD_ENCRYPTION_KEYSTORE_NAME);
19100            if (sdEncKey == null) {
19101                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19102                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19103                if (sdEncKey == null) {
19104                    Slog.e(TAG, "Failed to create encryption keys");
19105                    return null;
19106                }
19107            }
19108            return sdEncKey;
19109        } catch (NoSuchAlgorithmException nsae) {
19110            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19111            return null;
19112        } catch (IOException ioe) {
19113            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19114            return null;
19115        }
19116    }
19117
19118    /*
19119     * Update media status on PackageManager.
19120     */
19121    @Override
19122    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19123        int callingUid = Binder.getCallingUid();
19124        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19125            throw new SecurityException("Media status can only be updated by the system");
19126        }
19127        // reader; this apparently protects mMediaMounted, but should probably
19128        // be a different lock in that case.
19129        synchronized (mPackages) {
19130            Log.i(TAG, "Updating external media status from "
19131                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19132                    + (mediaStatus ? "mounted" : "unmounted"));
19133            if (DEBUG_SD_INSTALL)
19134                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19135                        + ", mMediaMounted=" + mMediaMounted);
19136            if (mediaStatus == mMediaMounted) {
19137                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19138                        : 0, -1);
19139                mHandler.sendMessage(msg);
19140                return;
19141            }
19142            mMediaMounted = mediaStatus;
19143        }
19144        // Queue up an async operation since the package installation may take a
19145        // little while.
19146        mHandler.post(new Runnable() {
19147            public void run() {
19148                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19149            }
19150        });
19151    }
19152
19153    /**
19154     * Called by MountService when the initial ASECs to scan are available.
19155     * Should block until all the ASEC containers are finished being scanned.
19156     */
19157    public void scanAvailableAsecs() {
19158        updateExternalMediaStatusInner(true, false, false);
19159    }
19160
19161    /*
19162     * Collect information of applications on external media, map them against
19163     * existing containers and update information based on current mount status.
19164     * Please note that we always have to report status if reportStatus has been
19165     * set to true especially when unloading packages.
19166     */
19167    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19168            boolean externalStorage) {
19169        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19170        int[] uidArr = EmptyArray.INT;
19171
19172        final String[] list = PackageHelper.getSecureContainerList();
19173        if (ArrayUtils.isEmpty(list)) {
19174            Log.i(TAG, "No secure containers found");
19175        } else {
19176            // Process list of secure containers and categorize them
19177            // as active or stale based on their package internal state.
19178
19179            // reader
19180            synchronized (mPackages) {
19181                for (String cid : list) {
19182                    // Leave stages untouched for now; installer service owns them
19183                    if (PackageInstallerService.isStageName(cid)) continue;
19184
19185                    if (DEBUG_SD_INSTALL)
19186                        Log.i(TAG, "Processing container " + cid);
19187                    String pkgName = getAsecPackageName(cid);
19188                    if (pkgName == null) {
19189                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19190                        continue;
19191                    }
19192                    if (DEBUG_SD_INSTALL)
19193                        Log.i(TAG, "Looking for pkg : " + pkgName);
19194
19195                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19196                    if (ps == null) {
19197                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19198                        continue;
19199                    }
19200
19201                    /*
19202                     * Skip packages that are not external if we're unmounting
19203                     * external storage.
19204                     */
19205                    if (externalStorage && !isMounted && !isExternal(ps)) {
19206                        continue;
19207                    }
19208
19209                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19210                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19211                    // The package status is changed only if the code path
19212                    // matches between settings and the container id.
19213                    if (ps.codePathString != null
19214                            && ps.codePathString.startsWith(args.getCodePath())) {
19215                        if (DEBUG_SD_INSTALL) {
19216                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19217                                    + " at code path: " + ps.codePathString);
19218                        }
19219
19220                        // We do have a valid package installed on sdcard
19221                        processCids.put(args, ps.codePathString);
19222                        final int uid = ps.appId;
19223                        if (uid != -1) {
19224                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19225                        }
19226                    } else {
19227                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19228                                + ps.codePathString);
19229                    }
19230                }
19231            }
19232
19233            Arrays.sort(uidArr);
19234        }
19235
19236        // Process packages with valid entries.
19237        if (isMounted) {
19238            if (DEBUG_SD_INSTALL)
19239                Log.i(TAG, "Loading packages");
19240            loadMediaPackages(processCids, uidArr, externalStorage);
19241            startCleaningPackages();
19242            mInstallerService.onSecureContainersAvailable();
19243        } else {
19244            if (DEBUG_SD_INSTALL)
19245                Log.i(TAG, "Unloading packages");
19246            unloadMediaPackages(processCids, uidArr, reportStatus);
19247        }
19248    }
19249
19250    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19251            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19252        final int size = infos.size();
19253        final String[] packageNames = new String[size];
19254        final int[] packageUids = new int[size];
19255        for (int i = 0; i < size; i++) {
19256            final ApplicationInfo info = infos.get(i);
19257            packageNames[i] = info.packageName;
19258            packageUids[i] = info.uid;
19259        }
19260        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19261                finishedReceiver);
19262    }
19263
19264    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19265            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19266        sendResourcesChangedBroadcast(mediaStatus, replacing,
19267                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19268    }
19269
19270    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19271            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19272        int size = pkgList.length;
19273        if (size > 0) {
19274            // Send broadcasts here
19275            Bundle extras = new Bundle();
19276            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19277            if (uidArr != null) {
19278                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19279            }
19280            if (replacing) {
19281                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19282            }
19283            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19284                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19285            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19286        }
19287    }
19288
19289   /*
19290     * Look at potentially valid container ids from processCids If package
19291     * information doesn't match the one on record or package scanning fails,
19292     * the cid is added to list of removeCids. We currently don't delete stale
19293     * containers.
19294     */
19295    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19296            boolean externalStorage) {
19297        ArrayList<String> pkgList = new ArrayList<String>();
19298        Set<AsecInstallArgs> keys = processCids.keySet();
19299
19300        for (AsecInstallArgs args : keys) {
19301            String codePath = processCids.get(args);
19302            if (DEBUG_SD_INSTALL)
19303                Log.i(TAG, "Loading container : " + args.cid);
19304            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19305            try {
19306                // Make sure there are no container errors first.
19307                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19308                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19309                            + " when installing from sdcard");
19310                    continue;
19311                }
19312                // Check code path here.
19313                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19314                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19315                            + " does not match one in settings " + codePath);
19316                    continue;
19317                }
19318                // Parse package
19319                int parseFlags = mDefParseFlags;
19320                if (args.isExternalAsec()) {
19321                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19322                }
19323                if (args.isFwdLocked()) {
19324                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19325                }
19326
19327                synchronized (mInstallLock) {
19328                    PackageParser.Package pkg = null;
19329                    try {
19330                        // Sadly we don't know the package name yet to freeze it
19331                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19332                                SCAN_IGNORE_FROZEN, 0, null);
19333                    } catch (PackageManagerException e) {
19334                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19335                    }
19336                    // Scan the package
19337                    if (pkg != null) {
19338                        /*
19339                         * TODO why is the lock being held? doPostInstall is
19340                         * called in other places without the lock. This needs
19341                         * to be straightened out.
19342                         */
19343                        // writer
19344                        synchronized (mPackages) {
19345                            retCode = PackageManager.INSTALL_SUCCEEDED;
19346                            pkgList.add(pkg.packageName);
19347                            // Post process args
19348                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19349                                    pkg.applicationInfo.uid);
19350                        }
19351                    } else {
19352                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19353                    }
19354                }
19355
19356            } finally {
19357                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19358                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19359                }
19360            }
19361        }
19362        // writer
19363        synchronized (mPackages) {
19364            // If the platform SDK has changed since the last time we booted,
19365            // we need to re-grant app permission to catch any new ones that
19366            // appear. This is really a hack, and means that apps can in some
19367            // cases get permissions that the user didn't initially explicitly
19368            // allow... it would be nice to have some better way to handle
19369            // this situation.
19370            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19371                    : mSettings.getInternalVersion();
19372            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19373                    : StorageManager.UUID_PRIVATE_INTERNAL;
19374
19375            int updateFlags = UPDATE_PERMISSIONS_ALL;
19376            if (ver.sdkVersion != mSdkVersion) {
19377                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19378                        + mSdkVersion + "; regranting permissions for external");
19379                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19380            }
19381            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19382
19383            // Yay, everything is now upgraded
19384            ver.forceCurrent();
19385
19386            // can downgrade to reader
19387            // Persist settings
19388            mSettings.writeLPr();
19389        }
19390        // Send a broadcast to let everyone know we are done processing
19391        if (pkgList.size() > 0) {
19392            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19393        }
19394    }
19395
19396   /*
19397     * Utility method to unload a list of specified containers
19398     */
19399    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19400        // Just unmount all valid containers.
19401        for (AsecInstallArgs arg : cidArgs) {
19402            synchronized (mInstallLock) {
19403                arg.doPostDeleteLI(false);
19404           }
19405       }
19406   }
19407
19408    /*
19409     * Unload packages mounted on external media. This involves deleting package
19410     * data from internal structures, sending broadcasts about disabled packages,
19411     * gc'ing to free up references, unmounting all secure containers
19412     * corresponding to packages on external media, and posting a
19413     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19414     * that we always have to post this message if status has been requested no
19415     * matter what.
19416     */
19417    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19418            final boolean reportStatus) {
19419        if (DEBUG_SD_INSTALL)
19420            Log.i(TAG, "unloading media packages");
19421        ArrayList<String> pkgList = new ArrayList<String>();
19422        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19423        final Set<AsecInstallArgs> keys = processCids.keySet();
19424        for (AsecInstallArgs args : keys) {
19425            String pkgName = args.getPackageName();
19426            if (DEBUG_SD_INSTALL)
19427                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19428            // Delete package internally
19429            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19430            synchronized (mInstallLock) {
19431                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19432                final boolean res;
19433                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19434                        "unloadMediaPackages")) {
19435                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19436                            null);
19437                }
19438                if (res) {
19439                    pkgList.add(pkgName);
19440                } else {
19441                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19442                    failedList.add(args);
19443                }
19444            }
19445        }
19446
19447        // reader
19448        synchronized (mPackages) {
19449            // We didn't update the settings after removing each package;
19450            // write them now for all packages.
19451            mSettings.writeLPr();
19452        }
19453
19454        // We have to absolutely send UPDATED_MEDIA_STATUS only
19455        // after confirming that all the receivers processed the ordered
19456        // broadcast when packages get disabled, force a gc to clean things up.
19457        // and unload all the containers.
19458        if (pkgList.size() > 0) {
19459            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19460                    new IIntentReceiver.Stub() {
19461                public void performReceive(Intent intent, int resultCode, String data,
19462                        Bundle extras, boolean ordered, boolean sticky,
19463                        int sendingUser) throws RemoteException {
19464                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19465                            reportStatus ? 1 : 0, 1, keys);
19466                    mHandler.sendMessage(msg);
19467                }
19468            });
19469        } else {
19470            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19471                    keys);
19472            mHandler.sendMessage(msg);
19473        }
19474    }
19475
19476    private void loadPrivatePackages(final VolumeInfo vol) {
19477        mHandler.post(new Runnable() {
19478            @Override
19479            public void run() {
19480                loadPrivatePackagesInner(vol);
19481            }
19482        });
19483    }
19484
19485    private void loadPrivatePackagesInner(VolumeInfo vol) {
19486        final String volumeUuid = vol.fsUuid;
19487        if (TextUtils.isEmpty(volumeUuid)) {
19488            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19489            return;
19490        }
19491
19492        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19493        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19494        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19495
19496        final VersionInfo ver;
19497        final List<PackageSetting> packages;
19498        synchronized (mPackages) {
19499            ver = mSettings.findOrCreateVersion(volumeUuid);
19500            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19501        }
19502
19503        for (PackageSetting ps : packages) {
19504            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19505            synchronized (mInstallLock) {
19506                final PackageParser.Package pkg;
19507                try {
19508                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19509                    loaded.add(pkg.applicationInfo);
19510
19511                } catch (PackageManagerException e) {
19512                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19513                }
19514
19515                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19516                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19517                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19518                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19519                }
19520            }
19521        }
19522
19523        // Reconcile app data for all started/unlocked users
19524        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19525        final UserManager um = mContext.getSystemService(UserManager.class);
19526        UserManagerInternal umInternal = getUserManagerInternal();
19527        for (UserInfo user : um.getUsers()) {
19528            final int flags;
19529            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19530                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19531            } else if (umInternal.isUserRunning(user.id)) {
19532                flags = StorageManager.FLAG_STORAGE_DE;
19533            } else {
19534                continue;
19535            }
19536
19537            try {
19538                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19539                synchronized (mInstallLock) {
19540                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19541                }
19542            } catch (IllegalStateException e) {
19543                // Device was probably ejected, and we'll process that event momentarily
19544                Slog.w(TAG, "Failed to prepare storage: " + e);
19545            }
19546        }
19547
19548        synchronized (mPackages) {
19549            int updateFlags = UPDATE_PERMISSIONS_ALL;
19550            if (ver.sdkVersion != mSdkVersion) {
19551                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19552                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19553                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19554            }
19555            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19556
19557            // Yay, everything is now upgraded
19558            ver.forceCurrent();
19559
19560            mSettings.writeLPr();
19561        }
19562
19563        for (PackageFreezer freezer : freezers) {
19564            freezer.close();
19565        }
19566
19567        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19568        sendResourcesChangedBroadcast(true, false, loaded, null);
19569    }
19570
19571    private void unloadPrivatePackages(final VolumeInfo vol) {
19572        mHandler.post(new Runnable() {
19573            @Override
19574            public void run() {
19575                unloadPrivatePackagesInner(vol);
19576            }
19577        });
19578    }
19579
19580    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19581        final String volumeUuid = vol.fsUuid;
19582        if (TextUtils.isEmpty(volumeUuid)) {
19583            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19584            return;
19585        }
19586
19587        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19588        synchronized (mInstallLock) {
19589        synchronized (mPackages) {
19590            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19591            for (PackageSetting ps : packages) {
19592                if (ps.pkg == null) continue;
19593
19594                final ApplicationInfo info = ps.pkg.applicationInfo;
19595                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19596                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19597
19598                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19599                        "unloadPrivatePackagesInner")) {
19600                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19601                            false, null)) {
19602                        unloaded.add(info);
19603                    } else {
19604                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19605                    }
19606                }
19607
19608                // Try very hard to release any references to this package
19609                // so we don't risk the system server being killed due to
19610                // open FDs
19611                AttributeCache.instance().removePackage(ps.name);
19612            }
19613
19614            mSettings.writeLPr();
19615        }
19616        }
19617
19618        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19619        sendResourcesChangedBroadcast(false, false, unloaded, null);
19620
19621        // Try very hard to release any references to this path so we don't risk
19622        // the system server being killed due to open FDs
19623        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19624
19625        for (int i = 0; i < 3; i++) {
19626            System.gc();
19627            System.runFinalization();
19628        }
19629    }
19630
19631    /**
19632     * Prepare storage areas for given user on all mounted devices.
19633     */
19634    void prepareUserData(int userId, int userSerial, int flags) {
19635        synchronized (mInstallLock) {
19636            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19637            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19638                final String volumeUuid = vol.getFsUuid();
19639                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19640            }
19641        }
19642    }
19643
19644    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19645            boolean allowRecover) {
19646        // Prepare storage and verify that serial numbers are consistent; if
19647        // there's a mismatch we need to destroy to avoid leaking data
19648        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19649        try {
19650            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19651
19652            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19653                UserManagerService.enforceSerialNumber(
19654                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19655                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19656                    UserManagerService.enforceSerialNumber(
19657                            Environment.getDataSystemDeDirectory(userId), userSerial);
19658                }
19659            }
19660            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19661                UserManagerService.enforceSerialNumber(
19662                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19663                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19664                    UserManagerService.enforceSerialNumber(
19665                            Environment.getDataSystemCeDirectory(userId), userSerial);
19666                }
19667            }
19668
19669            synchronized (mInstallLock) {
19670                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19671            }
19672        } catch (Exception e) {
19673            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19674                    + " because we failed to prepare: " + e);
19675            destroyUserDataLI(volumeUuid, userId,
19676                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19677
19678            if (allowRecover) {
19679                // Try one last time; if we fail again we're really in trouble
19680                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19681            }
19682        }
19683    }
19684
19685    /**
19686     * Destroy storage areas for given user on all mounted devices.
19687     */
19688    void destroyUserData(int userId, int flags) {
19689        synchronized (mInstallLock) {
19690            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19691            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19692                final String volumeUuid = vol.getFsUuid();
19693                destroyUserDataLI(volumeUuid, userId, flags);
19694            }
19695        }
19696    }
19697
19698    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19699        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19700        try {
19701            // Clean up app data, profile data, and media data
19702            mInstaller.destroyUserData(volumeUuid, userId, flags);
19703
19704            // Clean up system data
19705            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19706                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19707                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19708                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19709                }
19710                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19711                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19712                }
19713            }
19714
19715            // Data with special labels is now gone, so finish the job
19716            storage.destroyUserStorage(volumeUuid, userId, flags);
19717
19718        } catch (Exception e) {
19719            logCriticalInfo(Log.WARN,
19720                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19721        }
19722    }
19723
19724    /**
19725     * Examine all users present on given mounted volume, and destroy data
19726     * belonging to users that are no longer valid, or whose user ID has been
19727     * recycled.
19728     */
19729    private void reconcileUsers(String volumeUuid) {
19730        final List<File> files = new ArrayList<>();
19731        Collections.addAll(files, FileUtils
19732                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19733        Collections.addAll(files, FileUtils
19734                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19735        Collections.addAll(files, FileUtils
19736                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19737        Collections.addAll(files, FileUtils
19738                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19739        for (File file : files) {
19740            if (!file.isDirectory()) continue;
19741
19742            final int userId;
19743            final UserInfo info;
19744            try {
19745                userId = Integer.parseInt(file.getName());
19746                info = sUserManager.getUserInfo(userId);
19747            } catch (NumberFormatException e) {
19748                Slog.w(TAG, "Invalid user directory " + file);
19749                continue;
19750            }
19751
19752            boolean destroyUser = false;
19753            if (info == null) {
19754                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19755                        + " because no matching user was found");
19756                destroyUser = true;
19757            } else if (!mOnlyCore) {
19758                try {
19759                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19760                } catch (IOException e) {
19761                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19762                            + " because we failed to enforce serial number: " + e);
19763                    destroyUser = true;
19764                }
19765            }
19766
19767            if (destroyUser) {
19768                synchronized (mInstallLock) {
19769                    destroyUserDataLI(volumeUuid, userId,
19770                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19771                }
19772            }
19773        }
19774    }
19775
19776    private void assertPackageKnown(String volumeUuid, String packageName)
19777            throws PackageManagerException {
19778        synchronized (mPackages) {
19779            final PackageSetting ps = mSettings.mPackages.get(packageName);
19780            if (ps == null) {
19781                throw new PackageManagerException("Package " + packageName + " is unknown");
19782            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19783                throw new PackageManagerException(
19784                        "Package " + packageName + " found on unknown volume " + volumeUuid
19785                                + "; expected volume " + ps.volumeUuid);
19786            }
19787        }
19788    }
19789
19790    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19791            throws PackageManagerException {
19792        synchronized (mPackages) {
19793            final PackageSetting ps = mSettings.mPackages.get(packageName);
19794            if (ps == null) {
19795                throw new PackageManagerException("Package " + packageName + " is unknown");
19796            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19797                throw new PackageManagerException(
19798                        "Package " + packageName + " found on unknown volume " + volumeUuid
19799                                + "; expected volume " + ps.volumeUuid);
19800            } else if (!ps.getInstalled(userId)) {
19801                throw new PackageManagerException(
19802                        "Package " + packageName + " not installed for user " + userId);
19803            }
19804        }
19805    }
19806
19807    /**
19808     * Examine all apps present on given mounted volume, and destroy apps that
19809     * aren't expected, either due to uninstallation or reinstallation on
19810     * another volume.
19811     */
19812    private void reconcileApps(String volumeUuid) {
19813        final File[] files = FileUtils
19814                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19815        for (File file : files) {
19816            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19817                    && !PackageInstallerService.isStageName(file.getName());
19818            if (!isPackage) {
19819                // Ignore entries which are not packages
19820                continue;
19821            }
19822
19823            try {
19824                final PackageLite pkg = PackageParser.parsePackageLite(file,
19825                        PackageParser.PARSE_MUST_BE_APK);
19826                assertPackageKnown(volumeUuid, pkg.packageName);
19827
19828            } catch (PackageParserException | PackageManagerException e) {
19829                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19830                synchronized (mInstallLock) {
19831                    removeCodePathLI(file);
19832                }
19833            }
19834        }
19835    }
19836
19837    /**
19838     * Reconcile all app data for the given user.
19839     * <p>
19840     * Verifies that directories exist and that ownership and labeling is
19841     * correct for all installed apps on all mounted volumes.
19842     */
19843    void reconcileAppsData(int userId, int flags) {
19844        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19845        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19846            final String volumeUuid = vol.getFsUuid();
19847            synchronized (mInstallLock) {
19848                reconcileAppsDataLI(volumeUuid, userId, flags);
19849            }
19850        }
19851    }
19852
19853    /**
19854     * Reconcile all app data on given mounted volume.
19855     * <p>
19856     * Destroys app data that isn't expected, either due to uninstallation or
19857     * reinstallation on another volume.
19858     * <p>
19859     * Verifies that directories exist and that ownership and labeling is
19860     * correct for all installed apps.
19861     */
19862    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19863        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19864                + Integer.toHexString(flags));
19865
19866        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19867        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19868
19869        // First look for stale data that doesn't belong, and check if things
19870        // have changed since we did our last restorecon
19871        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19872            if (StorageManager.isFileEncryptedNativeOrEmulated()
19873                    && !StorageManager.isUserKeyUnlocked(userId)) {
19874                throw new RuntimeException(
19875                        "Yikes, someone asked us to reconcile CE storage while " + userId
19876                                + " was still locked; this would have caused massive data loss!");
19877            }
19878
19879            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19880            for (File file : files) {
19881                final String packageName = file.getName();
19882                try {
19883                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19884                } catch (PackageManagerException e) {
19885                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19886                    try {
19887                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19888                                StorageManager.FLAG_STORAGE_CE, 0);
19889                    } catch (InstallerException e2) {
19890                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19891                    }
19892                }
19893            }
19894        }
19895        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19896            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19897            for (File file : files) {
19898                final String packageName = file.getName();
19899                try {
19900                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19901                } catch (PackageManagerException e) {
19902                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19903                    try {
19904                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19905                                StorageManager.FLAG_STORAGE_DE, 0);
19906                    } catch (InstallerException e2) {
19907                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19908                    }
19909                }
19910            }
19911        }
19912
19913        // Ensure that data directories are ready to roll for all packages
19914        // installed for this volume and user
19915        final List<PackageSetting> packages;
19916        synchronized (mPackages) {
19917            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19918        }
19919        int preparedCount = 0;
19920        for (PackageSetting ps : packages) {
19921            final String packageName = ps.name;
19922            if (ps.pkg == null) {
19923                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19924                // TODO: might be due to legacy ASEC apps; we should circle back
19925                // and reconcile again once they're scanned
19926                continue;
19927            }
19928
19929            if (ps.getInstalled(userId)) {
19930                prepareAppDataLIF(ps.pkg, userId, flags);
19931
19932                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19933                    // We may have just shuffled around app data directories, so
19934                    // prepare them one more time
19935                    prepareAppDataLIF(ps.pkg, userId, flags);
19936                }
19937
19938                preparedCount++;
19939            }
19940        }
19941
19942        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
19943    }
19944
19945    /**
19946     * Prepare app data for the given app just after it was installed or
19947     * upgraded. This method carefully only touches users that it's installed
19948     * for, and it forces a restorecon to handle any seinfo changes.
19949     * <p>
19950     * Verifies that directories exist and that ownership and labeling is
19951     * correct for all installed apps. If there is an ownership mismatch, it
19952     * will try recovering system apps by wiping data; third-party app data is
19953     * left intact.
19954     * <p>
19955     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19956     */
19957    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19958        final PackageSetting ps;
19959        synchronized (mPackages) {
19960            ps = mSettings.mPackages.get(pkg.packageName);
19961            mSettings.writeKernelMappingLPr(ps);
19962        }
19963
19964        final UserManager um = mContext.getSystemService(UserManager.class);
19965        UserManagerInternal umInternal = getUserManagerInternal();
19966        for (UserInfo user : um.getUsers()) {
19967            final int flags;
19968            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19969                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19970            } else if (umInternal.isUserRunning(user.id)) {
19971                flags = StorageManager.FLAG_STORAGE_DE;
19972            } else {
19973                continue;
19974            }
19975
19976            if (ps.getInstalled(user.id)) {
19977                // TODO: when user data is locked, mark that we're still dirty
19978                prepareAppDataLIF(pkg, user.id, flags);
19979            }
19980        }
19981    }
19982
19983    /**
19984     * Prepare app data for the given app.
19985     * <p>
19986     * Verifies that directories exist and that ownership and labeling is
19987     * correct for all installed apps. If there is an ownership mismatch, this
19988     * will try recovering system apps by wiping data; third-party app data is
19989     * left intact.
19990     */
19991    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
19992        if (pkg == null) {
19993            Slog.wtf(TAG, "Package was null!", new Throwable());
19994            return;
19995        }
19996        prepareAppDataLeafLIF(pkg, userId, flags);
19997        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19998        for (int i = 0; i < childCount; i++) {
19999            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
20000        }
20001    }
20002
20003    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20004        if (DEBUG_APP_DATA) {
20005            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
20006                    + Integer.toHexString(flags));
20007        }
20008
20009        final String volumeUuid = pkg.volumeUuid;
20010        final String packageName = pkg.packageName;
20011        final ApplicationInfo app = pkg.applicationInfo;
20012        final int appId = UserHandle.getAppId(app.uid);
20013
20014        Preconditions.checkNotNull(app.seinfo);
20015
20016        long ceDataInode = -1;
20017        try {
20018            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20019                    appId, app.seinfo, app.targetSdkVersion);
20020        } catch (InstallerException e) {
20021            if (app.isSystemApp()) {
20022                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20023                        + ", but trying to recover: " + e);
20024                destroyAppDataLeafLIF(pkg, userId, flags);
20025                try {
20026                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20027                            appId, app.seinfo, app.targetSdkVersion);
20028                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20029                } catch (InstallerException e2) {
20030                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
20031                }
20032            } else {
20033                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20034            }
20035        }
20036
20037        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
20038            // TODO: mark this structure as dirty so we persist it!
20039            synchronized (mPackages) {
20040                final PackageSetting ps = mSettings.mPackages.get(packageName);
20041                if (ps != null) {
20042                    ps.setCeDataInode(ceDataInode, userId);
20043                }
20044            }
20045        }
20046
20047        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20048    }
20049
20050    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20051        if (pkg == null) {
20052            Slog.wtf(TAG, "Package was null!", new Throwable());
20053            return;
20054        }
20055        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20056        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20057        for (int i = 0; i < childCount; i++) {
20058            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20059        }
20060    }
20061
20062    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20063        final String volumeUuid = pkg.volumeUuid;
20064        final String packageName = pkg.packageName;
20065        final ApplicationInfo app = pkg.applicationInfo;
20066
20067        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20068            // Create a native library symlink only if we have native libraries
20069            // and if the native libraries are 32 bit libraries. We do not provide
20070            // this symlink for 64 bit libraries.
20071            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20072                final String nativeLibPath = app.nativeLibraryDir;
20073                try {
20074                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20075                            nativeLibPath, userId);
20076                } catch (InstallerException e) {
20077                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20078                }
20079            }
20080        }
20081    }
20082
20083    /**
20084     * For system apps on non-FBE devices, this method migrates any existing
20085     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20086     * requested by the app.
20087     */
20088    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20089        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20090                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20091            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20092                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20093            try {
20094                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20095                        storageTarget);
20096            } catch (InstallerException e) {
20097                logCriticalInfo(Log.WARN,
20098                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20099            }
20100            return true;
20101        } else {
20102            return false;
20103        }
20104    }
20105
20106    public PackageFreezer freezePackage(String packageName, String killReason) {
20107        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20108    }
20109
20110    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20111        return new PackageFreezer(packageName, userId, killReason);
20112    }
20113
20114    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20115            String killReason) {
20116        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20117    }
20118
20119    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20120            String killReason) {
20121        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20122            return new PackageFreezer();
20123        } else {
20124            return freezePackage(packageName, userId, killReason);
20125        }
20126    }
20127
20128    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20129            String killReason) {
20130        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20131    }
20132
20133    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20134            String killReason) {
20135        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20136            return new PackageFreezer();
20137        } else {
20138            return freezePackage(packageName, userId, killReason);
20139        }
20140    }
20141
20142    /**
20143     * Class that freezes and kills the given package upon creation, and
20144     * unfreezes it upon closing. This is typically used when doing surgery on
20145     * app code/data to prevent the app from running while you're working.
20146     */
20147    private class PackageFreezer implements AutoCloseable {
20148        private final String mPackageName;
20149        private final PackageFreezer[] mChildren;
20150
20151        private final boolean mWeFroze;
20152
20153        private final AtomicBoolean mClosed = new AtomicBoolean();
20154        private final CloseGuard mCloseGuard = CloseGuard.get();
20155
20156        /**
20157         * Create and return a stub freezer that doesn't actually do anything,
20158         * typically used when someone requested
20159         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20160         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20161         */
20162        public PackageFreezer() {
20163            mPackageName = null;
20164            mChildren = null;
20165            mWeFroze = false;
20166            mCloseGuard.open("close");
20167        }
20168
20169        public PackageFreezer(String packageName, int userId, String killReason) {
20170            synchronized (mPackages) {
20171                mPackageName = packageName;
20172                mWeFroze = mFrozenPackages.add(mPackageName);
20173
20174                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20175                if (ps != null) {
20176                    killApplication(ps.name, ps.appId, userId, killReason);
20177                }
20178
20179                final PackageParser.Package p = mPackages.get(packageName);
20180                if (p != null && p.childPackages != null) {
20181                    final int N = p.childPackages.size();
20182                    mChildren = new PackageFreezer[N];
20183                    for (int i = 0; i < N; i++) {
20184                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20185                                userId, killReason);
20186                    }
20187                } else {
20188                    mChildren = null;
20189                }
20190            }
20191            mCloseGuard.open("close");
20192        }
20193
20194        @Override
20195        protected void finalize() throws Throwable {
20196            try {
20197                mCloseGuard.warnIfOpen();
20198                close();
20199            } finally {
20200                super.finalize();
20201            }
20202        }
20203
20204        @Override
20205        public void close() {
20206            mCloseGuard.close();
20207            if (mClosed.compareAndSet(false, true)) {
20208                synchronized (mPackages) {
20209                    if (mWeFroze) {
20210                        mFrozenPackages.remove(mPackageName);
20211                    }
20212
20213                    if (mChildren != null) {
20214                        for (PackageFreezer freezer : mChildren) {
20215                            freezer.close();
20216                        }
20217                    }
20218                }
20219            }
20220        }
20221    }
20222
20223    /**
20224     * Verify that given package is currently frozen.
20225     */
20226    private void checkPackageFrozen(String packageName) {
20227        synchronized (mPackages) {
20228            if (!mFrozenPackages.contains(packageName)) {
20229                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20230            }
20231        }
20232    }
20233
20234    @Override
20235    public int movePackage(final String packageName, final String volumeUuid) {
20236        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20237
20238        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20239        final int moveId = mNextMoveId.getAndIncrement();
20240        mHandler.post(new Runnable() {
20241            @Override
20242            public void run() {
20243                try {
20244                    movePackageInternal(packageName, volumeUuid, moveId, user);
20245                } catch (PackageManagerException e) {
20246                    Slog.w(TAG, "Failed to move " + packageName, e);
20247                    mMoveCallbacks.notifyStatusChanged(moveId,
20248                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20249                }
20250            }
20251        });
20252        return moveId;
20253    }
20254
20255    private void movePackageInternal(final String packageName, final String volumeUuid,
20256            final int moveId, UserHandle user) throws PackageManagerException {
20257        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20258        final PackageManager pm = mContext.getPackageManager();
20259
20260        final boolean currentAsec;
20261        final String currentVolumeUuid;
20262        final File codeFile;
20263        final String installerPackageName;
20264        final String packageAbiOverride;
20265        final int appId;
20266        final String seinfo;
20267        final String label;
20268        final int targetSdkVersion;
20269        final PackageFreezer freezer;
20270        final int[] installedUserIds;
20271
20272        // reader
20273        synchronized (mPackages) {
20274            final PackageParser.Package pkg = mPackages.get(packageName);
20275            final PackageSetting ps = mSettings.mPackages.get(packageName);
20276            if (pkg == null || ps == null) {
20277                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20278            }
20279
20280            if (pkg.applicationInfo.isSystemApp()) {
20281                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20282                        "Cannot move system application");
20283            }
20284
20285            if (pkg.applicationInfo.isExternalAsec()) {
20286                currentAsec = true;
20287                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20288            } else if (pkg.applicationInfo.isForwardLocked()) {
20289                currentAsec = true;
20290                currentVolumeUuid = "forward_locked";
20291            } else {
20292                currentAsec = false;
20293                currentVolumeUuid = ps.volumeUuid;
20294
20295                final File probe = new File(pkg.codePath);
20296                final File probeOat = new File(probe, "oat");
20297                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20298                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20299                            "Move only supported for modern cluster style installs");
20300                }
20301            }
20302
20303            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20304                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20305                        "Package already moved to " + volumeUuid);
20306            }
20307            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20308                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20309                        "Device admin cannot be moved");
20310            }
20311
20312            if (mFrozenPackages.contains(packageName)) {
20313                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20314                        "Failed to move already frozen package");
20315            }
20316
20317            codeFile = new File(pkg.codePath);
20318            installerPackageName = ps.installerPackageName;
20319            packageAbiOverride = ps.cpuAbiOverrideString;
20320            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20321            seinfo = pkg.applicationInfo.seinfo;
20322            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20323            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20324            freezer = freezePackage(packageName, "movePackageInternal");
20325            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20326        }
20327
20328        final Bundle extras = new Bundle();
20329        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20330        extras.putString(Intent.EXTRA_TITLE, label);
20331        mMoveCallbacks.notifyCreated(moveId, extras);
20332
20333        int installFlags;
20334        final boolean moveCompleteApp;
20335        final File measurePath;
20336
20337        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20338            installFlags = INSTALL_INTERNAL;
20339            moveCompleteApp = !currentAsec;
20340            measurePath = Environment.getDataAppDirectory(volumeUuid);
20341        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20342            installFlags = INSTALL_EXTERNAL;
20343            moveCompleteApp = false;
20344            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20345        } else {
20346            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20347            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20348                    || !volume.isMountedWritable()) {
20349                freezer.close();
20350                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20351                        "Move location not mounted private volume");
20352            }
20353
20354            Preconditions.checkState(!currentAsec);
20355
20356            installFlags = INSTALL_INTERNAL;
20357            moveCompleteApp = true;
20358            measurePath = Environment.getDataAppDirectory(volumeUuid);
20359        }
20360
20361        final PackageStats stats = new PackageStats(null, -1);
20362        synchronized (mInstaller) {
20363            for (int userId : installedUserIds) {
20364                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20365                    freezer.close();
20366                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20367                            "Failed to measure package size");
20368                }
20369            }
20370        }
20371
20372        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20373                + stats.dataSize);
20374
20375        final long startFreeBytes = measurePath.getFreeSpace();
20376        final long sizeBytes;
20377        if (moveCompleteApp) {
20378            sizeBytes = stats.codeSize + stats.dataSize;
20379        } else {
20380            sizeBytes = stats.codeSize;
20381        }
20382
20383        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20384            freezer.close();
20385            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20386                    "Not enough free space to move");
20387        }
20388
20389        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20390
20391        final CountDownLatch installedLatch = new CountDownLatch(1);
20392        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20393            @Override
20394            public void onUserActionRequired(Intent intent) throws RemoteException {
20395                throw new IllegalStateException();
20396            }
20397
20398            @Override
20399            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20400                    Bundle extras) throws RemoteException {
20401                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20402                        + PackageManager.installStatusToString(returnCode, msg));
20403
20404                installedLatch.countDown();
20405                freezer.close();
20406
20407                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20408                switch (status) {
20409                    case PackageInstaller.STATUS_SUCCESS:
20410                        mMoveCallbacks.notifyStatusChanged(moveId,
20411                                PackageManager.MOVE_SUCCEEDED);
20412                        break;
20413                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20414                        mMoveCallbacks.notifyStatusChanged(moveId,
20415                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20416                        break;
20417                    default:
20418                        mMoveCallbacks.notifyStatusChanged(moveId,
20419                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20420                        break;
20421                }
20422            }
20423        };
20424
20425        final MoveInfo move;
20426        if (moveCompleteApp) {
20427            // Kick off a thread to report progress estimates
20428            new Thread() {
20429                @Override
20430                public void run() {
20431                    while (true) {
20432                        try {
20433                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20434                                break;
20435                            }
20436                        } catch (InterruptedException ignored) {
20437                        }
20438
20439                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20440                        final int progress = 10 + (int) MathUtils.constrain(
20441                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20442                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20443                    }
20444                }
20445            }.start();
20446
20447            final String dataAppName = codeFile.getName();
20448            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20449                    dataAppName, appId, seinfo, targetSdkVersion);
20450        } else {
20451            move = null;
20452        }
20453
20454        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20455
20456        final Message msg = mHandler.obtainMessage(INIT_COPY);
20457        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20458        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20459                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20460                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20461        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20462        msg.obj = params;
20463
20464        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20465                System.identityHashCode(msg.obj));
20466        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20467                System.identityHashCode(msg.obj));
20468
20469        mHandler.sendMessage(msg);
20470    }
20471
20472    @Override
20473    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20474        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20475
20476        final int realMoveId = mNextMoveId.getAndIncrement();
20477        final Bundle extras = new Bundle();
20478        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20479        mMoveCallbacks.notifyCreated(realMoveId, extras);
20480
20481        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20482            @Override
20483            public void onCreated(int moveId, Bundle extras) {
20484                // Ignored
20485            }
20486
20487            @Override
20488            public void onStatusChanged(int moveId, int status, long estMillis) {
20489                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20490            }
20491        };
20492
20493        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20494        storage.setPrimaryStorageUuid(volumeUuid, callback);
20495        return realMoveId;
20496    }
20497
20498    @Override
20499    public int getMoveStatus(int moveId) {
20500        mContext.enforceCallingOrSelfPermission(
20501                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20502        return mMoveCallbacks.mLastStatus.get(moveId);
20503    }
20504
20505    @Override
20506    public void registerMoveCallback(IPackageMoveObserver callback) {
20507        mContext.enforceCallingOrSelfPermission(
20508                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20509        mMoveCallbacks.register(callback);
20510    }
20511
20512    @Override
20513    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20514        mContext.enforceCallingOrSelfPermission(
20515                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20516        mMoveCallbacks.unregister(callback);
20517    }
20518
20519    @Override
20520    public boolean setInstallLocation(int loc) {
20521        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20522                null);
20523        if (getInstallLocation() == loc) {
20524            return true;
20525        }
20526        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20527                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20528            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20529                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20530            return true;
20531        }
20532        return false;
20533   }
20534
20535    @Override
20536    public int getInstallLocation() {
20537        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20538                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20539                PackageHelper.APP_INSTALL_AUTO);
20540    }
20541
20542    /** Called by UserManagerService */
20543    void cleanUpUser(UserManagerService userManager, int userHandle) {
20544        synchronized (mPackages) {
20545            mDirtyUsers.remove(userHandle);
20546            mUserNeedsBadging.delete(userHandle);
20547            mSettings.removeUserLPw(userHandle);
20548            mPendingBroadcasts.remove(userHandle);
20549            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20550            removeUnusedPackagesLPw(userManager, userHandle);
20551        }
20552    }
20553
20554    /**
20555     * We're removing userHandle and would like to remove any downloaded packages
20556     * that are no longer in use by any other user.
20557     * @param userHandle the user being removed
20558     */
20559    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20560        final boolean DEBUG_CLEAN_APKS = false;
20561        int [] users = userManager.getUserIds();
20562        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20563        while (psit.hasNext()) {
20564            PackageSetting ps = psit.next();
20565            if (ps.pkg == null) {
20566                continue;
20567            }
20568            final String packageName = ps.pkg.packageName;
20569            // Skip over if system app
20570            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20571                continue;
20572            }
20573            if (DEBUG_CLEAN_APKS) {
20574                Slog.i(TAG, "Checking package " + packageName);
20575            }
20576            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20577            if (keep) {
20578                if (DEBUG_CLEAN_APKS) {
20579                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20580                }
20581            } else {
20582                for (int i = 0; i < users.length; i++) {
20583                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20584                        keep = true;
20585                        if (DEBUG_CLEAN_APKS) {
20586                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20587                                    + users[i]);
20588                        }
20589                        break;
20590                    }
20591                }
20592            }
20593            if (!keep) {
20594                if (DEBUG_CLEAN_APKS) {
20595                    Slog.i(TAG, "  Removing package " + packageName);
20596                }
20597                mHandler.post(new Runnable() {
20598                    public void run() {
20599                        deletePackageX(packageName, userHandle, 0);
20600                    } //end run
20601                });
20602            }
20603        }
20604    }
20605
20606    /** Called by UserManagerService */
20607    void createNewUser(int userId) {
20608        synchronized (mInstallLock) {
20609            mSettings.createNewUserLI(this, mInstaller, userId);
20610        }
20611        synchronized (mPackages) {
20612            scheduleWritePackageRestrictionsLocked(userId);
20613            scheduleWritePackageListLocked(userId);
20614            applyFactoryDefaultBrowserLPw(userId);
20615            primeDomainVerificationsLPw(userId);
20616        }
20617    }
20618
20619    void onNewUserCreated(final int userId) {
20620        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20621        // If permission review for legacy apps is required, we represent
20622        // dagerous permissions for such apps as always granted runtime
20623        // permissions to keep per user flag state whether review is needed.
20624        // Hence, if a new user is added we have to propagate dangerous
20625        // permission grants for these legacy apps.
20626        if (mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) {
20627            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20628                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20629        }
20630    }
20631
20632    @Override
20633    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20634        mContext.enforceCallingOrSelfPermission(
20635                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20636                "Only package verification agents can read the verifier device identity");
20637
20638        synchronized (mPackages) {
20639            return mSettings.getVerifierDeviceIdentityLPw();
20640        }
20641    }
20642
20643    @Override
20644    public void setPermissionEnforced(String permission, boolean enforced) {
20645        // TODO: Now that we no longer change GID for storage, this should to away.
20646        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20647                "setPermissionEnforced");
20648        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20649            synchronized (mPackages) {
20650                if (mSettings.mReadExternalStorageEnforced == null
20651                        || mSettings.mReadExternalStorageEnforced != enforced) {
20652                    mSettings.mReadExternalStorageEnforced = enforced;
20653                    mSettings.writeLPr();
20654                }
20655            }
20656            // kill any non-foreground processes so we restart them and
20657            // grant/revoke the GID.
20658            final IActivityManager am = ActivityManagerNative.getDefault();
20659            if (am != null) {
20660                final long token = Binder.clearCallingIdentity();
20661                try {
20662                    am.killProcessesBelowForeground("setPermissionEnforcement");
20663                } catch (RemoteException e) {
20664                } finally {
20665                    Binder.restoreCallingIdentity(token);
20666                }
20667            }
20668        } else {
20669            throw new IllegalArgumentException("No selective enforcement for " + permission);
20670        }
20671    }
20672
20673    @Override
20674    @Deprecated
20675    public boolean isPermissionEnforced(String permission) {
20676        return true;
20677    }
20678
20679    @Override
20680    public boolean isStorageLow() {
20681        final long token = Binder.clearCallingIdentity();
20682        try {
20683            final DeviceStorageMonitorInternal
20684                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20685            if (dsm != null) {
20686                return dsm.isMemoryLow();
20687            } else {
20688                return false;
20689            }
20690        } finally {
20691            Binder.restoreCallingIdentity(token);
20692        }
20693    }
20694
20695    @Override
20696    public IPackageInstaller getPackageInstaller() {
20697        return mInstallerService;
20698    }
20699
20700    private boolean userNeedsBadging(int userId) {
20701        int index = mUserNeedsBadging.indexOfKey(userId);
20702        if (index < 0) {
20703            final UserInfo userInfo;
20704            final long token = Binder.clearCallingIdentity();
20705            try {
20706                userInfo = sUserManager.getUserInfo(userId);
20707            } finally {
20708                Binder.restoreCallingIdentity(token);
20709            }
20710            final boolean b;
20711            if (userInfo != null && userInfo.isManagedProfile()) {
20712                b = true;
20713            } else {
20714                b = false;
20715            }
20716            mUserNeedsBadging.put(userId, b);
20717            return b;
20718        }
20719        return mUserNeedsBadging.valueAt(index);
20720    }
20721
20722    @Override
20723    public KeySet getKeySetByAlias(String packageName, String alias) {
20724        if (packageName == null || alias == null) {
20725            return null;
20726        }
20727        synchronized(mPackages) {
20728            final PackageParser.Package pkg = mPackages.get(packageName);
20729            if (pkg == null) {
20730                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20731                throw new IllegalArgumentException("Unknown package: " + packageName);
20732            }
20733            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20734            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20735        }
20736    }
20737
20738    @Override
20739    public KeySet getSigningKeySet(String packageName) {
20740        if (packageName == null) {
20741            return null;
20742        }
20743        synchronized(mPackages) {
20744            final PackageParser.Package pkg = mPackages.get(packageName);
20745            if (pkg == null) {
20746                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20747                throw new IllegalArgumentException("Unknown package: " + packageName);
20748            }
20749            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20750                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20751                throw new SecurityException("May not access signing KeySet of other apps.");
20752            }
20753            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20754            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20755        }
20756    }
20757
20758    @Override
20759    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20760        if (packageName == null || ks == null) {
20761            return false;
20762        }
20763        synchronized(mPackages) {
20764            final PackageParser.Package pkg = mPackages.get(packageName);
20765            if (pkg == null) {
20766                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20767                throw new IllegalArgumentException("Unknown package: " + packageName);
20768            }
20769            IBinder ksh = ks.getToken();
20770            if (ksh instanceof KeySetHandle) {
20771                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20772                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20773            }
20774            return false;
20775        }
20776    }
20777
20778    @Override
20779    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20780        if (packageName == null || ks == null) {
20781            return false;
20782        }
20783        synchronized(mPackages) {
20784            final PackageParser.Package pkg = mPackages.get(packageName);
20785            if (pkg == null) {
20786                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20787                throw new IllegalArgumentException("Unknown package: " + packageName);
20788            }
20789            IBinder ksh = ks.getToken();
20790            if (ksh instanceof KeySetHandle) {
20791                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20792                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20793            }
20794            return false;
20795        }
20796    }
20797
20798    private void deletePackageIfUnusedLPr(final String packageName) {
20799        PackageSetting ps = mSettings.mPackages.get(packageName);
20800        if (ps == null) {
20801            return;
20802        }
20803        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20804            // TODO Implement atomic delete if package is unused
20805            // It is currently possible that the package will be deleted even if it is installed
20806            // after this method returns.
20807            mHandler.post(new Runnable() {
20808                public void run() {
20809                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20810                }
20811            });
20812        }
20813    }
20814
20815    /**
20816     * Check and throw if the given before/after packages would be considered a
20817     * downgrade.
20818     */
20819    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20820            throws PackageManagerException {
20821        if (after.versionCode < before.mVersionCode) {
20822            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20823                    "Update version code " + after.versionCode + " is older than current "
20824                    + before.mVersionCode);
20825        } else if (after.versionCode == before.mVersionCode) {
20826            if (after.baseRevisionCode < before.baseRevisionCode) {
20827                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20828                        "Update base revision code " + after.baseRevisionCode
20829                        + " is older than current " + before.baseRevisionCode);
20830            }
20831
20832            if (!ArrayUtils.isEmpty(after.splitNames)) {
20833                for (int i = 0; i < after.splitNames.length; i++) {
20834                    final String splitName = after.splitNames[i];
20835                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20836                    if (j != -1) {
20837                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20838                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20839                                    "Update split " + splitName + " revision code "
20840                                    + after.splitRevisionCodes[i] + " is older than current "
20841                                    + before.splitRevisionCodes[j]);
20842                        }
20843                    }
20844                }
20845            }
20846        }
20847    }
20848
20849    private static class MoveCallbacks extends Handler {
20850        private static final int MSG_CREATED = 1;
20851        private static final int MSG_STATUS_CHANGED = 2;
20852
20853        private final RemoteCallbackList<IPackageMoveObserver>
20854                mCallbacks = new RemoteCallbackList<>();
20855
20856        private final SparseIntArray mLastStatus = new SparseIntArray();
20857
20858        public MoveCallbacks(Looper looper) {
20859            super(looper);
20860        }
20861
20862        public void register(IPackageMoveObserver callback) {
20863            mCallbacks.register(callback);
20864        }
20865
20866        public void unregister(IPackageMoveObserver callback) {
20867            mCallbacks.unregister(callback);
20868        }
20869
20870        @Override
20871        public void handleMessage(Message msg) {
20872            final SomeArgs args = (SomeArgs) msg.obj;
20873            final int n = mCallbacks.beginBroadcast();
20874            for (int i = 0; i < n; i++) {
20875                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20876                try {
20877                    invokeCallback(callback, msg.what, args);
20878                } catch (RemoteException ignored) {
20879                }
20880            }
20881            mCallbacks.finishBroadcast();
20882            args.recycle();
20883        }
20884
20885        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20886                throws RemoteException {
20887            switch (what) {
20888                case MSG_CREATED: {
20889                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20890                    break;
20891                }
20892                case MSG_STATUS_CHANGED: {
20893                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20894                    break;
20895                }
20896            }
20897        }
20898
20899        private void notifyCreated(int moveId, Bundle extras) {
20900            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20901
20902            final SomeArgs args = SomeArgs.obtain();
20903            args.argi1 = moveId;
20904            args.arg2 = extras;
20905            obtainMessage(MSG_CREATED, args).sendToTarget();
20906        }
20907
20908        private void notifyStatusChanged(int moveId, int status) {
20909            notifyStatusChanged(moveId, status, -1);
20910        }
20911
20912        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20913            Slog.v(TAG, "Move " + moveId + " status " + status);
20914
20915            final SomeArgs args = SomeArgs.obtain();
20916            args.argi1 = moveId;
20917            args.argi2 = status;
20918            args.arg3 = estMillis;
20919            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20920
20921            synchronized (mLastStatus) {
20922                mLastStatus.put(moveId, status);
20923            }
20924        }
20925    }
20926
20927    private final static class OnPermissionChangeListeners extends Handler {
20928        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20929
20930        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20931                new RemoteCallbackList<>();
20932
20933        public OnPermissionChangeListeners(Looper looper) {
20934            super(looper);
20935        }
20936
20937        @Override
20938        public void handleMessage(Message msg) {
20939            switch (msg.what) {
20940                case MSG_ON_PERMISSIONS_CHANGED: {
20941                    final int uid = msg.arg1;
20942                    handleOnPermissionsChanged(uid);
20943                } break;
20944            }
20945        }
20946
20947        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20948            mPermissionListeners.register(listener);
20949
20950        }
20951
20952        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20953            mPermissionListeners.unregister(listener);
20954        }
20955
20956        public void onPermissionsChanged(int uid) {
20957            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20958                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20959            }
20960        }
20961
20962        private void handleOnPermissionsChanged(int uid) {
20963            final int count = mPermissionListeners.beginBroadcast();
20964            try {
20965                for (int i = 0; i < count; i++) {
20966                    IOnPermissionsChangeListener callback = mPermissionListeners
20967                            .getBroadcastItem(i);
20968                    try {
20969                        callback.onPermissionsChanged(uid);
20970                    } catch (RemoteException e) {
20971                        Log.e(TAG, "Permission listener is dead", e);
20972                    }
20973                }
20974            } finally {
20975                mPermissionListeners.finishBroadcast();
20976            }
20977        }
20978    }
20979
20980    private class PackageManagerInternalImpl extends PackageManagerInternal {
20981        @Override
20982        public void setLocationPackagesProvider(PackagesProvider provider) {
20983            synchronized (mPackages) {
20984                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20985            }
20986        }
20987
20988        @Override
20989        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20990            synchronized (mPackages) {
20991                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20992            }
20993        }
20994
20995        @Override
20996        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20997            synchronized (mPackages) {
20998                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20999            }
21000        }
21001
21002        @Override
21003        public void setDialerAppPackagesProvider(PackagesProvider provider) {
21004            synchronized (mPackages) {
21005                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21006            }
21007        }
21008
21009        @Override
21010        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21011            synchronized (mPackages) {
21012                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21013            }
21014        }
21015
21016        @Override
21017        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21018            synchronized (mPackages) {
21019                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21020            }
21021        }
21022
21023        @Override
21024        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21025            synchronized (mPackages) {
21026                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21027                        packageName, userId);
21028            }
21029        }
21030
21031        @Override
21032        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21033            synchronized (mPackages) {
21034                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21035                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21036                        packageName, userId);
21037            }
21038        }
21039
21040        @Override
21041        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21042            synchronized (mPackages) {
21043                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21044                        packageName, userId);
21045            }
21046        }
21047
21048        @Override
21049        public void setKeepUninstalledPackages(final List<String> packageList) {
21050            Preconditions.checkNotNull(packageList);
21051            List<String> removedFromList = null;
21052            synchronized (mPackages) {
21053                if (mKeepUninstalledPackages != null) {
21054                    final int packagesCount = mKeepUninstalledPackages.size();
21055                    for (int i = 0; i < packagesCount; i++) {
21056                        String oldPackage = mKeepUninstalledPackages.get(i);
21057                        if (packageList != null && packageList.contains(oldPackage)) {
21058                            continue;
21059                        }
21060                        if (removedFromList == null) {
21061                            removedFromList = new ArrayList<>();
21062                        }
21063                        removedFromList.add(oldPackage);
21064                    }
21065                }
21066                mKeepUninstalledPackages = new ArrayList<>(packageList);
21067                if (removedFromList != null) {
21068                    final int removedCount = removedFromList.size();
21069                    for (int i = 0; i < removedCount; i++) {
21070                        deletePackageIfUnusedLPr(removedFromList.get(i));
21071                    }
21072                }
21073            }
21074        }
21075
21076        @Override
21077        public boolean isPermissionsReviewRequired(String packageName, int userId) {
21078            synchronized (mPackages) {
21079                // If we do not support permission review, done.
21080                if (!mPermissionReviewRequired && !Build.PERMISSIONS_REVIEW_REQUIRED) {
21081                    return false;
21082                }
21083
21084                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21085                if (packageSetting == null) {
21086                    return false;
21087                }
21088
21089                // Permission review applies only to apps not supporting the new permission model.
21090                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21091                    return false;
21092                }
21093
21094                // Legacy apps have the permission and get user consent on launch.
21095                PermissionsState permissionsState = packageSetting.getPermissionsState();
21096                return permissionsState.isPermissionReviewRequired(userId);
21097            }
21098        }
21099
21100        @Override
21101        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21102            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21103        }
21104
21105        @Override
21106        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21107                int userId) {
21108            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21109        }
21110
21111        @Override
21112        public void setDeviceAndProfileOwnerPackages(
21113                int deviceOwnerUserId, String deviceOwnerPackage,
21114                SparseArray<String> profileOwnerPackages) {
21115            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21116                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21117        }
21118
21119        @Override
21120        public boolean isPackageDataProtected(int userId, String packageName) {
21121            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21122        }
21123
21124        @Override
21125        public boolean wasPackageEverLaunched(String packageName, int userId) {
21126            synchronized (mPackages) {
21127                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21128            }
21129        }
21130    }
21131
21132    @Override
21133    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21134        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21135        synchronized (mPackages) {
21136            final long identity = Binder.clearCallingIdentity();
21137            try {
21138                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21139                        packageNames, userId);
21140            } finally {
21141                Binder.restoreCallingIdentity(identity);
21142            }
21143        }
21144    }
21145
21146    private static void enforceSystemOrPhoneCaller(String tag) {
21147        int callingUid = Binder.getCallingUid();
21148        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21149            throw new SecurityException(
21150                    "Cannot call " + tag + " from UID " + callingUid);
21151        }
21152    }
21153
21154    boolean isHistoricalPackageUsageAvailable() {
21155        return mPackageUsage.isHistoricalPackageUsageAvailable();
21156    }
21157
21158    /**
21159     * Return a <b>copy</b> of the collection of packages known to the package manager.
21160     * @return A copy of the values of mPackages.
21161     */
21162    Collection<PackageParser.Package> getPackages() {
21163        synchronized (mPackages) {
21164            return new ArrayList<>(mPackages.values());
21165        }
21166    }
21167
21168    /**
21169     * Logs process start information (including base APK hash) to the security log.
21170     * @hide
21171     */
21172    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21173            String apkFile, int pid) {
21174        if (!SecurityLog.isLoggingEnabled()) {
21175            return;
21176        }
21177        Bundle data = new Bundle();
21178        data.putLong("startTimestamp", System.currentTimeMillis());
21179        data.putString("processName", processName);
21180        data.putInt("uid", uid);
21181        data.putString("seinfo", seinfo);
21182        data.putString("apkFile", apkFile);
21183        data.putInt("pid", pid);
21184        Message msg = mProcessLoggingHandler.obtainMessage(
21185                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21186        msg.setData(data);
21187        mProcessLoggingHandler.sendMessage(msg);
21188    }
21189
21190    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21191        return mCompilerStats.getPackageStats(pkgName);
21192    }
21193
21194    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21195        return getOrCreateCompilerPackageStats(pkg.packageName);
21196    }
21197
21198    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21199        return mCompilerStats.getOrCreatePackageStats(pkgName);
21200    }
21201
21202    public void deleteCompilerPackageStats(String pkgName) {
21203        mCompilerStats.deletePackageStats(pkgName);
21204    }
21205}
21206