PackageManagerService.java revision f7edab63d9358b9a4e0dbec3243f6db9f50a2bbe
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            if (!isEphemeral(res.pkg)) {
1792                // Notify DexManager that the package was installed for new users.
1793                // The updated users should already be indexed and the package code paths
1794                // should not change.
1795                // Don't notify the manager for ephemeral apps as they are not expected to
1796                // survive long enough to benefit of background optimizations.
1797                for (int userId : firstUsers) {
1798                    PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1799                    mDexManager.notifyPackageInstalled(info, userId);
1800                }
1801            }
1802        }
1803
1804        // If someone is watching installs - notify them
1805        if (installObserver != null) {
1806            try {
1807                Bundle extras = extrasForInstallResult(res);
1808                installObserver.onPackageInstalled(res.name, res.returnCode,
1809                        res.returnMsg, extras);
1810            } catch (RemoteException e) {
1811                Slog.i(TAG, "Observer no longer exists.");
1812            }
1813        }
1814    }
1815
1816    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1817            PackageParser.Package pkg) {
1818        if (pkg.parentPackage == null) {
1819            return;
1820        }
1821        if (pkg.requestedPermissions == null) {
1822            return;
1823        }
1824        final PackageSetting disabledSysParentPs = mSettings
1825                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1826        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1827                || !disabledSysParentPs.isPrivileged()
1828                || (disabledSysParentPs.childPackageNames != null
1829                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1830            return;
1831        }
1832        final int[] allUserIds = sUserManager.getUserIds();
1833        final int permCount = pkg.requestedPermissions.size();
1834        for (int i = 0; i < permCount; i++) {
1835            String permission = pkg.requestedPermissions.get(i);
1836            BasePermission bp = mSettings.mPermissions.get(permission);
1837            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1838                continue;
1839            }
1840            for (int userId : allUserIds) {
1841                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1842                        permission, userId)) {
1843                    grantRuntimePermission(pkg.packageName, permission, userId);
1844                }
1845            }
1846        }
1847    }
1848
1849    private StorageEventListener mStorageListener = new StorageEventListener() {
1850        @Override
1851        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1852            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1853                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1854                    final String volumeUuid = vol.getFsUuid();
1855
1856                    // Clean up any users or apps that were removed or recreated
1857                    // while this volume was missing
1858                    reconcileUsers(volumeUuid);
1859                    reconcileApps(volumeUuid);
1860
1861                    // Clean up any install sessions that expired or were
1862                    // cancelled while this volume was missing
1863                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1864
1865                    loadPrivatePackages(vol);
1866
1867                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1868                    unloadPrivatePackages(vol);
1869                }
1870            }
1871
1872            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1873                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1874                    updateExternalMediaStatus(true, false);
1875                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1876                    updateExternalMediaStatus(false, false);
1877                }
1878            }
1879        }
1880
1881        @Override
1882        public void onVolumeForgotten(String fsUuid) {
1883            if (TextUtils.isEmpty(fsUuid)) {
1884                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1885                return;
1886            }
1887
1888            // Remove any apps installed on the forgotten volume
1889            synchronized (mPackages) {
1890                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1891                for (PackageSetting ps : packages) {
1892                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1893                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1894                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1895                }
1896
1897                mSettings.onVolumeForgotten(fsUuid);
1898                mSettings.writeLPr();
1899            }
1900        }
1901    };
1902
1903    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1904            String[] grantedPermissions) {
1905        for (int userId : userIds) {
1906            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1907        }
1908
1909        // We could have touched GID membership, so flush out packages.list
1910        synchronized (mPackages) {
1911            mSettings.writePackageListLPr();
1912        }
1913    }
1914
1915    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1916            String[] grantedPermissions) {
1917        SettingBase sb = (SettingBase) pkg.mExtras;
1918        if (sb == null) {
1919            return;
1920        }
1921
1922        PermissionsState permissionsState = sb.getPermissionsState();
1923
1924        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1925                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1926
1927        for (String permission : pkg.requestedPermissions) {
1928            final BasePermission bp;
1929            synchronized (mPackages) {
1930                bp = mSettings.mPermissions.get(permission);
1931            }
1932            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1933                    && (grantedPermissions == null
1934                           || ArrayUtils.contains(grantedPermissions, permission))) {
1935                final int flags = permissionsState.getPermissionFlags(permission, userId);
1936                // Installer cannot change immutable permissions.
1937                if ((flags & immutableFlags) == 0) {
1938                    grantRuntimePermission(pkg.packageName, permission, userId);
1939                }
1940            }
1941        }
1942    }
1943
1944    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1945        Bundle extras = null;
1946        switch (res.returnCode) {
1947            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1948                extras = new Bundle();
1949                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1950                        res.origPermission);
1951                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1952                        res.origPackage);
1953                break;
1954            }
1955            case PackageManager.INSTALL_SUCCEEDED: {
1956                extras = new Bundle();
1957                extras.putBoolean(Intent.EXTRA_REPLACING,
1958                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1959                break;
1960            }
1961        }
1962        return extras;
1963    }
1964
1965    void scheduleWriteSettingsLocked() {
1966        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1967            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1968        }
1969    }
1970
1971    void scheduleWritePackageListLocked(int userId) {
1972        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1973            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1974            msg.arg1 = userId;
1975            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1976        }
1977    }
1978
1979    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1980        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1981        scheduleWritePackageRestrictionsLocked(userId);
1982    }
1983
1984    void scheduleWritePackageRestrictionsLocked(int userId) {
1985        final int[] userIds = (userId == UserHandle.USER_ALL)
1986                ? sUserManager.getUserIds() : new int[]{userId};
1987        for (int nextUserId : userIds) {
1988            if (!sUserManager.exists(nextUserId)) return;
1989            mDirtyUsers.add(nextUserId);
1990            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1991                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1992            }
1993        }
1994    }
1995
1996    public static PackageManagerService main(Context context, Installer installer,
1997            boolean factoryTest, boolean onlyCore) {
1998        // Self-check for initial settings.
1999        PackageManagerServiceCompilerMapping.checkProperties();
2000
2001        PackageManagerService m = new PackageManagerService(context, installer,
2002                factoryTest, onlyCore);
2003        m.enableSystemUserPackages();
2004        ServiceManager.addService("package", m);
2005        return m;
2006    }
2007
2008    private void enableSystemUserPackages() {
2009        if (!UserManager.isSplitSystemUser()) {
2010            return;
2011        }
2012        // For system user, enable apps based on the following conditions:
2013        // - app is whitelisted or belong to one of these groups:
2014        //   -- system app which has no launcher icons
2015        //   -- system app which has INTERACT_ACROSS_USERS permission
2016        //   -- system IME app
2017        // - app is not in the blacklist
2018        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2019        Set<String> enableApps = new ArraySet<>();
2020        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2021                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2022                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2023        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2024        enableApps.addAll(wlApps);
2025        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2026                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2027        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2028        enableApps.removeAll(blApps);
2029        Log.i(TAG, "Applications installed for system user: " + enableApps);
2030        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2031                UserHandle.SYSTEM);
2032        final int allAppsSize = allAps.size();
2033        synchronized (mPackages) {
2034            for (int i = 0; i < allAppsSize; i++) {
2035                String pName = allAps.get(i);
2036                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2037                // Should not happen, but we shouldn't be failing if it does
2038                if (pkgSetting == null) {
2039                    continue;
2040                }
2041                boolean install = enableApps.contains(pName);
2042                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2043                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2044                            + " for system user");
2045                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2046                }
2047            }
2048        }
2049    }
2050
2051    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2052        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2053                Context.DISPLAY_SERVICE);
2054        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2055    }
2056
2057    /**
2058     * Requests that files preopted on a secondary system partition be copied to the data partition
2059     * if possible.  Note that the actual copying of the files is accomplished by init for security
2060     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2061     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2062     */
2063    private static void requestCopyPreoptedFiles() {
2064        final int WAIT_TIME_MS = 100;
2065        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2066        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2067            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2068            // We will wait for up to 100 seconds.
2069            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2070            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2071                try {
2072                    Thread.sleep(WAIT_TIME_MS);
2073                } catch (InterruptedException e) {
2074                    // Do nothing
2075                }
2076                if (SystemClock.uptimeMillis() > timeEnd) {
2077                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2078                    Slog.wtf(TAG, "cppreopt did not finish!");
2079                    break;
2080                }
2081            }
2082        }
2083    }
2084
2085    public PackageManagerService(Context context, Installer installer,
2086            boolean factoryTest, boolean onlyCore) {
2087        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2088                SystemClock.uptimeMillis());
2089
2090        if (mSdkVersion <= 0) {
2091            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2092        }
2093
2094        mContext = context;
2095
2096        mPermissionReviewRequired = context.getResources().getBoolean(
2097                R.bool.config_permissionReviewRequired);
2098
2099        mFactoryTest = factoryTest;
2100        mOnlyCore = onlyCore;
2101        mMetrics = new DisplayMetrics();
2102        mSettings = new Settings(mPackages);
2103        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2104                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2105        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2106                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2107        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2108                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2109        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2110                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2111        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2112                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2113        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2114                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2115
2116        String separateProcesses = SystemProperties.get("debug.separate_processes");
2117        if (separateProcesses != null && separateProcesses.length() > 0) {
2118            if ("*".equals(separateProcesses)) {
2119                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2120                mSeparateProcesses = null;
2121                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2122            } else {
2123                mDefParseFlags = 0;
2124                mSeparateProcesses = separateProcesses.split(",");
2125                Slog.w(TAG, "Running with debug.separate_processes: "
2126                        + separateProcesses);
2127            }
2128        } else {
2129            mDefParseFlags = 0;
2130            mSeparateProcesses = null;
2131        }
2132
2133        mInstaller = installer;
2134        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2135                "*dexopt*");
2136        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2137        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2138
2139        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2140                FgThread.get().getLooper());
2141
2142        getDefaultDisplayMetrics(context, mMetrics);
2143
2144        SystemConfig systemConfig = SystemConfig.getInstance();
2145        mGlobalGids = systemConfig.getGlobalGids();
2146        mSystemPermissions = systemConfig.getSystemPermissions();
2147        mAvailableFeatures = systemConfig.getAvailableFeatures();
2148
2149        mProtectedPackages = new ProtectedPackages(mContext);
2150
2151        synchronized (mInstallLock) {
2152        // writer
2153        synchronized (mPackages) {
2154            mHandlerThread = new ServiceThread(TAG,
2155                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2156            mHandlerThread.start();
2157            mHandler = new PackageHandler(mHandlerThread.getLooper());
2158            mProcessLoggingHandler = new ProcessLoggingHandler();
2159            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2160
2161            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2162
2163            File dataDir = Environment.getDataDirectory();
2164            mAppInstallDir = new File(dataDir, "app");
2165            mAppLib32InstallDir = new File(dataDir, "app-lib");
2166            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2167            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2168            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2169
2170            sUserManager = new UserManagerService(context, this, mPackages);
2171
2172            // Propagate permission configuration in to package manager.
2173            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2174                    = systemConfig.getPermissions();
2175            for (int i=0; i<permConfig.size(); i++) {
2176                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2177                BasePermission bp = mSettings.mPermissions.get(perm.name);
2178                if (bp == null) {
2179                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2180                    mSettings.mPermissions.put(perm.name, bp);
2181                }
2182                if (perm.gids != null) {
2183                    bp.setGids(perm.gids, perm.perUser);
2184                }
2185            }
2186
2187            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2188            for (int i=0; i<libConfig.size(); i++) {
2189                mSharedLibraries.put(libConfig.keyAt(i),
2190                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2191            }
2192
2193            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2194
2195            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2196
2197            if (mFirstBoot) {
2198                requestCopyPreoptedFiles();
2199            }
2200
2201            String customResolverActivity = Resources.getSystem().getString(
2202                    R.string.config_customResolverActivity);
2203            if (TextUtils.isEmpty(customResolverActivity)) {
2204                customResolverActivity = null;
2205            } else {
2206                mCustomResolverComponentName = ComponentName.unflattenFromString(
2207                        customResolverActivity);
2208            }
2209
2210            long startTime = SystemClock.uptimeMillis();
2211
2212            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2213                    startTime);
2214
2215            // Set flag to monitor and not change apk file paths when
2216            // scanning install directories.
2217            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2218
2219            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2220            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2221
2222            if (bootClassPath == null) {
2223                Slog.w(TAG, "No BOOTCLASSPATH found!");
2224            }
2225
2226            if (systemServerClassPath == null) {
2227                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2228            }
2229
2230            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2231            final String[] dexCodeInstructionSets =
2232                    getDexCodeInstructionSets(
2233                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2234
2235            /**
2236             * Ensure all external libraries have had dexopt run on them.
2237             */
2238            if (mSharedLibraries.size() > 0) {
2239                // NOTE: For now, we're compiling these system "shared libraries"
2240                // (and framework jars) into all available architectures. It's possible
2241                // to compile them only when we come across an app that uses them (there's
2242                // already logic for that in scanPackageLI) but that adds some complexity.
2243                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2244                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2245                        final String lib = libEntry.path;
2246                        if (lib == null) {
2247                            continue;
2248                        }
2249
2250                        try {
2251                            // Shared libraries do not have profiles so we perform a full
2252                            // AOT compilation (if needed).
2253                            int dexoptNeeded = DexFile.getDexOptNeeded(
2254                                    lib, dexCodeInstructionSet,
2255                                    getCompilerFilterForReason(REASON_SHARED_APK),
2256                                    false /* newProfile */);
2257                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2258                                mInstaller.dexopt(lib, Process.SYSTEM_UID, "*",
2259                                        dexCodeInstructionSet, dexoptNeeded, null,
2260                                        DEXOPT_PUBLIC,
2261                                        getCompilerFilterForReason(REASON_SHARED_APK),
2262                                        StorageManager.UUID_PRIVATE_INTERNAL,
2263                                        SKIP_SHARED_LIBRARY_CHECK);
2264                            }
2265                        } catch (FileNotFoundException e) {
2266                            Slog.w(TAG, "Library not found: " + lib);
2267                        } catch (IOException | InstallerException e) {
2268                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2269                                    + e.getMessage());
2270                        }
2271                    }
2272                }
2273            }
2274
2275            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2276
2277            final VersionInfo ver = mSettings.getInternalVersion();
2278            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2279
2280            // when upgrading from pre-M, promote system app permissions from install to runtime
2281            mPromoteSystemApps =
2282                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2283
2284            // When upgrading from pre-N, we need to handle package extraction like first boot,
2285            // as there is no profiling data available.
2286            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2287
2288            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2289
2290            // save off the names of pre-existing system packages prior to scanning; we don't
2291            // want to automatically grant runtime permissions for new system apps
2292            if (mPromoteSystemApps) {
2293                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2294                while (pkgSettingIter.hasNext()) {
2295                    PackageSetting ps = pkgSettingIter.next();
2296                    if (isSystemApp(ps)) {
2297                        mExistingSystemPackages.add(ps.name);
2298                    }
2299                }
2300            }
2301
2302            // Collect vendor overlay packages.
2303            // (Do this before scanning any apps.)
2304            // For security and version matching reason, only consider
2305            // overlay packages if they reside in the right directory.
2306            File vendorOverlayDir;
2307            String overlaySkuDir = SystemProperties.get(VENDOR_OVERLAY_SKU_PROPERTY);
2308            if (!overlaySkuDir.isEmpty()) {
2309                vendorOverlayDir = new File(VENDOR_OVERLAY_DIR, overlaySkuDir);
2310            } else {
2311                vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2312            }
2313            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2314                    | PackageParser.PARSE_IS_SYSTEM
2315                    | PackageParser.PARSE_IS_SYSTEM_DIR
2316                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2317
2318            // Find base frameworks (resource packages without code).
2319            scanDirTracedLI(frameworkDir, mDefParseFlags
2320                    | PackageParser.PARSE_IS_SYSTEM
2321                    | PackageParser.PARSE_IS_SYSTEM_DIR
2322                    | PackageParser.PARSE_IS_PRIVILEGED,
2323                    scanFlags | SCAN_NO_DEX, 0);
2324
2325            // Collected privileged system packages.
2326            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2327            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2328                    | PackageParser.PARSE_IS_SYSTEM
2329                    | PackageParser.PARSE_IS_SYSTEM_DIR
2330                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2331
2332            // Collect ordinary system packages.
2333            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2334            scanDirTracedLI(systemAppDir, mDefParseFlags
2335                    | PackageParser.PARSE_IS_SYSTEM
2336                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2337
2338            // Collect all vendor packages.
2339            File vendorAppDir = new File("/vendor/app");
2340            try {
2341                vendorAppDir = vendorAppDir.getCanonicalFile();
2342            } catch (IOException e) {
2343                // failed to look up canonical path, continue with original one
2344            }
2345            scanDirTracedLI(vendorAppDir, mDefParseFlags
2346                    | PackageParser.PARSE_IS_SYSTEM
2347                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2348
2349            // Collect all OEM packages.
2350            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2351            scanDirTracedLI(oemAppDir, mDefParseFlags
2352                    | PackageParser.PARSE_IS_SYSTEM
2353                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2354
2355            // Prune any system packages that no longer exist.
2356            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2357            if (!mOnlyCore) {
2358                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2359                while (psit.hasNext()) {
2360                    PackageSetting ps = psit.next();
2361
2362                    /*
2363                     * If this is not a system app, it can't be a
2364                     * disable system app.
2365                     */
2366                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2367                        continue;
2368                    }
2369
2370                    /*
2371                     * If the package is scanned, it's not erased.
2372                     */
2373                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2374                    if (scannedPkg != null) {
2375                        /*
2376                         * If the system app is both scanned and in the
2377                         * disabled packages list, then it must have been
2378                         * added via OTA. Remove it from the currently
2379                         * scanned package so the previously user-installed
2380                         * application can be scanned.
2381                         */
2382                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2383                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2384                                    + ps.name + "; removing system app.  Last known codePath="
2385                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2386                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2387                                    + scannedPkg.mVersionCode);
2388                            removePackageLI(scannedPkg, true);
2389                            mExpectingBetter.put(ps.name, ps.codePath);
2390                        }
2391
2392                        continue;
2393                    }
2394
2395                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2396                        psit.remove();
2397                        logCriticalInfo(Log.WARN, "System package " + ps.name
2398                                + " no longer exists; it's data will be wiped");
2399                        // Actual deletion of code and data will be handled by later
2400                        // reconciliation step
2401                    } else {
2402                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2403                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2404                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2405                        }
2406                    }
2407                }
2408            }
2409
2410            //look for any incomplete package installations
2411            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2412            for (int i = 0; i < deletePkgsList.size(); i++) {
2413                // Actual deletion of code and data will be handled by later
2414                // reconciliation step
2415                final String packageName = deletePkgsList.get(i).name;
2416                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2417                synchronized (mPackages) {
2418                    mSettings.removePackageLPw(packageName);
2419                }
2420            }
2421
2422            //delete tmp files
2423            deleteTempPackageFiles();
2424
2425            // Remove any shared userIDs that have no associated packages
2426            mSettings.pruneSharedUsersLPw();
2427
2428            if (!mOnlyCore) {
2429                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2430                        SystemClock.uptimeMillis());
2431                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2432
2433                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2434                        | PackageParser.PARSE_FORWARD_LOCK,
2435                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2436
2437                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2438                        | PackageParser.PARSE_IS_EPHEMERAL,
2439                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2440
2441                /**
2442                 * Remove disable package settings for any updated system
2443                 * apps that were removed via an OTA. If they're not a
2444                 * previously-updated app, remove them completely.
2445                 * Otherwise, just revoke their system-level permissions.
2446                 */
2447                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2448                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2449                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2450
2451                    String msg;
2452                    if (deletedPkg == null) {
2453                        msg = "Updated system package " + deletedAppName
2454                                + " no longer exists; it's data will be wiped";
2455                        // Actual deletion of code and data will be handled by later
2456                        // reconciliation step
2457                    } else {
2458                        msg = "Updated system app + " + deletedAppName
2459                                + " no longer present; removing system privileges for "
2460                                + deletedAppName;
2461
2462                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2463
2464                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2465                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2466                    }
2467                    logCriticalInfo(Log.WARN, msg);
2468                }
2469
2470                /**
2471                 * Make sure all system apps that we expected to appear on
2472                 * the userdata partition actually showed up. If they never
2473                 * appeared, crawl back and revive the system version.
2474                 */
2475                for (int i = 0; i < mExpectingBetter.size(); i++) {
2476                    final String packageName = mExpectingBetter.keyAt(i);
2477                    if (!mPackages.containsKey(packageName)) {
2478                        final File scanFile = mExpectingBetter.valueAt(i);
2479
2480                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2481                                + " but never showed up; reverting to system");
2482
2483                        int reparseFlags = mDefParseFlags;
2484                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2485                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2486                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2487                                    | PackageParser.PARSE_IS_PRIVILEGED;
2488                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2489                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2490                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2491                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2492                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2493                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2494                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2495                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2496                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2497                        } else {
2498                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2499                            continue;
2500                        }
2501
2502                        mSettings.enableSystemPackageLPw(packageName);
2503
2504                        try {
2505                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2506                        } catch (PackageManagerException e) {
2507                            Slog.e(TAG, "Failed to parse original system package: "
2508                                    + e.getMessage());
2509                        }
2510                    }
2511                }
2512            }
2513            mExpectingBetter.clear();
2514
2515            // Resolve the storage manager.
2516            mStorageManagerPackage = getStorageManagerPackageName();
2517
2518            // Resolve protected action filters. Only the setup wizard is allowed to
2519            // have a high priority filter for these actions.
2520            mSetupWizardPackage = getSetupWizardPackageName();
2521            if (mProtectedFilters.size() > 0) {
2522                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2523                    Slog.i(TAG, "No setup wizard;"
2524                        + " All protected intents capped to priority 0");
2525                }
2526                for (ActivityIntentInfo filter : mProtectedFilters) {
2527                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2528                        if (DEBUG_FILTERS) {
2529                            Slog.i(TAG, "Found setup wizard;"
2530                                + " allow priority " + filter.getPriority() + ";"
2531                                + " package: " + filter.activity.info.packageName
2532                                + " activity: " + filter.activity.className
2533                                + " priority: " + filter.getPriority());
2534                        }
2535                        // skip setup wizard; allow it to keep the high priority filter
2536                        continue;
2537                    }
2538                    Slog.w(TAG, "Protected action; cap priority to 0;"
2539                            + " package: " + filter.activity.info.packageName
2540                            + " activity: " + filter.activity.className
2541                            + " origPrio: " + filter.getPriority());
2542                    filter.setPriority(0);
2543                }
2544            }
2545            mDeferProtectedFilters = false;
2546            mProtectedFilters.clear();
2547
2548            // Now that we know all of the shared libraries, update all clients to have
2549            // the correct library paths.
2550            updateAllSharedLibrariesLPw();
2551
2552            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2553                // NOTE: We ignore potential failures here during a system scan (like
2554                // the rest of the commands above) because there's precious little we
2555                // can do about it. A settings error is reported, though.
2556                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2557                        false /* boot complete */);
2558            }
2559
2560            // Now that we know all the packages we are keeping,
2561            // read and update their last usage times.
2562            mPackageUsage.read(mPackages);
2563            mCompilerStats.read();
2564
2565            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2566                    SystemClock.uptimeMillis());
2567            Slog.i(TAG, "Time to scan packages: "
2568                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2569                    + " seconds");
2570
2571            // If the platform SDK has changed since the last time we booted,
2572            // we need to re-grant app permission to catch any new ones that
2573            // appear.  This is really a hack, and means that apps can in some
2574            // cases get permissions that the user didn't initially explicitly
2575            // allow...  it would be nice to have some better way to handle
2576            // this situation.
2577            int updateFlags = UPDATE_PERMISSIONS_ALL;
2578            if (ver.sdkVersion != mSdkVersion) {
2579                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2580                        + mSdkVersion + "; regranting permissions for internal storage");
2581                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2582            }
2583            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2584            ver.sdkVersion = mSdkVersion;
2585
2586            // If this is the first boot or an update from pre-M, and it is a normal
2587            // boot, then we need to initialize the default preferred apps across
2588            // all defined users.
2589            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2590                for (UserInfo user : sUserManager.getUsers(true)) {
2591                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2592                    applyFactoryDefaultBrowserLPw(user.id);
2593                    primeDomainVerificationsLPw(user.id);
2594                }
2595            }
2596
2597            // Prepare storage for system user really early during boot,
2598            // since core system apps like SettingsProvider and SystemUI
2599            // can't wait for user to start
2600            final int storageFlags;
2601            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2602                storageFlags = StorageManager.FLAG_STORAGE_DE;
2603            } else {
2604                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2605            }
2606            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2607                    storageFlags);
2608
2609            // If this is first boot after an OTA, and a normal boot, then
2610            // we need to clear code cache directories.
2611            // Note that we do *not* clear the application profiles. These remain valid
2612            // across OTAs and are used to drive profile verification (post OTA) and
2613            // profile compilation (without waiting to collect a fresh set of profiles).
2614            if (mIsUpgrade && !onlyCore) {
2615                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2616                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2617                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2618                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2619                        // No apps are running this early, so no need to freeze
2620                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2621                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2622                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2623                    }
2624                }
2625                ver.fingerprint = Build.FINGERPRINT;
2626            }
2627
2628            checkDefaultBrowser();
2629
2630            // clear only after permissions and other defaults have been updated
2631            mExistingSystemPackages.clear();
2632            mPromoteSystemApps = false;
2633
2634            // All the changes are done during package scanning.
2635            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2636
2637            // can downgrade to reader
2638            mSettings.writeLPr();
2639
2640            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2641            // early on (before the package manager declares itself as early) because other
2642            // components in the system server might ask for package contexts for these apps.
2643            //
2644            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2645            // (i.e, that the data partition is unavailable).
2646            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2647                long start = System.nanoTime();
2648                List<PackageParser.Package> coreApps = new ArrayList<>();
2649                for (PackageParser.Package pkg : mPackages.values()) {
2650                    if (pkg.coreApp) {
2651                        coreApps.add(pkg);
2652                    }
2653                }
2654
2655                int[] stats = performDexOptUpgrade(coreApps, false,
2656                        getCompilerFilterForReason(REASON_CORE_APP));
2657
2658                final int elapsedTimeSeconds =
2659                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2660                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2661
2662                if (DEBUG_DEXOPT) {
2663                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2664                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2665                }
2666
2667
2668                // TODO: Should we log these stats to tron too ?
2669                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2670                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2671                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2672                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2673            }
2674
2675            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2676                    SystemClock.uptimeMillis());
2677
2678            if (!mOnlyCore) {
2679                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2680                mRequiredInstallerPackage = getRequiredInstallerLPr();
2681                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2682                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2683                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2684                        mIntentFilterVerifierComponent);
2685                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2686                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2687                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2688                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2689            } else {
2690                mRequiredVerifierPackage = null;
2691                mRequiredInstallerPackage = null;
2692                mRequiredUninstallerPackage = null;
2693                mIntentFilterVerifierComponent = null;
2694                mIntentFilterVerifier = null;
2695                mServicesSystemSharedLibraryPackageName = null;
2696                mSharedSystemSharedLibraryPackageName = null;
2697            }
2698
2699            mInstallerService = new PackageInstallerService(context, this);
2700
2701            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2702            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2703            // both the installer and resolver must be present to enable ephemeral
2704            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2705                if (DEBUG_EPHEMERAL) {
2706                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2707                            + " installer:" + ephemeralInstallerComponent);
2708                }
2709                mEphemeralResolverComponent = ephemeralResolverComponent;
2710                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2711                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2712                mEphemeralResolverConnection =
2713                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2714            } else {
2715                if (DEBUG_EPHEMERAL) {
2716                    final String missingComponent =
2717                            (ephemeralResolverComponent == null)
2718                            ? (ephemeralInstallerComponent == null)
2719                                    ? "resolver and installer"
2720                                    : "resolver"
2721                            : "installer";
2722                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2723                }
2724                mEphemeralResolverComponent = null;
2725                mEphemeralInstallerComponent = null;
2726                mEphemeralResolverConnection = null;
2727            }
2728
2729            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2730
2731            // Read and update the usage of dex files.
2732            // Do this at the end of PM init so that all the packages have their
2733            // data directory reconciled.
2734            // At this point we know the code paths of the packages, so we can validate
2735            // the disk file and build the internal cache.
2736            // The usage file is expected to be small so loading and verifying it
2737            // should take a fairly small time compare to the other activities (e.g. package
2738            // scanning).
2739            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2740            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2741            for (int userId : currentUserIds) {
2742                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2743            }
2744            mDexManager.load(userPackages);
2745        } // synchronized (mPackages)
2746        } // synchronized (mInstallLock)
2747
2748        // Now after opening every single application zip, make sure they
2749        // are all flushed.  Not really needed, but keeps things nice and
2750        // tidy.
2751        Runtime.getRuntime().gc();
2752
2753        // The initial scanning above does many calls into installd while
2754        // holding the mPackages lock, but we're mostly interested in yelling
2755        // once we have a booted system.
2756        mInstaller.setWarnIfHeld(mPackages);
2757
2758        // Expose private service for system components to use.
2759        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2760    }
2761
2762    @Override
2763    public boolean isFirstBoot() {
2764        return mFirstBoot;
2765    }
2766
2767    @Override
2768    public boolean isOnlyCoreApps() {
2769        return mOnlyCore;
2770    }
2771
2772    @Override
2773    public boolean isUpgrade() {
2774        return mIsUpgrade;
2775    }
2776
2777    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2778        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2779
2780        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2781                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2782                UserHandle.USER_SYSTEM);
2783        if (matches.size() == 1) {
2784            return matches.get(0).getComponentInfo().packageName;
2785        } else if (matches.size() == 0) {
2786            Log.e(TAG, "There should probably be a verifier, but, none were found");
2787            return null;
2788        }
2789        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2790    }
2791
2792    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2793        synchronized (mPackages) {
2794            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2795            if (libraryEntry == null) {
2796                throw new IllegalStateException("Missing required shared library:" + libraryName);
2797            }
2798            return libraryEntry.apk;
2799        }
2800    }
2801
2802    private @NonNull String getRequiredInstallerLPr() {
2803        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2804        intent.addCategory(Intent.CATEGORY_DEFAULT);
2805        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2806
2807        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2808                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2809                UserHandle.USER_SYSTEM);
2810        if (matches.size() == 1) {
2811            ResolveInfo resolveInfo = matches.get(0);
2812            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2813                throw new RuntimeException("The installer must be a privileged app");
2814            }
2815            return matches.get(0).getComponentInfo().packageName;
2816        } else {
2817            throw new RuntimeException("There must be exactly one installer; found " + matches);
2818        }
2819    }
2820
2821    private @NonNull String getRequiredUninstallerLPr() {
2822        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2823        intent.addCategory(Intent.CATEGORY_DEFAULT);
2824        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2825
2826        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2827                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2828                UserHandle.USER_SYSTEM);
2829        if (resolveInfo == null ||
2830                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2831            throw new RuntimeException("There must be exactly one uninstaller; found "
2832                    + resolveInfo);
2833        }
2834        return resolveInfo.getComponentInfo().packageName;
2835    }
2836
2837    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2838        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2839
2840        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2841                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2842                UserHandle.USER_SYSTEM);
2843        ResolveInfo best = null;
2844        final int N = matches.size();
2845        for (int i = 0; i < N; i++) {
2846            final ResolveInfo cur = matches.get(i);
2847            final String packageName = cur.getComponentInfo().packageName;
2848            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2849                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2850                continue;
2851            }
2852
2853            if (best == null || cur.priority > best.priority) {
2854                best = cur;
2855            }
2856        }
2857
2858        if (best != null) {
2859            return best.getComponentInfo().getComponentName();
2860        } else {
2861            throw new RuntimeException("There must be at least one intent filter verifier");
2862        }
2863    }
2864
2865    private @Nullable ComponentName getEphemeralResolverLPr() {
2866        final String[] packageArray =
2867                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2868        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2869            if (DEBUG_EPHEMERAL) {
2870                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2871            }
2872            return null;
2873        }
2874
2875        final int resolveFlags =
2876                MATCH_DIRECT_BOOT_AWARE
2877                | MATCH_DIRECT_BOOT_UNAWARE
2878                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2879        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2880        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2881                resolveFlags, UserHandle.USER_SYSTEM);
2882
2883        final int N = resolvers.size();
2884        if (N == 0) {
2885            if (DEBUG_EPHEMERAL) {
2886                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2887            }
2888            return null;
2889        }
2890
2891        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2892        for (int i = 0; i < N; i++) {
2893            final ResolveInfo info = resolvers.get(i);
2894
2895            if (info.serviceInfo == null) {
2896                continue;
2897            }
2898
2899            final String packageName = info.serviceInfo.packageName;
2900            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2901                if (DEBUG_EPHEMERAL) {
2902                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2903                            + " pkg: " + packageName + ", info:" + info);
2904                }
2905                continue;
2906            }
2907
2908            if (DEBUG_EPHEMERAL) {
2909                Slog.v(TAG, "Ephemeral resolver found;"
2910                        + " pkg: " + packageName + ", info:" + info);
2911            }
2912            return new ComponentName(packageName, info.serviceInfo.name);
2913        }
2914        if (DEBUG_EPHEMERAL) {
2915            Slog.v(TAG, "Ephemeral resolver NOT found");
2916        }
2917        return null;
2918    }
2919
2920    private @Nullable ComponentName getEphemeralInstallerLPr() {
2921        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2922        intent.addCategory(Intent.CATEGORY_DEFAULT);
2923        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2924
2925        final int resolveFlags =
2926                MATCH_DIRECT_BOOT_AWARE
2927                | MATCH_DIRECT_BOOT_UNAWARE
2928                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2929        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2930                resolveFlags, UserHandle.USER_SYSTEM);
2931        if (matches.size() == 0) {
2932            return null;
2933        } else if (matches.size() == 1) {
2934            return matches.get(0).getComponentInfo().getComponentName();
2935        } else {
2936            throw new RuntimeException(
2937                    "There must be at most one ephemeral installer; found " + matches);
2938        }
2939    }
2940
2941    private void primeDomainVerificationsLPw(int userId) {
2942        if (DEBUG_DOMAIN_VERIFICATION) {
2943            Slog.d(TAG, "Priming domain verifications in user " + userId);
2944        }
2945
2946        SystemConfig systemConfig = SystemConfig.getInstance();
2947        ArraySet<String> packages = systemConfig.getLinkedApps();
2948        ArraySet<String> domains = new ArraySet<String>();
2949
2950        for (String packageName : packages) {
2951            PackageParser.Package pkg = mPackages.get(packageName);
2952            if (pkg != null) {
2953                if (!pkg.isSystemApp()) {
2954                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2955                    continue;
2956                }
2957
2958                domains.clear();
2959                for (PackageParser.Activity a : pkg.activities) {
2960                    for (ActivityIntentInfo filter : a.intents) {
2961                        if (hasValidDomains(filter)) {
2962                            domains.addAll(filter.getHostsList());
2963                        }
2964                    }
2965                }
2966
2967                if (domains.size() > 0) {
2968                    if (DEBUG_DOMAIN_VERIFICATION) {
2969                        Slog.v(TAG, "      + " + packageName);
2970                    }
2971                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2972                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2973                    // and then 'always' in the per-user state actually used for intent resolution.
2974                    final IntentFilterVerificationInfo ivi;
2975                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2976                            new ArrayList<String>(domains));
2977                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2978                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2979                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2980                } else {
2981                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2982                            + "' does not handle web links");
2983                }
2984            } else {
2985                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2986            }
2987        }
2988
2989        scheduleWritePackageRestrictionsLocked(userId);
2990        scheduleWriteSettingsLocked();
2991    }
2992
2993    private void applyFactoryDefaultBrowserLPw(int userId) {
2994        // The default browser app's package name is stored in a string resource,
2995        // with a product-specific overlay used for vendor customization.
2996        String browserPkg = mContext.getResources().getString(
2997                com.android.internal.R.string.default_browser);
2998        if (!TextUtils.isEmpty(browserPkg)) {
2999            // non-empty string => required to be a known package
3000            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3001            if (ps == null) {
3002                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3003                browserPkg = null;
3004            } else {
3005                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3006            }
3007        }
3008
3009        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3010        // default.  If there's more than one, just leave everything alone.
3011        if (browserPkg == null) {
3012            calculateDefaultBrowserLPw(userId);
3013        }
3014    }
3015
3016    private void calculateDefaultBrowserLPw(int userId) {
3017        List<String> allBrowsers = resolveAllBrowserApps(userId);
3018        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3019        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3020    }
3021
3022    private List<String> resolveAllBrowserApps(int userId) {
3023        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3024        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3025                PackageManager.MATCH_ALL, userId);
3026
3027        final int count = list.size();
3028        List<String> result = new ArrayList<String>(count);
3029        for (int i=0; i<count; i++) {
3030            ResolveInfo info = list.get(i);
3031            if (info.activityInfo == null
3032                    || !info.handleAllWebDataURI
3033                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3034                    || result.contains(info.activityInfo.packageName)) {
3035                continue;
3036            }
3037            result.add(info.activityInfo.packageName);
3038        }
3039
3040        return result;
3041    }
3042
3043    private boolean packageIsBrowser(String packageName, int userId) {
3044        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3045                PackageManager.MATCH_ALL, userId);
3046        final int N = list.size();
3047        for (int i = 0; i < N; i++) {
3048            ResolveInfo info = list.get(i);
3049            if (packageName.equals(info.activityInfo.packageName)) {
3050                return true;
3051            }
3052        }
3053        return false;
3054    }
3055
3056    private void checkDefaultBrowser() {
3057        final int myUserId = UserHandle.myUserId();
3058        final String packageName = getDefaultBrowserPackageName(myUserId);
3059        if (packageName != null) {
3060            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3061            if (info == null) {
3062                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3063                synchronized (mPackages) {
3064                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3065                }
3066            }
3067        }
3068    }
3069
3070    @Override
3071    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3072            throws RemoteException {
3073        try {
3074            return super.onTransact(code, data, reply, flags);
3075        } catch (RuntimeException e) {
3076            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3077                Slog.wtf(TAG, "Package Manager Crash", e);
3078            }
3079            throw e;
3080        }
3081    }
3082
3083    static int[] appendInts(int[] cur, int[] add) {
3084        if (add == null) return cur;
3085        if (cur == null) return add;
3086        final int N = add.length;
3087        for (int i=0; i<N; i++) {
3088            cur = appendInt(cur, add[i]);
3089        }
3090        return cur;
3091    }
3092
3093    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3094        if (!sUserManager.exists(userId)) return null;
3095        if (ps == null) {
3096            return null;
3097        }
3098        final PackageParser.Package p = ps.pkg;
3099        if (p == null) {
3100            return null;
3101        }
3102
3103        final PermissionsState permissionsState = ps.getPermissionsState();
3104
3105        // Compute GIDs only if requested
3106        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3107                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3108        // Compute granted permissions only if package has requested permissions
3109        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3110                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3111        final PackageUserState state = ps.readUserState(userId);
3112
3113        return PackageParser.generatePackageInfo(p, gids, flags,
3114                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3115    }
3116
3117    @Override
3118    public void checkPackageStartable(String packageName, int userId) {
3119        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3120
3121        synchronized (mPackages) {
3122            final PackageSetting ps = mSettings.mPackages.get(packageName);
3123            if (ps == null) {
3124                throw new SecurityException("Package " + packageName + " was not found!");
3125            }
3126
3127            if (!ps.getInstalled(userId)) {
3128                throw new SecurityException(
3129                        "Package " + packageName + " was not installed for user " + userId + "!");
3130            }
3131
3132            if (mSafeMode && !ps.isSystem()) {
3133                throw new SecurityException("Package " + packageName + " not a system app!");
3134            }
3135
3136            if (mFrozenPackages.contains(packageName)) {
3137                throw new SecurityException("Package " + packageName + " is currently frozen!");
3138            }
3139
3140            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3141                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3142                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3143            }
3144        }
3145    }
3146
3147    @Override
3148    public boolean isPackageAvailable(String packageName, int userId) {
3149        if (!sUserManager.exists(userId)) return false;
3150        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3151                false /* requireFullPermission */, false /* checkShell */, "is package available");
3152        synchronized (mPackages) {
3153            PackageParser.Package p = mPackages.get(packageName);
3154            if (p != null) {
3155                final PackageSetting ps = (PackageSetting) p.mExtras;
3156                if (ps != null) {
3157                    final PackageUserState state = ps.readUserState(userId);
3158                    if (state != null) {
3159                        return PackageParser.isAvailable(state);
3160                    }
3161                }
3162            }
3163        }
3164        return false;
3165    }
3166
3167    @Override
3168    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3169        if (!sUserManager.exists(userId)) return null;
3170        flags = updateFlagsForPackage(flags, userId, packageName);
3171        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3172                false /* requireFullPermission */, false /* checkShell */, "get package info");
3173        // reader
3174        synchronized (mPackages) {
3175            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3176            PackageParser.Package p = null;
3177            if (matchFactoryOnly) {
3178                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3179                if (ps != null) {
3180                    return generatePackageInfo(ps, flags, userId);
3181                }
3182            }
3183            if (p == null) {
3184                p = mPackages.get(packageName);
3185                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3186                    return null;
3187                }
3188            }
3189            if (DEBUG_PACKAGE_INFO)
3190                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3191            if (p != null) {
3192                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3193            }
3194            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3195                final PackageSetting ps = mSettings.mPackages.get(packageName);
3196                return generatePackageInfo(ps, flags, userId);
3197            }
3198        }
3199        return null;
3200    }
3201
3202    @Override
3203    public String[] currentToCanonicalPackageNames(String[] names) {
3204        String[] out = new String[names.length];
3205        // reader
3206        synchronized (mPackages) {
3207            for (int i=names.length-1; i>=0; i--) {
3208                PackageSetting ps = mSettings.mPackages.get(names[i]);
3209                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3210            }
3211        }
3212        return out;
3213    }
3214
3215    @Override
3216    public String[] canonicalToCurrentPackageNames(String[] names) {
3217        String[] out = new String[names.length];
3218        // reader
3219        synchronized (mPackages) {
3220            for (int i=names.length-1; i>=0; i--) {
3221                String cur = mSettings.mRenamedPackages.get(names[i]);
3222                out[i] = cur != null ? cur : names[i];
3223            }
3224        }
3225        return out;
3226    }
3227
3228    @Override
3229    public int getPackageUid(String packageName, int flags, int userId) {
3230        if (!sUserManager.exists(userId)) return -1;
3231        flags = updateFlagsForPackage(flags, userId, packageName);
3232        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3233                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3234
3235        // reader
3236        synchronized (mPackages) {
3237            final PackageParser.Package p = mPackages.get(packageName);
3238            if (p != null && p.isMatch(flags)) {
3239                return UserHandle.getUid(userId, p.applicationInfo.uid);
3240            }
3241            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3242                final PackageSetting ps = mSettings.mPackages.get(packageName);
3243                if (ps != null && ps.isMatch(flags)) {
3244                    return UserHandle.getUid(userId, ps.appId);
3245                }
3246            }
3247        }
3248
3249        return -1;
3250    }
3251
3252    @Override
3253    public int[] getPackageGids(String packageName, int flags, int userId) {
3254        if (!sUserManager.exists(userId)) return null;
3255        flags = updateFlagsForPackage(flags, userId, packageName);
3256        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3257                false /* requireFullPermission */, false /* checkShell */,
3258                "getPackageGids");
3259
3260        // reader
3261        synchronized (mPackages) {
3262            final PackageParser.Package p = mPackages.get(packageName);
3263            if (p != null && p.isMatch(flags)) {
3264                PackageSetting ps = (PackageSetting) p.mExtras;
3265                return ps.getPermissionsState().computeGids(userId);
3266            }
3267            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3268                final PackageSetting ps = mSettings.mPackages.get(packageName);
3269                if (ps != null && ps.isMatch(flags)) {
3270                    return ps.getPermissionsState().computeGids(userId);
3271                }
3272            }
3273        }
3274
3275        return null;
3276    }
3277
3278    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3279        if (bp.perm != null) {
3280            return PackageParser.generatePermissionInfo(bp.perm, flags);
3281        }
3282        PermissionInfo pi = new PermissionInfo();
3283        pi.name = bp.name;
3284        pi.packageName = bp.sourcePackage;
3285        pi.nonLocalizedLabel = bp.name;
3286        pi.protectionLevel = bp.protectionLevel;
3287        return pi;
3288    }
3289
3290    @Override
3291    public PermissionInfo getPermissionInfo(String name, int flags) {
3292        // reader
3293        synchronized (mPackages) {
3294            final BasePermission p = mSettings.mPermissions.get(name);
3295            if (p != null) {
3296                return generatePermissionInfo(p, flags);
3297            }
3298            return null;
3299        }
3300    }
3301
3302    @Override
3303    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3304            int flags) {
3305        // reader
3306        synchronized (mPackages) {
3307            if (group != null && !mPermissionGroups.containsKey(group)) {
3308                // This is thrown as NameNotFoundException
3309                return null;
3310            }
3311
3312            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3313            for (BasePermission p : mSettings.mPermissions.values()) {
3314                if (group == null) {
3315                    if (p.perm == null || p.perm.info.group == null) {
3316                        out.add(generatePermissionInfo(p, flags));
3317                    }
3318                } else {
3319                    if (p.perm != null && group.equals(p.perm.info.group)) {
3320                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3321                    }
3322                }
3323            }
3324            return new ParceledListSlice<>(out);
3325        }
3326    }
3327
3328    @Override
3329    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3330        // reader
3331        synchronized (mPackages) {
3332            return PackageParser.generatePermissionGroupInfo(
3333                    mPermissionGroups.get(name), flags);
3334        }
3335    }
3336
3337    @Override
3338    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3339        // reader
3340        synchronized (mPackages) {
3341            final int N = mPermissionGroups.size();
3342            ArrayList<PermissionGroupInfo> out
3343                    = new ArrayList<PermissionGroupInfo>(N);
3344            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3345                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3346            }
3347            return new ParceledListSlice<>(out);
3348        }
3349    }
3350
3351    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3352            int userId) {
3353        if (!sUserManager.exists(userId)) return null;
3354        PackageSetting ps = mSettings.mPackages.get(packageName);
3355        if (ps != null) {
3356            if (ps.pkg == null) {
3357                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3358                if (pInfo != null) {
3359                    return pInfo.applicationInfo;
3360                }
3361                return null;
3362            }
3363            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3364                    ps.readUserState(userId), userId);
3365        }
3366        return null;
3367    }
3368
3369    @Override
3370    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3371        if (!sUserManager.exists(userId)) return null;
3372        flags = updateFlagsForApplication(flags, userId, packageName);
3373        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3374                false /* requireFullPermission */, false /* checkShell */, "get application info");
3375        // writer
3376        synchronized (mPackages) {
3377            PackageParser.Package p = mPackages.get(packageName);
3378            if (DEBUG_PACKAGE_INFO) Log.v(
3379                    TAG, "getApplicationInfo " + packageName
3380                    + ": " + p);
3381            if (p != null) {
3382                PackageSetting ps = mSettings.mPackages.get(packageName);
3383                if (ps == null) return null;
3384                // Note: isEnabledLP() does not apply here - always return info
3385                return PackageParser.generateApplicationInfo(
3386                        p, flags, ps.readUserState(userId), userId);
3387            }
3388            if ("android".equals(packageName)||"system".equals(packageName)) {
3389                return mAndroidApplication;
3390            }
3391            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3392                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3393            }
3394        }
3395        return null;
3396    }
3397
3398    @Override
3399    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3400            final IPackageDataObserver observer) {
3401        mContext.enforceCallingOrSelfPermission(
3402                android.Manifest.permission.CLEAR_APP_CACHE, null);
3403        // Queue up an async operation since clearing cache may take a little while.
3404        mHandler.post(new Runnable() {
3405            public void run() {
3406                mHandler.removeCallbacks(this);
3407                boolean success = true;
3408                synchronized (mInstallLock) {
3409                    try {
3410                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3411                    } catch (InstallerException e) {
3412                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3413                        success = false;
3414                    }
3415                }
3416                if (observer != null) {
3417                    try {
3418                        observer.onRemoveCompleted(null, success);
3419                    } catch (RemoteException e) {
3420                        Slog.w(TAG, "RemoveException when invoking call back");
3421                    }
3422                }
3423            }
3424        });
3425    }
3426
3427    @Override
3428    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3429            final IntentSender pi) {
3430        mContext.enforceCallingOrSelfPermission(
3431                android.Manifest.permission.CLEAR_APP_CACHE, null);
3432        // Queue up an async operation since clearing cache may take a little while.
3433        mHandler.post(new Runnable() {
3434            public void run() {
3435                mHandler.removeCallbacks(this);
3436                boolean success = true;
3437                synchronized (mInstallLock) {
3438                    try {
3439                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3440                    } catch (InstallerException e) {
3441                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3442                        success = false;
3443                    }
3444                }
3445                if(pi != null) {
3446                    try {
3447                        // Callback via pending intent
3448                        int code = success ? 1 : 0;
3449                        pi.sendIntent(null, code, null,
3450                                null, null);
3451                    } catch (SendIntentException e1) {
3452                        Slog.i(TAG, "Failed to send pending intent");
3453                    }
3454                }
3455            }
3456        });
3457    }
3458
3459    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3460        synchronized (mInstallLock) {
3461            try {
3462                mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3463            } catch (InstallerException e) {
3464                throw new IOException("Failed to free enough space", e);
3465            }
3466        }
3467    }
3468
3469    /**
3470     * Update given flags based on encryption status of current user.
3471     */
3472    private int updateFlags(int flags, int userId) {
3473        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3474                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3475            // Caller expressed an explicit opinion about what encryption
3476            // aware/unaware components they want to see, so fall through and
3477            // give them what they want
3478        } else {
3479            // Caller expressed no opinion, so match based on user state
3480            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3481                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3482            } else {
3483                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3484            }
3485        }
3486        return flags;
3487    }
3488
3489    private UserManagerInternal getUserManagerInternal() {
3490        if (mUserManagerInternal == null) {
3491            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3492        }
3493        return mUserManagerInternal;
3494    }
3495
3496    /**
3497     * Update given flags when being used to request {@link PackageInfo}.
3498     */
3499    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3500        boolean triaged = true;
3501        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3502                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3503            // Caller is asking for component details, so they'd better be
3504            // asking for specific encryption matching behavior, or be triaged
3505            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3506                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3507                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3508                triaged = false;
3509            }
3510        }
3511        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3512                | PackageManager.MATCH_SYSTEM_ONLY
3513                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3514            triaged = false;
3515        }
3516        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3517            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3518                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3519        }
3520        return updateFlags(flags, userId);
3521    }
3522
3523    /**
3524     * Update given flags when being used to request {@link ApplicationInfo}.
3525     */
3526    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3527        return updateFlagsForPackage(flags, userId, cookie);
3528    }
3529
3530    /**
3531     * Update given flags when being used to request {@link ComponentInfo}.
3532     */
3533    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3534        if (cookie instanceof Intent) {
3535            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3536                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3537            }
3538        }
3539
3540        boolean triaged = true;
3541        // Caller is asking for component details, so they'd better be
3542        // asking for specific encryption matching behavior, or be triaged
3543        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3544                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3545                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3546            triaged = false;
3547        }
3548        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3549            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3550                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3551        }
3552
3553        return updateFlags(flags, userId);
3554    }
3555
3556    /**
3557     * Update given flags when being used to request {@link ResolveInfo}.
3558     */
3559    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3560        // Safe mode means we shouldn't match any third-party components
3561        if (mSafeMode) {
3562            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3563        }
3564
3565        return updateFlagsForComponent(flags, userId, cookie);
3566    }
3567
3568    @Override
3569    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3570        if (!sUserManager.exists(userId)) return null;
3571        flags = updateFlagsForComponent(flags, userId, component);
3572        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3573                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3574        synchronized (mPackages) {
3575            PackageParser.Activity a = mActivities.mActivities.get(component);
3576
3577            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3578            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3579                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3580                if (ps == null) return null;
3581                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3582                        userId);
3583            }
3584            if (mResolveComponentName.equals(component)) {
3585                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3586                        new PackageUserState(), userId);
3587            }
3588        }
3589        return null;
3590    }
3591
3592    @Override
3593    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3594            String resolvedType) {
3595        synchronized (mPackages) {
3596            if (component.equals(mResolveComponentName)) {
3597                // The resolver supports EVERYTHING!
3598                return true;
3599            }
3600            PackageParser.Activity a = mActivities.mActivities.get(component);
3601            if (a == null) {
3602                return false;
3603            }
3604            for (int i=0; i<a.intents.size(); i++) {
3605                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3606                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3607                    return true;
3608                }
3609            }
3610            return false;
3611        }
3612    }
3613
3614    @Override
3615    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3616        if (!sUserManager.exists(userId)) return null;
3617        flags = updateFlagsForComponent(flags, userId, component);
3618        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3619                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3620        synchronized (mPackages) {
3621            PackageParser.Activity a = mReceivers.mActivities.get(component);
3622            if (DEBUG_PACKAGE_INFO) Log.v(
3623                TAG, "getReceiverInfo " + component + ": " + a);
3624            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3625                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3626                if (ps == null) return null;
3627                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3628                        userId);
3629            }
3630        }
3631        return null;
3632    }
3633
3634    @Override
3635    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3636        if (!sUserManager.exists(userId)) return null;
3637        flags = updateFlagsForComponent(flags, userId, component);
3638        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3639                false /* requireFullPermission */, false /* checkShell */, "get service info");
3640        synchronized (mPackages) {
3641            PackageParser.Service s = mServices.mServices.get(component);
3642            if (DEBUG_PACKAGE_INFO) Log.v(
3643                TAG, "getServiceInfo " + component + ": " + s);
3644            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3645                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3646                if (ps == null) return null;
3647                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3648                        userId);
3649            }
3650        }
3651        return null;
3652    }
3653
3654    @Override
3655    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3656        if (!sUserManager.exists(userId)) return null;
3657        flags = updateFlagsForComponent(flags, userId, component);
3658        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3659                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3660        synchronized (mPackages) {
3661            PackageParser.Provider p = mProviders.mProviders.get(component);
3662            if (DEBUG_PACKAGE_INFO) Log.v(
3663                TAG, "getProviderInfo " + component + ": " + p);
3664            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3665                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3666                if (ps == null) return null;
3667                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3668                        userId);
3669            }
3670        }
3671        return null;
3672    }
3673
3674    @Override
3675    public String[] getSystemSharedLibraryNames() {
3676        Set<String> libSet;
3677        synchronized (mPackages) {
3678            libSet = mSharedLibraries.keySet();
3679            int size = libSet.size();
3680            if (size > 0) {
3681                String[] libs = new String[size];
3682                libSet.toArray(libs);
3683                return libs;
3684            }
3685        }
3686        return null;
3687    }
3688
3689    @Override
3690    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3691        synchronized (mPackages) {
3692            return mServicesSystemSharedLibraryPackageName;
3693        }
3694    }
3695
3696    @Override
3697    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3698        synchronized (mPackages) {
3699            return mSharedSystemSharedLibraryPackageName;
3700        }
3701    }
3702
3703    @Override
3704    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3705        synchronized (mPackages) {
3706            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3707
3708            final FeatureInfo fi = new FeatureInfo();
3709            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3710                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3711            res.add(fi);
3712
3713            return new ParceledListSlice<>(res);
3714        }
3715    }
3716
3717    @Override
3718    public boolean hasSystemFeature(String name, int version) {
3719        synchronized (mPackages) {
3720            final FeatureInfo feat = mAvailableFeatures.get(name);
3721            if (feat == null) {
3722                return false;
3723            } else {
3724                return feat.version >= version;
3725            }
3726        }
3727    }
3728
3729    @Override
3730    public int checkPermission(String permName, String pkgName, int userId) {
3731        if (!sUserManager.exists(userId)) {
3732            return PackageManager.PERMISSION_DENIED;
3733        }
3734
3735        synchronized (mPackages) {
3736            final PackageParser.Package p = mPackages.get(pkgName);
3737            if (p != null && p.mExtras != null) {
3738                final PackageSetting ps = (PackageSetting) p.mExtras;
3739                final PermissionsState permissionsState = ps.getPermissionsState();
3740                if (permissionsState.hasPermission(permName, userId)) {
3741                    return PackageManager.PERMISSION_GRANTED;
3742                }
3743                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3744                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3745                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3746                    return PackageManager.PERMISSION_GRANTED;
3747                }
3748            }
3749        }
3750
3751        return PackageManager.PERMISSION_DENIED;
3752    }
3753
3754    @Override
3755    public int checkUidPermission(String permName, int uid) {
3756        final int userId = UserHandle.getUserId(uid);
3757
3758        if (!sUserManager.exists(userId)) {
3759            return PackageManager.PERMISSION_DENIED;
3760        }
3761
3762        synchronized (mPackages) {
3763            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3764            if (obj != null) {
3765                final SettingBase ps = (SettingBase) obj;
3766                final PermissionsState permissionsState = ps.getPermissionsState();
3767                if (permissionsState.hasPermission(permName, userId)) {
3768                    return PackageManager.PERMISSION_GRANTED;
3769                }
3770                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3771                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3772                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3773                    return PackageManager.PERMISSION_GRANTED;
3774                }
3775            } else {
3776                ArraySet<String> perms = mSystemPermissions.get(uid);
3777                if (perms != null) {
3778                    if (perms.contains(permName)) {
3779                        return PackageManager.PERMISSION_GRANTED;
3780                    }
3781                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3782                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3783                        return PackageManager.PERMISSION_GRANTED;
3784                    }
3785                }
3786            }
3787        }
3788
3789        return PackageManager.PERMISSION_DENIED;
3790    }
3791
3792    @Override
3793    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3794        if (UserHandle.getCallingUserId() != userId) {
3795            mContext.enforceCallingPermission(
3796                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3797                    "isPermissionRevokedByPolicy for user " + userId);
3798        }
3799
3800        if (checkPermission(permission, packageName, userId)
3801                == PackageManager.PERMISSION_GRANTED) {
3802            return false;
3803        }
3804
3805        final long identity = Binder.clearCallingIdentity();
3806        try {
3807            final int flags = getPermissionFlags(permission, packageName, userId);
3808            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3809        } finally {
3810            Binder.restoreCallingIdentity(identity);
3811        }
3812    }
3813
3814    @Override
3815    public String getPermissionControllerPackageName() {
3816        synchronized (mPackages) {
3817            return mRequiredInstallerPackage;
3818        }
3819    }
3820
3821    /**
3822     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3823     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3824     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3825     * @param message the message to log on security exception
3826     */
3827    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3828            boolean checkShell, String message) {
3829        if (userId < 0) {
3830            throw new IllegalArgumentException("Invalid userId " + userId);
3831        }
3832        if (checkShell) {
3833            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3834        }
3835        if (userId == UserHandle.getUserId(callingUid)) return;
3836        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3837            if (requireFullPermission) {
3838                mContext.enforceCallingOrSelfPermission(
3839                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3840            } else {
3841                try {
3842                    mContext.enforceCallingOrSelfPermission(
3843                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3844                } catch (SecurityException se) {
3845                    mContext.enforceCallingOrSelfPermission(
3846                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3847                }
3848            }
3849        }
3850    }
3851
3852    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3853        if (callingUid == Process.SHELL_UID) {
3854            if (userHandle >= 0
3855                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3856                throw new SecurityException("Shell does not have permission to access user "
3857                        + userHandle);
3858            } else if (userHandle < 0) {
3859                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3860                        + Debug.getCallers(3));
3861            }
3862        }
3863    }
3864
3865    private BasePermission findPermissionTreeLP(String permName) {
3866        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3867            if (permName.startsWith(bp.name) &&
3868                    permName.length() > bp.name.length() &&
3869                    permName.charAt(bp.name.length()) == '.') {
3870                return bp;
3871            }
3872        }
3873        return null;
3874    }
3875
3876    private BasePermission checkPermissionTreeLP(String permName) {
3877        if (permName != null) {
3878            BasePermission bp = findPermissionTreeLP(permName);
3879            if (bp != null) {
3880                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3881                    return bp;
3882                }
3883                throw new SecurityException("Calling uid "
3884                        + Binder.getCallingUid()
3885                        + " is not allowed to add to permission tree "
3886                        + bp.name + " owned by uid " + bp.uid);
3887            }
3888        }
3889        throw new SecurityException("No permission tree found for " + permName);
3890    }
3891
3892    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3893        if (s1 == null) {
3894            return s2 == null;
3895        }
3896        if (s2 == null) {
3897            return false;
3898        }
3899        if (s1.getClass() != s2.getClass()) {
3900            return false;
3901        }
3902        return s1.equals(s2);
3903    }
3904
3905    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3906        if (pi1.icon != pi2.icon) return false;
3907        if (pi1.logo != pi2.logo) return false;
3908        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3909        if (!compareStrings(pi1.name, pi2.name)) return false;
3910        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3911        // We'll take care of setting this one.
3912        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3913        // These are not currently stored in settings.
3914        //if (!compareStrings(pi1.group, pi2.group)) return false;
3915        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3916        //if (pi1.labelRes != pi2.labelRes) return false;
3917        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3918        return true;
3919    }
3920
3921    int permissionInfoFootprint(PermissionInfo info) {
3922        int size = info.name.length();
3923        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3924        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3925        return size;
3926    }
3927
3928    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3929        int size = 0;
3930        for (BasePermission perm : mSettings.mPermissions.values()) {
3931            if (perm.uid == tree.uid) {
3932                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3933            }
3934        }
3935        return size;
3936    }
3937
3938    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3939        // We calculate the max size of permissions defined by this uid and throw
3940        // if that plus the size of 'info' would exceed our stated maximum.
3941        if (tree.uid != Process.SYSTEM_UID) {
3942            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3943            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3944                throw new SecurityException("Permission tree size cap exceeded");
3945            }
3946        }
3947    }
3948
3949    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3950        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3951            throw new SecurityException("Label must be specified in permission");
3952        }
3953        BasePermission tree = checkPermissionTreeLP(info.name);
3954        BasePermission bp = mSettings.mPermissions.get(info.name);
3955        boolean added = bp == null;
3956        boolean changed = true;
3957        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3958        if (added) {
3959            enforcePermissionCapLocked(info, tree);
3960            bp = new BasePermission(info.name, tree.sourcePackage,
3961                    BasePermission.TYPE_DYNAMIC);
3962        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3963            throw new SecurityException(
3964                    "Not allowed to modify non-dynamic permission "
3965                    + info.name);
3966        } else {
3967            if (bp.protectionLevel == fixedLevel
3968                    && bp.perm.owner.equals(tree.perm.owner)
3969                    && bp.uid == tree.uid
3970                    && comparePermissionInfos(bp.perm.info, info)) {
3971                changed = false;
3972            }
3973        }
3974        bp.protectionLevel = fixedLevel;
3975        info = new PermissionInfo(info);
3976        info.protectionLevel = fixedLevel;
3977        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3978        bp.perm.info.packageName = tree.perm.info.packageName;
3979        bp.uid = tree.uid;
3980        if (added) {
3981            mSettings.mPermissions.put(info.name, bp);
3982        }
3983        if (changed) {
3984            if (!async) {
3985                mSettings.writeLPr();
3986            } else {
3987                scheduleWriteSettingsLocked();
3988            }
3989        }
3990        return added;
3991    }
3992
3993    @Override
3994    public boolean addPermission(PermissionInfo info) {
3995        synchronized (mPackages) {
3996            return addPermissionLocked(info, false);
3997        }
3998    }
3999
4000    @Override
4001    public boolean addPermissionAsync(PermissionInfo info) {
4002        synchronized (mPackages) {
4003            return addPermissionLocked(info, true);
4004        }
4005    }
4006
4007    @Override
4008    public void removePermission(String name) {
4009        synchronized (mPackages) {
4010            checkPermissionTreeLP(name);
4011            BasePermission bp = mSettings.mPermissions.get(name);
4012            if (bp != null) {
4013                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4014                    throw new SecurityException(
4015                            "Not allowed to modify non-dynamic permission "
4016                            + name);
4017                }
4018                mSettings.mPermissions.remove(name);
4019                mSettings.writeLPr();
4020            }
4021        }
4022    }
4023
4024    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4025            BasePermission bp) {
4026        int index = pkg.requestedPermissions.indexOf(bp.name);
4027        if (index == -1) {
4028            throw new SecurityException("Package " + pkg.packageName
4029                    + " has not requested permission " + bp.name);
4030        }
4031        if (!bp.isRuntime() && !bp.isDevelopment()) {
4032            throw new SecurityException("Permission " + bp.name
4033                    + " is not a changeable permission type");
4034        }
4035    }
4036
4037    @Override
4038    public void grantRuntimePermission(String packageName, String name, final int userId) {
4039        if (!sUserManager.exists(userId)) {
4040            Log.e(TAG, "No such user:" + userId);
4041            return;
4042        }
4043
4044        mContext.enforceCallingOrSelfPermission(
4045                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4046                "grantRuntimePermission");
4047
4048        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4049                true /* requireFullPermission */, true /* checkShell */,
4050                "grantRuntimePermission");
4051
4052        final int uid;
4053        final SettingBase sb;
4054
4055        synchronized (mPackages) {
4056            final PackageParser.Package pkg = mPackages.get(packageName);
4057            if (pkg == null) {
4058                throw new IllegalArgumentException("Unknown package: " + packageName);
4059            }
4060
4061            final BasePermission bp = mSettings.mPermissions.get(name);
4062            if (bp == null) {
4063                throw new IllegalArgumentException("Unknown permission: " + name);
4064            }
4065
4066            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4067
4068            // If a permission review is required for legacy apps we represent
4069            // their permissions as always granted runtime ones since we need
4070            // to keep the review required permission flag per user while an
4071            // install permission's state is shared across all users.
4072            if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
4073                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4074                    && bp.isRuntime()) {
4075                return;
4076            }
4077
4078            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4079            sb = (SettingBase) pkg.mExtras;
4080            if (sb == null) {
4081                throw new IllegalArgumentException("Unknown package: " + packageName);
4082            }
4083
4084            final PermissionsState permissionsState = sb.getPermissionsState();
4085
4086            final int flags = permissionsState.getPermissionFlags(name, userId);
4087            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4088                throw new SecurityException("Cannot grant system fixed permission "
4089                        + name + " for package " + packageName);
4090            }
4091
4092            if (bp.isDevelopment()) {
4093                // Development permissions must be handled specially, since they are not
4094                // normal runtime permissions.  For now they apply to all users.
4095                if (permissionsState.grantInstallPermission(bp) !=
4096                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4097                    scheduleWriteSettingsLocked();
4098                }
4099                return;
4100            }
4101
4102            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4103                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4104                return;
4105            }
4106
4107            final int result = permissionsState.grantRuntimePermission(bp, userId);
4108            switch (result) {
4109                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4110                    return;
4111                }
4112
4113                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4114                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4115                    mHandler.post(new Runnable() {
4116                        @Override
4117                        public void run() {
4118                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4119                        }
4120                    });
4121                }
4122                break;
4123            }
4124
4125            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4126
4127            // Not critical if that is lost - app has to request again.
4128            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4129        }
4130
4131        // Only need to do this if user is initialized. Otherwise it's a new user
4132        // and there are no processes running as the user yet and there's no need
4133        // to make an expensive call to remount processes for the changed permissions.
4134        if (READ_EXTERNAL_STORAGE.equals(name)
4135                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4136            final long token = Binder.clearCallingIdentity();
4137            try {
4138                if (sUserManager.isInitialized(userId)) {
4139                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4140                            MountServiceInternal.class);
4141                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4142                }
4143            } finally {
4144                Binder.restoreCallingIdentity(token);
4145            }
4146        }
4147    }
4148
4149    @Override
4150    public void revokeRuntimePermission(String packageName, String name, int userId) {
4151        if (!sUserManager.exists(userId)) {
4152            Log.e(TAG, "No such user:" + userId);
4153            return;
4154        }
4155
4156        mContext.enforceCallingOrSelfPermission(
4157                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4158                "revokeRuntimePermission");
4159
4160        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4161                true /* requireFullPermission */, true /* checkShell */,
4162                "revokeRuntimePermission");
4163
4164        final int appId;
4165
4166        synchronized (mPackages) {
4167            final PackageParser.Package pkg = mPackages.get(packageName);
4168            if (pkg == null) {
4169                throw new IllegalArgumentException("Unknown package: " + packageName);
4170            }
4171
4172            final BasePermission bp = mSettings.mPermissions.get(name);
4173            if (bp == null) {
4174                throw new IllegalArgumentException("Unknown permission: " + name);
4175            }
4176
4177            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4178
4179            // If a permission review is required for legacy apps we represent
4180            // their permissions as always granted runtime ones since we need
4181            // to keep the review required permission flag per user while an
4182            // install permission's state is shared across all users.
4183            if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
4184                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4185                    && bp.isRuntime()) {
4186                return;
4187            }
4188
4189            SettingBase sb = (SettingBase) pkg.mExtras;
4190            if (sb == null) {
4191                throw new IllegalArgumentException("Unknown package: " + packageName);
4192            }
4193
4194            final PermissionsState permissionsState = sb.getPermissionsState();
4195
4196            final int flags = permissionsState.getPermissionFlags(name, userId);
4197            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4198                throw new SecurityException("Cannot revoke system fixed permission "
4199                        + name + " for package " + packageName);
4200            }
4201
4202            if (bp.isDevelopment()) {
4203                // Development permissions must be handled specially, since they are not
4204                // normal runtime permissions.  For now they apply to all users.
4205                if (permissionsState.revokeInstallPermission(bp) !=
4206                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4207                    scheduleWriteSettingsLocked();
4208                }
4209                return;
4210            }
4211
4212            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4213                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4214                return;
4215            }
4216
4217            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4218
4219            // Critical, after this call app should never have the permission.
4220            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4221
4222            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4223        }
4224
4225        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4226    }
4227
4228    @Override
4229    public void resetRuntimePermissions() {
4230        mContext.enforceCallingOrSelfPermission(
4231                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4232                "revokeRuntimePermission");
4233
4234        int callingUid = Binder.getCallingUid();
4235        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4236            mContext.enforceCallingOrSelfPermission(
4237                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4238                    "resetRuntimePermissions");
4239        }
4240
4241        synchronized (mPackages) {
4242            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4243            for (int userId : UserManagerService.getInstance().getUserIds()) {
4244                final int packageCount = mPackages.size();
4245                for (int i = 0; i < packageCount; i++) {
4246                    PackageParser.Package pkg = mPackages.valueAt(i);
4247                    if (!(pkg.mExtras instanceof PackageSetting)) {
4248                        continue;
4249                    }
4250                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4251                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4252                }
4253            }
4254        }
4255    }
4256
4257    @Override
4258    public int getPermissionFlags(String name, String packageName, int userId) {
4259        if (!sUserManager.exists(userId)) {
4260            return 0;
4261        }
4262
4263        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4264
4265        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4266                true /* requireFullPermission */, false /* checkShell */,
4267                "getPermissionFlags");
4268
4269        synchronized (mPackages) {
4270            final PackageParser.Package pkg = mPackages.get(packageName);
4271            if (pkg == null) {
4272                return 0;
4273            }
4274
4275            final BasePermission bp = mSettings.mPermissions.get(name);
4276            if (bp == null) {
4277                return 0;
4278            }
4279
4280            SettingBase sb = (SettingBase) pkg.mExtras;
4281            if (sb == null) {
4282                return 0;
4283            }
4284
4285            PermissionsState permissionsState = sb.getPermissionsState();
4286            return permissionsState.getPermissionFlags(name, userId);
4287        }
4288    }
4289
4290    @Override
4291    public void updatePermissionFlags(String name, String packageName, int flagMask,
4292            int flagValues, int userId) {
4293        if (!sUserManager.exists(userId)) {
4294            return;
4295        }
4296
4297        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4298
4299        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4300                true /* requireFullPermission */, true /* checkShell */,
4301                "updatePermissionFlags");
4302
4303        // Only the system can change these flags and nothing else.
4304        if (getCallingUid() != Process.SYSTEM_UID) {
4305            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4306            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4307            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4308            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4309            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4310        }
4311
4312        synchronized (mPackages) {
4313            final PackageParser.Package pkg = mPackages.get(packageName);
4314            if (pkg == null) {
4315                throw new IllegalArgumentException("Unknown package: " + packageName);
4316            }
4317
4318            final BasePermission bp = mSettings.mPermissions.get(name);
4319            if (bp == null) {
4320                throw new IllegalArgumentException("Unknown permission: " + name);
4321            }
4322
4323            SettingBase sb = (SettingBase) pkg.mExtras;
4324            if (sb == null) {
4325                throw new IllegalArgumentException("Unknown package: " + packageName);
4326            }
4327
4328            PermissionsState permissionsState = sb.getPermissionsState();
4329
4330            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4331
4332            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4333                // Install and runtime permissions are stored in different places,
4334                // so figure out what permission changed and persist the change.
4335                if (permissionsState.getInstallPermissionState(name) != null) {
4336                    scheduleWriteSettingsLocked();
4337                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4338                        || hadState) {
4339                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4340                }
4341            }
4342        }
4343    }
4344
4345    /**
4346     * Update the permission flags for all packages and runtime permissions of a user in order
4347     * to allow device or profile owner to remove POLICY_FIXED.
4348     */
4349    @Override
4350    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4351        if (!sUserManager.exists(userId)) {
4352            return;
4353        }
4354
4355        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4356
4357        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4358                true /* requireFullPermission */, true /* checkShell */,
4359                "updatePermissionFlagsForAllApps");
4360
4361        // Only the system can change system fixed flags.
4362        if (getCallingUid() != Process.SYSTEM_UID) {
4363            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4364            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4365        }
4366
4367        synchronized (mPackages) {
4368            boolean changed = false;
4369            final int packageCount = mPackages.size();
4370            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4371                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4372                SettingBase sb = (SettingBase) pkg.mExtras;
4373                if (sb == null) {
4374                    continue;
4375                }
4376                PermissionsState permissionsState = sb.getPermissionsState();
4377                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4378                        userId, flagMask, flagValues);
4379            }
4380            if (changed) {
4381                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4382            }
4383        }
4384    }
4385
4386    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4387        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4388                != PackageManager.PERMISSION_GRANTED
4389            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4390                != PackageManager.PERMISSION_GRANTED) {
4391            throw new SecurityException(message + " requires "
4392                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4393                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4394        }
4395    }
4396
4397    @Override
4398    public boolean shouldShowRequestPermissionRationale(String permissionName,
4399            String packageName, int userId) {
4400        if (UserHandle.getCallingUserId() != userId) {
4401            mContext.enforceCallingPermission(
4402                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4403                    "canShowRequestPermissionRationale for user " + userId);
4404        }
4405
4406        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4407        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4408            return false;
4409        }
4410
4411        if (checkPermission(permissionName, packageName, userId)
4412                == PackageManager.PERMISSION_GRANTED) {
4413            return false;
4414        }
4415
4416        final int flags;
4417
4418        final long identity = Binder.clearCallingIdentity();
4419        try {
4420            flags = getPermissionFlags(permissionName,
4421                    packageName, userId);
4422        } finally {
4423            Binder.restoreCallingIdentity(identity);
4424        }
4425
4426        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4427                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4428                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4429
4430        if ((flags & fixedFlags) != 0) {
4431            return false;
4432        }
4433
4434        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4435    }
4436
4437    @Override
4438    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4439        mContext.enforceCallingOrSelfPermission(
4440                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4441                "addOnPermissionsChangeListener");
4442
4443        synchronized (mPackages) {
4444            mOnPermissionChangeListeners.addListenerLocked(listener);
4445        }
4446    }
4447
4448    @Override
4449    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4450        synchronized (mPackages) {
4451            mOnPermissionChangeListeners.removeListenerLocked(listener);
4452        }
4453    }
4454
4455    @Override
4456    public boolean isProtectedBroadcast(String actionName) {
4457        synchronized (mPackages) {
4458            if (mProtectedBroadcasts.contains(actionName)) {
4459                return true;
4460            } else if (actionName != null) {
4461                // TODO: remove these terrible hacks
4462                if (actionName.startsWith("android.net.netmon.lingerExpired")
4463                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4464                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4465                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4466                    return true;
4467                }
4468            }
4469        }
4470        return false;
4471    }
4472
4473    @Override
4474    public int checkSignatures(String pkg1, String pkg2) {
4475        synchronized (mPackages) {
4476            final PackageParser.Package p1 = mPackages.get(pkg1);
4477            final PackageParser.Package p2 = mPackages.get(pkg2);
4478            if (p1 == null || p1.mExtras == null
4479                    || p2 == null || p2.mExtras == null) {
4480                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4481            }
4482            return compareSignatures(p1.mSignatures, p2.mSignatures);
4483        }
4484    }
4485
4486    @Override
4487    public int checkUidSignatures(int uid1, int uid2) {
4488        // Map to base uids.
4489        uid1 = UserHandle.getAppId(uid1);
4490        uid2 = UserHandle.getAppId(uid2);
4491        // reader
4492        synchronized (mPackages) {
4493            Signature[] s1;
4494            Signature[] s2;
4495            Object obj = mSettings.getUserIdLPr(uid1);
4496            if (obj != null) {
4497                if (obj instanceof SharedUserSetting) {
4498                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4499                } else if (obj instanceof PackageSetting) {
4500                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4501                } else {
4502                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4503                }
4504            } else {
4505                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4506            }
4507            obj = mSettings.getUserIdLPr(uid2);
4508            if (obj != null) {
4509                if (obj instanceof SharedUserSetting) {
4510                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4511                } else if (obj instanceof PackageSetting) {
4512                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4513                } else {
4514                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4515                }
4516            } else {
4517                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4518            }
4519            return compareSignatures(s1, s2);
4520        }
4521    }
4522
4523    /**
4524     * This method should typically only be used when granting or revoking
4525     * permissions, since the app may immediately restart after this call.
4526     * <p>
4527     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4528     * guard your work against the app being relaunched.
4529     */
4530    private void killUid(int appId, int userId, String reason) {
4531        final long identity = Binder.clearCallingIdentity();
4532        try {
4533            IActivityManager am = ActivityManagerNative.getDefault();
4534            if (am != null) {
4535                try {
4536                    am.killUid(appId, userId, reason);
4537                } catch (RemoteException e) {
4538                    /* ignore - same process */
4539                }
4540            }
4541        } finally {
4542            Binder.restoreCallingIdentity(identity);
4543        }
4544    }
4545
4546    /**
4547     * Compares two sets of signatures. Returns:
4548     * <br />
4549     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4550     * <br />
4551     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4552     * <br />
4553     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4554     * <br />
4555     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4556     * <br />
4557     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4558     */
4559    static int compareSignatures(Signature[] s1, Signature[] s2) {
4560        if (s1 == null) {
4561            return s2 == null
4562                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4563                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4564        }
4565
4566        if (s2 == null) {
4567            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4568        }
4569
4570        if (s1.length != s2.length) {
4571            return PackageManager.SIGNATURE_NO_MATCH;
4572        }
4573
4574        // Since both signature sets are of size 1, we can compare without HashSets.
4575        if (s1.length == 1) {
4576            return s1[0].equals(s2[0]) ?
4577                    PackageManager.SIGNATURE_MATCH :
4578                    PackageManager.SIGNATURE_NO_MATCH;
4579        }
4580
4581        ArraySet<Signature> set1 = new ArraySet<Signature>();
4582        for (Signature sig : s1) {
4583            set1.add(sig);
4584        }
4585        ArraySet<Signature> set2 = new ArraySet<Signature>();
4586        for (Signature sig : s2) {
4587            set2.add(sig);
4588        }
4589        // Make sure s2 contains all signatures in s1.
4590        if (set1.equals(set2)) {
4591            return PackageManager.SIGNATURE_MATCH;
4592        }
4593        return PackageManager.SIGNATURE_NO_MATCH;
4594    }
4595
4596    /**
4597     * If the database version for this type of package (internal storage or
4598     * external storage) is less than the version where package signatures
4599     * were updated, return true.
4600     */
4601    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4602        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4603        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4604    }
4605
4606    /**
4607     * Used for backward compatibility to make sure any packages with
4608     * certificate chains get upgraded to the new style. {@code existingSigs}
4609     * will be in the old format (since they were stored on disk from before the
4610     * system upgrade) and {@code scannedSigs} will be in the newer format.
4611     */
4612    private int compareSignaturesCompat(PackageSignatures existingSigs,
4613            PackageParser.Package scannedPkg) {
4614        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4615            return PackageManager.SIGNATURE_NO_MATCH;
4616        }
4617
4618        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4619        for (Signature sig : existingSigs.mSignatures) {
4620            existingSet.add(sig);
4621        }
4622        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4623        for (Signature sig : scannedPkg.mSignatures) {
4624            try {
4625                Signature[] chainSignatures = sig.getChainSignatures();
4626                for (Signature chainSig : chainSignatures) {
4627                    scannedCompatSet.add(chainSig);
4628                }
4629            } catch (CertificateEncodingException e) {
4630                scannedCompatSet.add(sig);
4631            }
4632        }
4633        /*
4634         * Make sure the expanded scanned set contains all signatures in the
4635         * existing one.
4636         */
4637        if (scannedCompatSet.equals(existingSet)) {
4638            // Migrate the old signatures to the new scheme.
4639            existingSigs.assignSignatures(scannedPkg.mSignatures);
4640            // The new KeySets will be re-added later in the scanning process.
4641            synchronized (mPackages) {
4642                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4643            }
4644            return PackageManager.SIGNATURE_MATCH;
4645        }
4646        return PackageManager.SIGNATURE_NO_MATCH;
4647    }
4648
4649    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4650        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4651        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4652    }
4653
4654    private int compareSignaturesRecover(PackageSignatures existingSigs,
4655            PackageParser.Package scannedPkg) {
4656        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4657            return PackageManager.SIGNATURE_NO_MATCH;
4658        }
4659
4660        String msg = null;
4661        try {
4662            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4663                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4664                        + scannedPkg.packageName);
4665                return PackageManager.SIGNATURE_MATCH;
4666            }
4667        } catch (CertificateException e) {
4668            msg = e.getMessage();
4669        }
4670
4671        logCriticalInfo(Log.INFO,
4672                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4673        return PackageManager.SIGNATURE_NO_MATCH;
4674    }
4675
4676    @Override
4677    public List<String> getAllPackages() {
4678        synchronized (mPackages) {
4679            return new ArrayList<String>(mPackages.keySet());
4680        }
4681    }
4682
4683    @Override
4684    public String[] getPackagesForUid(int uid) {
4685        final int userId = UserHandle.getUserId(uid);
4686        uid = UserHandle.getAppId(uid);
4687        // reader
4688        synchronized (mPackages) {
4689            Object obj = mSettings.getUserIdLPr(uid);
4690            if (obj instanceof SharedUserSetting) {
4691                final SharedUserSetting sus = (SharedUserSetting) obj;
4692                final int N = sus.packages.size();
4693                String[] res = new String[N];
4694                final Iterator<PackageSetting> it = sus.packages.iterator();
4695                int i = 0;
4696                while (it.hasNext()) {
4697                    PackageSetting ps = it.next();
4698                    if (ps.getInstalled(userId)) {
4699                        res[i++] = ps.name;
4700                    } else {
4701                        res = ArrayUtils.removeElement(String.class, res, res[i]);
4702                    }
4703                }
4704                return res;
4705            } else if (obj instanceof PackageSetting) {
4706                final PackageSetting ps = (PackageSetting) obj;
4707                return new String[] { ps.name };
4708            }
4709        }
4710        return null;
4711    }
4712
4713    @Override
4714    public String getNameForUid(int uid) {
4715        // reader
4716        synchronized (mPackages) {
4717            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4718            if (obj instanceof SharedUserSetting) {
4719                final SharedUserSetting sus = (SharedUserSetting) obj;
4720                return sus.name + ":" + sus.userId;
4721            } else if (obj instanceof PackageSetting) {
4722                final PackageSetting ps = (PackageSetting) obj;
4723                return ps.name;
4724            }
4725        }
4726        return null;
4727    }
4728
4729    @Override
4730    public int getUidForSharedUser(String sharedUserName) {
4731        if(sharedUserName == null) {
4732            return -1;
4733        }
4734        // reader
4735        synchronized (mPackages) {
4736            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4737            if (suid == null) {
4738                return -1;
4739            }
4740            return suid.userId;
4741        }
4742    }
4743
4744    @Override
4745    public int getFlagsForUid(int uid) {
4746        synchronized (mPackages) {
4747            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4748            if (obj instanceof SharedUserSetting) {
4749                final SharedUserSetting sus = (SharedUserSetting) obj;
4750                return sus.pkgFlags;
4751            } else if (obj instanceof PackageSetting) {
4752                final PackageSetting ps = (PackageSetting) obj;
4753                return ps.pkgFlags;
4754            }
4755        }
4756        return 0;
4757    }
4758
4759    @Override
4760    public int getPrivateFlagsForUid(int uid) {
4761        synchronized (mPackages) {
4762            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4763            if (obj instanceof SharedUserSetting) {
4764                final SharedUserSetting sus = (SharedUserSetting) obj;
4765                return sus.pkgPrivateFlags;
4766            } else if (obj instanceof PackageSetting) {
4767                final PackageSetting ps = (PackageSetting) obj;
4768                return ps.pkgPrivateFlags;
4769            }
4770        }
4771        return 0;
4772    }
4773
4774    @Override
4775    public boolean isUidPrivileged(int uid) {
4776        uid = UserHandle.getAppId(uid);
4777        // reader
4778        synchronized (mPackages) {
4779            Object obj = mSettings.getUserIdLPr(uid);
4780            if (obj instanceof SharedUserSetting) {
4781                final SharedUserSetting sus = (SharedUserSetting) obj;
4782                final Iterator<PackageSetting> it = sus.packages.iterator();
4783                while (it.hasNext()) {
4784                    if (it.next().isPrivileged()) {
4785                        return true;
4786                    }
4787                }
4788            } else if (obj instanceof PackageSetting) {
4789                final PackageSetting ps = (PackageSetting) obj;
4790                return ps.isPrivileged();
4791            }
4792        }
4793        return false;
4794    }
4795
4796    @Override
4797    public String[] getAppOpPermissionPackages(String permissionName) {
4798        synchronized (mPackages) {
4799            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4800            if (pkgs == null) {
4801                return null;
4802            }
4803            return pkgs.toArray(new String[pkgs.size()]);
4804        }
4805    }
4806
4807    @Override
4808    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4809            int flags, int userId) {
4810        try {
4811            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4812
4813            if (!sUserManager.exists(userId)) return null;
4814            flags = updateFlagsForResolve(flags, userId, intent);
4815            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4816                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4817
4818            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4819            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4820                    flags, userId);
4821            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4822
4823            final ResolveInfo bestChoice =
4824                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4825            return bestChoice;
4826        } finally {
4827            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4828        }
4829    }
4830
4831    @Override
4832    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4833            IntentFilter filter, int match, ComponentName activity) {
4834        final int userId = UserHandle.getCallingUserId();
4835        if (DEBUG_PREFERRED) {
4836            Log.v(TAG, "setLastChosenActivity intent=" + intent
4837                + " resolvedType=" + resolvedType
4838                + " flags=" + flags
4839                + " filter=" + filter
4840                + " match=" + match
4841                + " activity=" + activity);
4842            filter.dump(new PrintStreamPrinter(System.out), "    ");
4843        }
4844        intent.setComponent(null);
4845        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4846                userId);
4847        // Find any earlier preferred or last chosen entries and nuke them
4848        findPreferredActivity(intent, resolvedType,
4849                flags, query, 0, false, true, false, userId);
4850        // Add the new activity as the last chosen for this filter
4851        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4852                "Setting last chosen");
4853    }
4854
4855    @Override
4856    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4857        final int userId = UserHandle.getCallingUserId();
4858        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4859        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4860                userId);
4861        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4862                false, false, false, userId);
4863    }
4864
4865    private boolean isEphemeralDisabled() {
4866        // ephemeral apps have been disabled across the board
4867        if (DISABLE_EPHEMERAL_APPS) {
4868            return true;
4869        }
4870        // system isn't up yet; can't read settings, so, assume no ephemeral apps
4871        if (!mSystemReady) {
4872            return true;
4873        }
4874        // we can't get a content resolver until the system is ready; these checks must happen last
4875        final ContentResolver resolver = mContext.getContentResolver();
4876        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
4877            return true;
4878        }
4879        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
4880    }
4881
4882    private boolean isEphemeralAllowed(
4883            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4884            boolean skipPackageCheck) {
4885        // Short circuit and return early if possible.
4886        if (isEphemeralDisabled()) {
4887            return false;
4888        }
4889        final int callingUser = UserHandle.getCallingUserId();
4890        if (callingUser != UserHandle.USER_SYSTEM) {
4891            return false;
4892        }
4893        if (mEphemeralResolverConnection == null) {
4894            return false;
4895        }
4896        if (intent.getComponent() != null) {
4897            return false;
4898        }
4899        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4900            return false;
4901        }
4902        if (!skipPackageCheck && intent.getPackage() != null) {
4903            return false;
4904        }
4905        final boolean isWebUri = hasWebURI(intent);
4906        if (!isWebUri || intent.getData().getHost() == null) {
4907            return false;
4908        }
4909        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4910        synchronized (mPackages) {
4911            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4912            for (int n = 0; n < count; n++) {
4913                ResolveInfo info = resolvedActivities.get(n);
4914                String packageName = info.activityInfo.packageName;
4915                PackageSetting ps = mSettings.mPackages.get(packageName);
4916                if (ps != null) {
4917                    // Try to get the status from User settings first
4918                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4919                    int status = (int) (packedStatus >> 32);
4920                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4921                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4922                        if (DEBUG_EPHEMERAL) {
4923                            Slog.v(TAG, "DENY ephemeral apps;"
4924                                + " pkg: " + packageName + ", status: " + status);
4925                        }
4926                        return false;
4927                    }
4928                }
4929            }
4930        }
4931        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4932        return true;
4933    }
4934
4935    private static EphemeralResolveInfo getEphemeralResolveInfo(
4936            Context context, EphemeralResolverConnection resolverConnection, Intent intent,
4937            String resolvedType, int userId, String packageName) {
4938        final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(),
4939                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4940        final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(),
4941                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4942        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4943                ephemeralPrefixCount);
4944        final int[] shaPrefix = digest.getDigestPrefix();
4945        final byte[][] digestBytes = digest.getDigestBytes();
4946        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4947                resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask);
4948        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4949            // No hash prefix match; there are no ephemeral apps for this domain.
4950            return null;
4951        }
4952
4953        // Go in reverse order so we match the narrowest scope first.
4954        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4955            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4956                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4957                    continue;
4958                }
4959                final List<IntentFilter> filters = ephemeralApplication.getFilters();
4960                // No filters; this should never happen.
4961                if (filters.isEmpty()) {
4962                    continue;
4963                }
4964                if (packageName != null
4965                        && !packageName.equals(ephemeralApplication.getPackageName())) {
4966                    continue;
4967                }
4968                // We have a domain match; resolve the filters to see if anything matches.
4969                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4970                for (int j = filters.size() - 1; j >= 0; --j) {
4971                    final EphemeralResolveIntentInfo intentInfo =
4972                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4973                    ephemeralResolver.addFilter(intentInfo);
4974                }
4975                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4976                        intent, resolvedType, false /*defaultOnly*/, userId);
4977                if (!matchedResolveInfoList.isEmpty()) {
4978                    return matchedResolveInfoList.get(0);
4979                }
4980            }
4981        }
4982        // Hash or filter mis-match; no ephemeral apps for this domain.
4983        return null;
4984    }
4985
4986    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4987            int flags, List<ResolveInfo> query, int userId) {
4988        if (query != null) {
4989            final int N = query.size();
4990            if (N == 1) {
4991                return query.get(0);
4992            } else if (N > 1) {
4993                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4994                // If there is more than one activity with the same priority,
4995                // then let the user decide between them.
4996                ResolveInfo r0 = query.get(0);
4997                ResolveInfo r1 = query.get(1);
4998                if (DEBUG_INTENT_MATCHING || debug) {
4999                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5000                            + r1.activityInfo.name + "=" + r1.priority);
5001                }
5002                // If the first activity has a higher priority, or a different
5003                // default, then it is always desirable to pick it.
5004                if (r0.priority != r1.priority
5005                        || r0.preferredOrder != r1.preferredOrder
5006                        || r0.isDefault != r1.isDefault) {
5007                    return query.get(0);
5008                }
5009                // If we have saved a preference for a preferred activity for
5010                // this Intent, use that.
5011                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5012                        flags, query, r0.priority, true, false, debug, userId);
5013                if (ri != null) {
5014                    return ri;
5015                }
5016                ri = new ResolveInfo(mResolveInfo);
5017                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5018                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5019                // If all of the options come from the same package, show the application's
5020                // label and icon instead of the generic resolver's.
5021                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5022                // and then throw away the ResolveInfo itself, meaning that the caller loses
5023                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5024                // a fallback for this case; we only set the target package's resources on
5025                // the ResolveInfo, not the ActivityInfo.
5026                final String intentPackage = intent.getPackage();
5027                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5028                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5029                    ri.resolvePackageName = intentPackage;
5030                    if (userNeedsBadging(userId)) {
5031                        ri.noResourceId = true;
5032                    } else {
5033                        ri.icon = appi.icon;
5034                    }
5035                    ri.iconResourceId = appi.icon;
5036                    ri.labelRes = appi.labelRes;
5037                }
5038                ri.activityInfo.applicationInfo = new ApplicationInfo(
5039                        ri.activityInfo.applicationInfo);
5040                if (userId != 0) {
5041                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5042                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5043                }
5044                // Make sure that the resolver is displayable in car mode
5045                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5046                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5047                return ri;
5048            }
5049        }
5050        return null;
5051    }
5052
5053    /**
5054     * Return true if the given list is not empty and all of its contents have
5055     * an activityInfo with the given package name.
5056     */
5057    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5058        if (ArrayUtils.isEmpty(list)) {
5059            return false;
5060        }
5061        for (int i = 0, N = list.size(); i < N; i++) {
5062            final ResolveInfo ri = list.get(i);
5063            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5064            if (ai == null || !packageName.equals(ai.packageName)) {
5065                return false;
5066            }
5067        }
5068        return true;
5069    }
5070
5071    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5072            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5073        final int N = query.size();
5074        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5075                .get(userId);
5076        // Get the list of persistent preferred activities that handle the intent
5077        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5078        List<PersistentPreferredActivity> pprefs = ppir != null
5079                ? ppir.queryIntent(intent, resolvedType,
5080                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5081                : null;
5082        if (pprefs != null && pprefs.size() > 0) {
5083            final int M = pprefs.size();
5084            for (int i=0; i<M; i++) {
5085                final PersistentPreferredActivity ppa = pprefs.get(i);
5086                if (DEBUG_PREFERRED || debug) {
5087                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5088                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5089                            + "\n  component=" + ppa.mComponent);
5090                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5091                }
5092                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5093                        flags | MATCH_DISABLED_COMPONENTS, userId);
5094                if (DEBUG_PREFERRED || debug) {
5095                    Slog.v(TAG, "Found persistent preferred activity:");
5096                    if (ai != null) {
5097                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5098                    } else {
5099                        Slog.v(TAG, "  null");
5100                    }
5101                }
5102                if (ai == null) {
5103                    // This previously registered persistent preferred activity
5104                    // component is no longer known. Ignore it and do NOT remove it.
5105                    continue;
5106                }
5107                for (int j=0; j<N; j++) {
5108                    final ResolveInfo ri = query.get(j);
5109                    if (!ri.activityInfo.applicationInfo.packageName
5110                            .equals(ai.applicationInfo.packageName)) {
5111                        continue;
5112                    }
5113                    if (!ri.activityInfo.name.equals(ai.name)) {
5114                        continue;
5115                    }
5116                    //  Found a persistent preference that can handle the intent.
5117                    if (DEBUG_PREFERRED || debug) {
5118                        Slog.v(TAG, "Returning persistent preferred activity: " +
5119                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5120                    }
5121                    return ri;
5122                }
5123            }
5124        }
5125        return null;
5126    }
5127
5128    // TODO: handle preferred activities missing while user has amnesia
5129    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5130            List<ResolveInfo> query, int priority, boolean always,
5131            boolean removeMatches, boolean debug, int userId) {
5132        if (!sUserManager.exists(userId)) return null;
5133        flags = updateFlagsForResolve(flags, userId, intent);
5134        // writer
5135        synchronized (mPackages) {
5136            if (intent.getSelector() != null) {
5137                intent = intent.getSelector();
5138            }
5139            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5140
5141            // Try to find a matching persistent preferred activity.
5142            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5143                    debug, userId);
5144
5145            // If a persistent preferred activity matched, use it.
5146            if (pri != null) {
5147                return pri;
5148            }
5149
5150            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5151            // Get the list of preferred activities that handle the intent
5152            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5153            List<PreferredActivity> prefs = pir != null
5154                    ? pir.queryIntent(intent, resolvedType,
5155                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5156                    : null;
5157            if (prefs != null && prefs.size() > 0) {
5158                boolean changed = false;
5159                try {
5160                    // First figure out how good the original match set is.
5161                    // We will only allow preferred activities that came
5162                    // from the same match quality.
5163                    int match = 0;
5164
5165                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5166
5167                    final int N = query.size();
5168                    for (int j=0; j<N; j++) {
5169                        final ResolveInfo ri = query.get(j);
5170                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5171                                + ": 0x" + Integer.toHexString(match));
5172                        if (ri.match > match) {
5173                            match = ri.match;
5174                        }
5175                    }
5176
5177                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5178                            + Integer.toHexString(match));
5179
5180                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5181                    final int M = prefs.size();
5182                    for (int i=0; i<M; i++) {
5183                        final PreferredActivity pa = prefs.get(i);
5184                        if (DEBUG_PREFERRED || debug) {
5185                            Slog.v(TAG, "Checking PreferredActivity ds="
5186                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5187                                    + "\n  component=" + pa.mPref.mComponent);
5188                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5189                        }
5190                        if (pa.mPref.mMatch != match) {
5191                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5192                                    + Integer.toHexString(pa.mPref.mMatch));
5193                            continue;
5194                        }
5195                        // If it's not an "always" type preferred activity and that's what we're
5196                        // looking for, skip it.
5197                        if (always && !pa.mPref.mAlways) {
5198                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5199                            continue;
5200                        }
5201                        final ActivityInfo ai = getActivityInfo(
5202                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5203                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5204                                userId);
5205                        if (DEBUG_PREFERRED || debug) {
5206                            Slog.v(TAG, "Found preferred activity:");
5207                            if (ai != null) {
5208                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5209                            } else {
5210                                Slog.v(TAG, "  null");
5211                            }
5212                        }
5213                        if (ai == null) {
5214                            // This previously registered preferred activity
5215                            // component is no longer known.  Most likely an update
5216                            // to the app was installed and in the new version this
5217                            // component no longer exists.  Clean it up by removing
5218                            // it from the preferred activities list, and skip it.
5219                            Slog.w(TAG, "Removing dangling preferred activity: "
5220                                    + pa.mPref.mComponent);
5221                            pir.removeFilter(pa);
5222                            changed = true;
5223                            continue;
5224                        }
5225                        for (int j=0; j<N; j++) {
5226                            final ResolveInfo ri = query.get(j);
5227                            if (!ri.activityInfo.applicationInfo.packageName
5228                                    .equals(ai.applicationInfo.packageName)) {
5229                                continue;
5230                            }
5231                            if (!ri.activityInfo.name.equals(ai.name)) {
5232                                continue;
5233                            }
5234
5235                            if (removeMatches) {
5236                                pir.removeFilter(pa);
5237                                changed = true;
5238                                if (DEBUG_PREFERRED) {
5239                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5240                                }
5241                                break;
5242                            }
5243
5244                            // Okay we found a previously set preferred or last chosen app.
5245                            // If the result set is different from when this
5246                            // was created, we need to clear it and re-ask the
5247                            // user their preference, if we're looking for an "always" type entry.
5248                            if (always && !pa.mPref.sameSet(query)) {
5249                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5250                                        + intent + " type " + resolvedType);
5251                                if (DEBUG_PREFERRED) {
5252                                    Slog.v(TAG, "Removing preferred activity since set changed "
5253                                            + pa.mPref.mComponent);
5254                                }
5255                                pir.removeFilter(pa);
5256                                // Re-add the filter as a "last chosen" entry (!always)
5257                                PreferredActivity lastChosen = new PreferredActivity(
5258                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5259                                pir.addFilter(lastChosen);
5260                                changed = true;
5261                                return null;
5262                            }
5263
5264                            // Yay! Either the set matched or we're looking for the last chosen
5265                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5266                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5267                            return ri;
5268                        }
5269                    }
5270                } finally {
5271                    if (changed) {
5272                        if (DEBUG_PREFERRED) {
5273                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5274                        }
5275                        scheduleWritePackageRestrictionsLocked(userId);
5276                    }
5277                }
5278            }
5279        }
5280        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5281        return null;
5282    }
5283
5284    /*
5285     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5286     */
5287    @Override
5288    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5289            int targetUserId) {
5290        mContext.enforceCallingOrSelfPermission(
5291                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5292        List<CrossProfileIntentFilter> matches =
5293                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5294        if (matches != null) {
5295            int size = matches.size();
5296            for (int i = 0; i < size; i++) {
5297                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5298            }
5299        }
5300        if (hasWebURI(intent)) {
5301            // cross-profile app linking works only towards the parent.
5302            final UserInfo parent = getProfileParent(sourceUserId);
5303            synchronized(mPackages) {
5304                int flags = updateFlagsForResolve(0, parent.id, intent);
5305                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5306                        intent, resolvedType, flags, sourceUserId, parent.id);
5307                return xpDomainInfo != null;
5308            }
5309        }
5310        return false;
5311    }
5312
5313    private UserInfo getProfileParent(int userId) {
5314        final long identity = Binder.clearCallingIdentity();
5315        try {
5316            return sUserManager.getProfileParent(userId);
5317        } finally {
5318            Binder.restoreCallingIdentity(identity);
5319        }
5320    }
5321
5322    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5323            String resolvedType, int userId) {
5324        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5325        if (resolver != null) {
5326            return resolver.queryIntent(intent, resolvedType, false, userId);
5327        }
5328        return null;
5329    }
5330
5331    @Override
5332    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5333            String resolvedType, int flags, int userId) {
5334        try {
5335            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5336
5337            return new ParceledListSlice<>(
5338                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5339        } finally {
5340            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5341        }
5342    }
5343
5344    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5345            String resolvedType, int flags, int userId) {
5346        if (!sUserManager.exists(userId)) return Collections.emptyList();
5347        flags = updateFlagsForResolve(flags, userId, intent);
5348        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5349                false /* requireFullPermission */, false /* checkShell */,
5350                "query intent activities");
5351        ComponentName comp = intent.getComponent();
5352        if (comp == null) {
5353            if (intent.getSelector() != null) {
5354                intent = intent.getSelector();
5355                comp = intent.getComponent();
5356            }
5357        }
5358
5359        if (comp != null) {
5360            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5361            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5362            if (ai != null) {
5363                final ResolveInfo ri = new ResolveInfo();
5364                ri.activityInfo = ai;
5365                list.add(ri);
5366            }
5367            return list;
5368        }
5369
5370        // reader
5371        boolean sortResult = false;
5372        boolean addEphemeral = false;
5373        boolean matchEphemeralPackage = false;
5374        List<ResolveInfo> result;
5375        final String pkgName = intent.getPackage();
5376        synchronized (mPackages) {
5377            if (pkgName == null) {
5378                List<CrossProfileIntentFilter> matchingFilters =
5379                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5380                // Check for results that need to skip the current profile.
5381                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5382                        resolvedType, flags, userId);
5383                if (xpResolveInfo != null) {
5384                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5385                    xpResult.add(xpResolveInfo);
5386                    return filterIfNotSystemUser(xpResult, userId);
5387                }
5388
5389                // Check for results in the current profile.
5390                result = filterIfNotSystemUser(mActivities.queryIntent(
5391                        intent, resolvedType, flags, userId), userId);
5392                addEphemeral =
5393                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5394
5395                // Check for cross profile results.
5396                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5397                xpResolveInfo = queryCrossProfileIntents(
5398                        matchingFilters, intent, resolvedType, flags, userId,
5399                        hasNonNegativePriorityResult);
5400                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5401                    boolean isVisibleToUser = filterIfNotSystemUser(
5402                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5403                    if (isVisibleToUser) {
5404                        result.add(xpResolveInfo);
5405                        sortResult = true;
5406                    }
5407                }
5408                if (hasWebURI(intent)) {
5409                    CrossProfileDomainInfo xpDomainInfo = null;
5410                    final UserInfo parent = getProfileParent(userId);
5411                    if (parent != null) {
5412                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5413                                flags, userId, parent.id);
5414                    }
5415                    if (xpDomainInfo != null) {
5416                        if (xpResolveInfo != null) {
5417                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5418                            // in the result.
5419                            result.remove(xpResolveInfo);
5420                        }
5421                        if (result.size() == 0 && !addEphemeral) {
5422                            result.add(xpDomainInfo.resolveInfo);
5423                            return result;
5424                        }
5425                    }
5426                    if (result.size() > 1 || addEphemeral) {
5427                        result = filterCandidatesWithDomainPreferredActivitiesLPr(
5428                                intent, flags, result, xpDomainInfo, userId);
5429                        sortResult = true;
5430                    }
5431                }
5432            } else {
5433                final PackageParser.Package pkg = mPackages.get(pkgName);
5434                if (pkg != null) {
5435                    result = filterIfNotSystemUser(
5436                            mActivities.queryIntentForPackage(
5437                                    intent, resolvedType, flags, pkg.activities, userId),
5438                            userId);
5439                } else {
5440                    // the caller wants to resolve for a particular package; however, there
5441                    // were no installed results, so, try to find an ephemeral result
5442                    addEphemeral = isEphemeralAllowed(
5443                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5444                    matchEphemeralPackage = true;
5445                    result = new ArrayList<ResolveInfo>();
5446                }
5447            }
5448        }
5449        if (addEphemeral) {
5450            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5451            final EphemeralResolveInfo ai = getEphemeralResolveInfo(
5452                    mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5453                    matchEphemeralPackage ? pkgName : null);
5454            if (ai != null) {
5455                if (DEBUG_EPHEMERAL) {
5456                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5457                }
5458                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5459                ephemeralInstaller.ephemeralResolveInfo = ai;
5460                // make sure this resolver is the default
5461                ephemeralInstaller.isDefault = true;
5462                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5463                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5464                // add a non-generic filter
5465                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5466                ephemeralInstaller.filter.addDataPath(
5467                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5468                result.add(ephemeralInstaller);
5469            }
5470            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5471        }
5472        if (sortResult) {
5473            Collections.sort(result, mResolvePrioritySorter);
5474        }
5475        return result;
5476    }
5477
5478    private static class CrossProfileDomainInfo {
5479        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5480        ResolveInfo resolveInfo;
5481        /* Best domain verification status of the activities found in the other profile */
5482        int bestDomainVerificationStatus;
5483    }
5484
5485    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5486            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5487        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5488                sourceUserId)) {
5489            return null;
5490        }
5491        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5492                resolvedType, flags, parentUserId);
5493
5494        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5495            return null;
5496        }
5497        CrossProfileDomainInfo result = null;
5498        int size = resultTargetUser.size();
5499        for (int i = 0; i < size; i++) {
5500            ResolveInfo riTargetUser = resultTargetUser.get(i);
5501            // Intent filter verification is only for filters that specify a host. So don't return
5502            // those that handle all web uris.
5503            if (riTargetUser.handleAllWebDataURI) {
5504                continue;
5505            }
5506            String packageName = riTargetUser.activityInfo.packageName;
5507            PackageSetting ps = mSettings.mPackages.get(packageName);
5508            if (ps == null) {
5509                continue;
5510            }
5511            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5512            int status = (int)(verificationState >> 32);
5513            if (result == null) {
5514                result = new CrossProfileDomainInfo();
5515                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5516                        sourceUserId, parentUserId);
5517                result.bestDomainVerificationStatus = status;
5518            } else {
5519                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5520                        result.bestDomainVerificationStatus);
5521            }
5522        }
5523        // Don't consider matches with status NEVER across profiles.
5524        if (result != null && result.bestDomainVerificationStatus
5525                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5526            return null;
5527        }
5528        return result;
5529    }
5530
5531    /**
5532     * Verification statuses are ordered from the worse to the best, except for
5533     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5534     */
5535    private int bestDomainVerificationStatus(int status1, int status2) {
5536        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5537            return status2;
5538        }
5539        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5540            return status1;
5541        }
5542        return (int) MathUtils.max(status1, status2);
5543    }
5544
5545    private boolean isUserEnabled(int userId) {
5546        long callingId = Binder.clearCallingIdentity();
5547        try {
5548            UserInfo userInfo = sUserManager.getUserInfo(userId);
5549            return userInfo != null && userInfo.isEnabled();
5550        } finally {
5551            Binder.restoreCallingIdentity(callingId);
5552        }
5553    }
5554
5555    /**
5556     * Filter out activities with systemUserOnly flag set, when current user is not System.
5557     *
5558     * @return filtered list
5559     */
5560    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5561        if (userId == UserHandle.USER_SYSTEM) {
5562            return resolveInfos;
5563        }
5564        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5565            ResolveInfo info = resolveInfos.get(i);
5566            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5567                resolveInfos.remove(i);
5568            }
5569        }
5570        return resolveInfos;
5571    }
5572
5573    /**
5574     * @param resolveInfos list of resolve infos in descending priority order
5575     * @return if the list contains a resolve info with non-negative priority
5576     */
5577    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5578        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5579    }
5580
5581    private static boolean hasWebURI(Intent intent) {
5582        if (intent.getData() == null) {
5583            return false;
5584        }
5585        final String scheme = intent.getScheme();
5586        if (TextUtils.isEmpty(scheme)) {
5587            return false;
5588        }
5589        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5590    }
5591
5592    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5593            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5594            int userId) {
5595        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5596
5597        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5598            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5599                    candidates.size());
5600        }
5601
5602        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5603        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5604        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5605        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5606        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5607        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5608
5609        synchronized (mPackages) {
5610            final int count = candidates.size();
5611            // First, try to use linked apps. Partition the candidates into four lists:
5612            // one for the final results, one for the "do not use ever", one for "undefined status"
5613            // and finally one for "browser app type".
5614            for (int n=0; n<count; n++) {
5615                ResolveInfo info = candidates.get(n);
5616                String packageName = info.activityInfo.packageName;
5617                PackageSetting ps = mSettings.mPackages.get(packageName);
5618                if (ps != null) {
5619                    // Add to the special match all list (Browser use case)
5620                    if (info.handleAllWebDataURI) {
5621                        matchAllList.add(info);
5622                        continue;
5623                    }
5624                    // Try to get the status from User settings first
5625                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5626                    int status = (int)(packedStatus >> 32);
5627                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5628                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5629                        if (DEBUG_DOMAIN_VERIFICATION) {
5630                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5631                                    + " : linkgen=" + linkGeneration);
5632                        }
5633                        // Use link-enabled generation as preferredOrder, i.e.
5634                        // prefer newly-enabled over earlier-enabled.
5635                        info.preferredOrder = linkGeneration;
5636                        alwaysList.add(info);
5637                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5638                        if (DEBUG_DOMAIN_VERIFICATION) {
5639                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5640                        }
5641                        neverList.add(info);
5642                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5643                        if (DEBUG_DOMAIN_VERIFICATION) {
5644                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5645                        }
5646                        alwaysAskList.add(info);
5647                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5648                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5649                        if (DEBUG_DOMAIN_VERIFICATION) {
5650                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5651                        }
5652                        undefinedList.add(info);
5653                    }
5654                }
5655            }
5656
5657            // We'll want to include browser possibilities in a few cases
5658            boolean includeBrowser = false;
5659
5660            // First try to add the "always" resolution(s) for the current user, if any
5661            if (alwaysList.size() > 0) {
5662                result.addAll(alwaysList);
5663            } else {
5664                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5665                result.addAll(undefinedList);
5666                // Maybe add one for the other profile.
5667                if (xpDomainInfo != null && (
5668                        xpDomainInfo.bestDomainVerificationStatus
5669                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5670                    result.add(xpDomainInfo.resolveInfo);
5671                }
5672                includeBrowser = true;
5673            }
5674
5675            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5676            // If there were 'always' entries their preferred order has been set, so we also
5677            // back that off to make the alternatives equivalent
5678            if (alwaysAskList.size() > 0) {
5679                for (ResolveInfo i : result) {
5680                    i.preferredOrder = 0;
5681                }
5682                result.addAll(alwaysAskList);
5683                includeBrowser = true;
5684            }
5685
5686            if (includeBrowser) {
5687                // Also add browsers (all of them or only the default one)
5688                if (DEBUG_DOMAIN_VERIFICATION) {
5689                    Slog.v(TAG, "   ...including browsers in candidate set");
5690                }
5691                if ((matchFlags & MATCH_ALL) != 0) {
5692                    result.addAll(matchAllList);
5693                } else {
5694                    // Browser/generic handling case.  If there's a default browser, go straight
5695                    // to that (but only if there is no other higher-priority match).
5696                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5697                    int maxMatchPrio = 0;
5698                    ResolveInfo defaultBrowserMatch = null;
5699                    final int numCandidates = matchAllList.size();
5700                    for (int n = 0; n < numCandidates; n++) {
5701                        ResolveInfo info = matchAllList.get(n);
5702                        // track the highest overall match priority...
5703                        if (info.priority > maxMatchPrio) {
5704                            maxMatchPrio = info.priority;
5705                        }
5706                        // ...and the highest-priority default browser match
5707                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5708                            if (defaultBrowserMatch == null
5709                                    || (defaultBrowserMatch.priority < info.priority)) {
5710                                if (debug) {
5711                                    Slog.v(TAG, "Considering default browser match " + info);
5712                                }
5713                                defaultBrowserMatch = info;
5714                            }
5715                        }
5716                    }
5717                    if (defaultBrowserMatch != null
5718                            && defaultBrowserMatch.priority >= maxMatchPrio
5719                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5720                    {
5721                        if (debug) {
5722                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5723                        }
5724                        result.add(defaultBrowserMatch);
5725                    } else {
5726                        result.addAll(matchAllList);
5727                    }
5728                }
5729
5730                // If there is nothing selected, add all candidates and remove the ones that the user
5731                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5732                if (result.size() == 0) {
5733                    result.addAll(candidates);
5734                    result.removeAll(neverList);
5735                }
5736            }
5737        }
5738        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5739            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5740                    result.size());
5741            for (ResolveInfo info : result) {
5742                Slog.v(TAG, "  + " + info.activityInfo);
5743            }
5744        }
5745        return result;
5746    }
5747
5748    // Returns a packed value as a long:
5749    //
5750    // high 'int'-sized word: link status: undefined/ask/never/always.
5751    // low 'int'-sized word: relative priority among 'always' results.
5752    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5753        long result = ps.getDomainVerificationStatusForUser(userId);
5754        // if none available, get the master status
5755        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5756            if (ps.getIntentFilterVerificationInfo() != null) {
5757                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5758            }
5759        }
5760        return result;
5761    }
5762
5763    private ResolveInfo querySkipCurrentProfileIntents(
5764            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5765            int flags, int sourceUserId) {
5766        if (matchingFilters != null) {
5767            int size = matchingFilters.size();
5768            for (int i = 0; i < size; i ++) {
5769                CrossProfileIntentFilter filter = matchingFilters.get(i);
5770                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5771                    // Checking if there are activities in the target user that can handle the
5772                    // intent.
5773                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5774                            resolvedType, flags, sourceUserId);
5775                    if (resolveInfo != null) {
5776                        return resolveInfo;
5777                    }
5778                }
5779            }
5780        }
5781        return null;
5782    }
5783
5784    // Return matching ResolveInfo in target user if any.
5785    private ResolveInfo queryCrossProfileIntents(
5786            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5787            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5788        if (matchingFilters != null) {
5789            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5790            // match the same intent. For performance reasons, it is better not to
5791            // run queryIntent twice for the same userId
5792            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5793            int size = matchingFilters.size();
5794            for (int i = 0; i < size; i++) {
5795                CrossProfileIntentFilter filter = matchingFilters.get(i);
5796                int targetUserId = filter.getTargetUserId();
5797                boolean skipCurrentProfile =
5798                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5799                boolean skipCurrentProfileIfNoMatchFound =
5800                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5801                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5802                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5803                    // Checking if there are activities in the target user that can handle the
5804                    // intent.
5805                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5806                            resolvedType, flags, sourceUserId);
5807                    if (resolveInfo != null) return resolveInfo;
5808                    alreadyTriedUserIds.put(targetUserId, true);
5809                }
5810            }
5811        }
5812        return null;
5813    }
5814
5815    /**
5816     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5817     * will forward the intent to the filter's target user.
5818     * Otherwise, returns null.
5819     */
5820    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5821            String resolvedType, int flags, int sourceUserId) {
5822        int targetUserId = filter.getTargetUserId();
5823        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5824                resolvedType, flags, targetUserId);
5825        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5826            // If all the matches in the target profile are suspended, return null.
5827            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5828                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5829                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5830                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5831                            targetUserId);
5832                }
5833            }
5834        }
5835        return null;
5836    }
5837
5838    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5839            int sourceUserId, int targetUserId) {
5840        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5841        long ident = Binder.clearCallingIdentity();
5842        boolean targetIsProfile;
5843        try {
5844            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5845        } finally {
5846            Binder.restoreCallingIdentity(ident);
5847        }
5848        String className;
5849        if (targetIsProfile) {
5850            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5851        } else {
5852            className = FORWARD_INTENT_TO_PARENT;
5853        }
5854        ComponentName forwardingActivityComponentName = new ComponentName(
5855                mAndroidApplication.packageName, className);
5856        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5857                sourceUserId);
5858        if (!targetIsProfile) {
5859            forwardingActivityInfo.showUserIcon = targetUserId;
5860            forwardingResolveInfo.noResourceId = true;
5861        }
5862        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5863        forwardingResolveInfo.priority = 0;
5864        forwardingResolveInfo.preferredOrder = 0;
5865        forwardingResolveInfo.match = 0;
5866        forwardingResolveInfo.isDefault = true;
5867        forwardingResolveInfo.filter = filter;
5868        forwardingResolveInfo.targetUserId = targetUserId;
5869        return forwardingResolveInfo;
5870    }
5871
5872    @Override
5873    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5874            Intent[] specifics, String[] specificTypes, Intent intent,
5875            String resolvedType, int flags, int userId) {
5876        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5877                specificTypes, intent, resolvedType, flags, userId));
5878    }
5879
5880    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5881            Intent[] specifics, String[] specificTypes, Intent intent,
5882            String resolvedType, int flags, int userId) {
5883        if (!sUserManager.exists(userId)) return Collections.emptyList();
5884        flags = updateFlagsForResolve(flags, userId, intent);
5885        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5886                false /* requireFullPermission */, false /* checkShell */,
5887                "query intent activity options");
5888        final String resultsAction = intent.getAction();
5889
5890        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5891                | PackageManager.GET_RESOLVED_FILTER, userId);
5892
5893        if (DEBUG_INTENT_MATCHING) {
5894            Log.v(TAG, "Query " + intent + ": " + results);
5895        }
5896
5897        int specificsPos = 0;
5898        int N;
5899
5900        // todo: note that the algorithm used here is O(N^2).  This
5901        // isn't a problem in our current environment, but if we start running
5902        // into situations where we have more than 5 or 10 matches then this
5903        // should probably be changed to something smarter...
5904
5905        // First we go through and resolve each of the specific items
5906        // that were supplied, taking care of removing any corresponding
5907        // duplicate items in the generic resolve list.
5908        if (specifics != null) {
5909            for (int i=0; i<specifics.length; i++) {
5910                final Intent sintent = specifics[i];
5911                if (sintent == null) {
5912                    continue;
5913                }
5914
5915                if (DEBUG_INTENT_MATCHING) {
5916                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5917                }
5918
5919                String action = sintent.getAction();
5920                if (resultsAction != null && resultsAction.equals(action)) {
5921                    // If this action was explicitly requested, then don't
5922                    // remove things that have it.
5923                    action = null;
5924                }
5925
5926                ResolveInfo ri = null;
5927                ActivityInfo ai = null;
5928
5929                ComponentName comp = sintent.getComponent();
5930                if (comp == null) {
5931                    ri = resolveIntent(
5932                        sintent,
5933                        specificTypes != null ? specificTypes[i] : null,
5934                            flags, userId);
5935                    if (ri == null) {
5936                        continue;
5937                    }
5938                    if (ri == mResolveInfo) {
5939                        // ACK!  Must do something better with this.
5940                    }
5941                    ai = ri.activityInfo;
5942                    comp = new ComponentName(ai.applicationInfo.packageName,
5943                            ai.name);
5944                } else {
5945                    ai = getActivityInfo(comp, flags, userId);
5946                    if (ai == null) {
5947                        continue;
5948                    }
5949                }
5950
5951                // Look for any generic query activities that are duplicates
5952                // of this specific one, and remove them from the results.
5953                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5954                N = results.size();
5955                int j;
5956                for (j=specificsPos; j<N; j++) {
5957                    ResolveInfo sri = results.get(j);
5958                    if ((sri.activityInfo.name.equals(comp.getClassName())
5959                            && sri.activityInfo.applicationInfo.packageName.equals(
5960                                    comp.getPackageName()))
5961                        || (action != null && sri.filter.matchAction(action))) {
5962                        results.remove(j);
5963                        if (DEBUG_INTENT_MATCHING) Log.v(
5964                            TAG, "Removing duplicate item from " + j
5965                            + " due to specific " + specificsPos);
5966                        if (ri == null) {
5967                            ri = sri;
5968                        }
5969                        j--;
5970                        N--;
5971                    }
5972                }
5973
5974                // Add this specific item to its proper place.
5975                if (ri == null) {
5976                    ri = new ResolveInfo();
5977                    ri.activityInfo = ai;
5978                }
5979                results.add(specificsPos, ri);
5980                ri.specificIndex = i;
5981                specificsPos++;
5982            }
5983        }
5984
5985        // Now we go through the remaining generic results and remove any
5986        // duplicate actions that are found here.
5987        N = results.size();
5988        for (int i=specificsPos; i<N-1; i++) {
5989            final ResolveInfo rii = results.get(i);
5990            if (rii.filter == null) {
5991                continue;
5992            }
5993
5994            // Iterate over all of the actions of this result's intent
5995            // filter...  typically this should be just one.
5996            final Iterator<String> it = rii.filter.actionsIterator();
5997            if (it == null) {
5998                continue;
5999            }
6000            while (it.hasNext()) {
6001                final String action = it.next();
6002                if (resultsAction != null && resultsAction.equals(action)) {
6003                    // If this action was explicitly requested, then don't
6004                    // remove things that have it.
6005                    continue;
6006                }
6007                for (int j=i+1; j<N; j++) {
6008                    final ResolveInfo rij = results.get(j);
6009                    if (rij.filter != null && rij.filter.hasAction(action)) {
6010                        results.remove(j);
6011                        if (DEBUG_INTENT_MATCHING) Log.v(
6012                            TAG, "Removing duplicate item from " + j
6013                            + " due to action " + action + " at " + i);
6014                        j--;
6015                        N--;
6016                    }
6017                }
6018            }
6019
6020            // If the caller didn't request filter information, drop it now
6021            // so we don't have to marshall/unmarshall it.
6022            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6023                rii.filter = null;
6024            }
6025        }
6026
6027        // Filter out the caller activity if so requested.
6028        if (caller != null) {
6029            N = results.size();
6030            for (int i=0; i<N; i++) {
6031                ActivityInfo ainfo = results.get(i).activityInfo;
6032                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6033                        && caller.getClassName().equals(ainfo.name)) {
6034                    results.remove(i);
6035                    break;
6036                }
6037            }
6038        }
6039
6040        // If the caller didn't request filter information,
6041        // drop them now so we don't have to
6042        // marshall/unmarshall it.
6043        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6044            N = results.size();
6045            for (int i=0; i<N; i++) {
6046                results.get(i).filter = null;
6047            }
6048        }
6049
6050        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6051        return results;
6052    }
6053
6054    @Override
6055    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6056            String resolvedType, int flags, int userId) {
6057        return new ParceledListSlice<>(
6058                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6059    }
6060
6061    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6062            String resolvedType, int flags, int userId) {
6063        if (!sUserManager.exists(userId)) return Collections.emptyList();
6064        flags = updateFlagsForResolve(flags, userId, intent);
6065        ComponentName comp = intent.getComponent();
6066        if (comp == null) {
6067            if (intent.getSelector() != null) {
6068                intent = intent.getSelector();
6069                comp = intent.getComponent();
6070            }
6071        }
6072        if (comp != null) {
6073            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6074            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6075            if (ai != null) {
6076                ResolveInfo ri = new ResolveInfo();
6077                ri.activityInfo = ai;
6078                list.add(ri);
6079            }
6080            return list;
6081        }
6082
6083        // reader
6084        synchronized (mPackages) {
6085            String pkgName = intent.getPackage();
6086            if (pkgName == null) {
6087                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6088            }
6089            final PackageParser.Package pkg = mPackages.get(pkgName);
6090            if (pkg != null) {
6091                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6092                        userId);
6093            }
6094            return Collections.emptyList();
6095        }
6096    }
6097
6098    @Override
6099    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6100        if (!sUserManager.exists(userId)) return null;
6101        flags = updateFlagsForResolve(flags, userId, intent);
6102        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6103        if (query != null) {
6104            if (query.size() >= 1) {
6105                // If there is more than one service with the same priority,
6106                // just arbitrarily pick the first one.
6107                return query.get(0);
6108            }
6109        }
6110        return null;
6111    }
6112
6113    @Override
6114    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6115            String resolvedType, int flags, int userId) {
6116        return new ParceledListSlice<>(
6117                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6118    }
6119
6120    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6121            String resolvedType, int flags, int userId) {
6122        if (!sUserManager.exists(userId)) return Collections.emptyList();
6123        flags = updateFlagsForResolve(flags, userId, intent);
6124        ComponentName comp = intent.getComponent();
6125        if (comp == null) {
6126            if (intent.getSelector() != null) {
6127                intent = intent.getSelector();
6128                comp = intent.getComponent();
6129            }
6130        }
6131        if (comp != null) {
6132            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6133            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6134            if (si != null) {
6135                final ResolveInfo ri = new ResolveInfo();
6136                ri.serviceInfo = si;
6137                list.add(ri);
6138            }
6139            return list;
6140        }
6141
6142        // reader
6143        synchronized (mPackages) {
6144            String pkgName = intent.getPackage();
6145            if (pkgName == null) {
6146                return mServices.queryIntent(intent, resolvedType, flags, userId);
6147            }
6148            final PackageParser.Package pkg = mPackages.get(pkgName);
6149            if (pkg != null) {
6150                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6151                        userId);
6152            }
6153            return Collections.emptyList();
6154        }
6155    }
6156
6157    @Override
6158    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6159            String resolvedType, int flags, int userId) {
6160        return new ParceledListSlice<>(
6161                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6162    }
6163
6164    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6165            Intent intent, String resolvedType, int flags, int userId) {
6166        if (!sUserManager.exists(userId)) return Collections.emptyList();
6167        flags = updateFlagsForResolve(flags, userId, intent);
6168        ComponentName comp = intent.getComponent();
6169        if (comp == null) {
6170            if (intent.getSelector() != null) {
6171                intent = intent.getSelector();
6172                comp = intent.getComponent();
6173            }
6174        }
6175        if (comp != null) {
6176            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6177            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6178            if (pi != null) {
6179                final ResolveInfo ri = new ResolveInfo();
6180                ri.providerInfo = pi;
6181                list.add(ri);
6182            }
6183            return list;
6184        }
6185
6186        // reader
6187        synchronized (mPackages) {
6188            String pkgName = intent.getPackage();
6189            if (pkgName == null) {
6190                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6191            }
6192            final PackageParser.Package pkg = mPackages.get(pkgName);
6193            if (pkg != null) {
6194                return mProviders.queryIntentForPackage(
6195                        intent, resolvedType, flags, pkg.providers, userId);
6196            }
6197            return Collections.emptyList();
6198        }
6199    }
6200
6201    @Override
6202    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6203        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6204        flags = updateFlagsForPackage(flags, userId, null);
6205        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6206        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6207                true /* requireFullPermission */, false /* checkShell */,
6208                "get installed packages");
6209
6210        // writer
6211        synchronized (mPackages) {
6212            ArrayList<PackageInfo> list;
6213            if (listUninstalled) {
6214                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6215                for (PackageSetting ps : mSettings.mPackages.values()) {
6216                    final PackageInfo pi;
6217                    if (ps.pkg != null) {
6218                        pi = generatePackageInfo(ps, flags, userId);
6219                    } else {
6220                        pi = generatePackageInfo(ps, flags, userId);
6221                    }
6222                    if (pi != null) {
6223                        list.add(pi);
6224                    }
6225                }
6226            } else {
6227                list = new ArrayList<PackageInfo>(mPackages.size());
6228                for (PackageParser.Package p : mPackages.values()) {
6229                    final PackageInfo pi =
6230                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6231                    if (pi != null) {
6232                        list.add(pi);
6233                    }
6234                }
6235            }
6236
6237            return new ParceledListSlice<PackageInfo>(list);
6238        }
6239    }
6240
6241    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6242            String[] permissions, boolean[] tmp, int flags, int userId) {
6243        int numMatch = 0;
6244        final PermissionsState permissionsState = ps.getPermissionsState();
6245        for (int i=0; i<permissions.length; i++) {
6246            final String permission = permissions[i];
6247            if (permissionsState.hasPermission(permission, userId)) {
6248                tmp[i] = true;
6249                numMatch++;
6250            } else {
6251                tmp[i] = false;
6252            }
6253        }
6254        if (numMatch == 0) {
6255            return;
6256        }
6257        final PackageInfo pi;
6258        if (ps.pkg != null) {
6259            pi = generatePackageInfo(ps, flags, userId);
6260        } else {
6261            pi = generatePackageInfo(ps, flags, userId);
6262        }
6263        // The above might return null in cases of uninstalled apps or install-state
6264        // skew across users/profiles.
6265        if (pi != null) {
6266            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6267                if (numMatch == permissions.length) {
6268                    pi.requestedPermissions = permissions;
6269                } else {
6270                    pi.requestedPermissions = new String[numMatch];
6271                    numMatch = 0;
6272                    for (int i=0; i<permissions.length; i++) {
6273                        if (tmp[i]) {
6274                            pi.requestedPermissions[numMatch] = permissions[i];
6275                            numMatch++;
6276                        }
6277                    }
6278                }
6279            }
6280            list.add(pi);
6281        }
6282    }
6283
6284    @Override
6285    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6286            String[] permissions, int flags, int userId) {
6287        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6288        flags = updateFlagsForPackage(flags, userId, permissions);
6289        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6290
6291        // writer
6292        synchronized (mPackages) {
6293            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6294            boolean[] tmpBools = new boolean[permissions.length];
6295            if (listUninstalled) {
6296                for (PackageSetting ps : mSettings.mPackages.values()) {
6297                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6298                }
6299            } else {
6300                for (PackageParser.Package pkg : mPackages.values()) {
6301                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6302                    if (ps != null) {
6303                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6304                                userId);
6305                    }
6306                }
6307            }
6308
6309            return new ParceledListSlice<PackageInfo>(list);
6310        }
6311    }
6312
6313    @Override
6314    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6315        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6316        flags = updateFlagsForApplication(flags, userId, null);
6317        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6318
6319        // writer
6320        synchronized (mPackages) {
6321            ArrayList<ApplicationInfo> list;
6322            if (listUninstalled) {
6323                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6324                for (PackageSetting ps : mSettings.mPackages.values()) {
6325                    ApplicationInfo ai;
6326                    if (ps.pkg != null) {
6327                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6328                                ps.readUserState(userId), userId);
6329                    } else {
6330                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6331                    }
6332                    if (ai != null) {
6333                        list.add(ai);
6334                    }
6335                }
6336            } else {
6337                list = new ArrayList<ApplicationInfo>(mPackages.size());
6338                for (PackageParser.Package p : mPackages.values()) {
6339                    if (p.mExtras != null) {
6340                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6341                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6342                        if (ai != null) {
6343                            list.add(ai);
6344                        }
6345                    }
6346                }
6347            }
6348
6349            return new ParceledListSlice<ApplicationInfo>(list);
6350        }
6351    }
6352
6353    @Override
6354    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6355        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6356            return null;
6357        }
6358
6359        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6360                "getEphemeralApplications");
6361        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6362                true /* requireFullPermission */, false /* checkShell */,
6363                "getEphemeralApplications");
6364        synchronized (mPackages) {
6365            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6366                    .getEphemeralApplicationsLPw(userId);
6367            if (ephemeralApps != null) {
6368                return new ParceledListSlice<>(ephemeralApps);
6369            }
6370        }
6371        return null;
6372    }
6373
6374    @Override
6375    public boolean isEphemeralApplication(String packageName, int userId) {
6376        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6377                true /* requireFullPermission */, false /* checkShell */,
6378                "isEphemeral");
6379        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6380            return false;
6381        }
6382
6383        if (!isCallerSameApp(packageName)) {
6384            return false;
6385        }
6386        synchronized (mPackages) {
6387            PackageParser.Package pkg = mPackages.get(packageName);
6388            if (pkg != null) {
6389                return pkg.applicationInfo.isEphemeralApp();
6390            }
6391        }
6392        return false;
6393    }
6394
6395    @Override
6396    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6397        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6398            return null;
6399        }
6400
6401        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6402                true /* requireFullPermission */, false /* checkShell */,
6403                "getCookie");
6404        if (!isCallerSameApp(packageName)) {
6405            return null;
6406        }
6407        synchronized (mPackages) {
6408            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6409                    packageName, userId);
6410        }
6411    }
6412
6413    @Override
6414    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6415        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6416            return true;
6417        }
6418
6419        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6420                true /* requireFullPermission */, true /* checkShell */,
6421                "setCookie");
6422        if (!isCallerSameApp(packageName)) {
6423            return false;
6424        }
6425        synchronized (mPackages) {
6426            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6427                    packageName, cookie, userId);
6428        }
6429    }
6430
6431    @Override
6432    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6433        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6434            return null;
6435        }
6436
6437        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6438                "getEphemeralApplicationIcon");
6439        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6440                true /* requireFullPermission */, false /* checkShell */,
6441                "getEphemeralApplicationIcon");
6442        synchronized (mPackages) {
6443            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6444                    packageName, userId);
6445        }
6446    }
6447
6448    private boolean isCallerSameApp(String packageName) {
6449        PackageParser.Package pkg = mPackages.get(packageName);
6450        return pkg != null
6451                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6452    }
6453
6454    @Override
6455    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6456        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6457    }
6458
6459    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6460        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6461
6462        // reader
6463        synchronized (mPackages) {
6464            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6465            final int userId = UserHandle.getCallingUserId();
6466            while (i.hasNext()) {
6467                final PackageParser.Package p = i.next();
6468                if (p.applicationInfo == null) continue;
6469
6470                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6471                        && !p.applicationInfo.isDirectBootAware();
6472                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6473                        && p.applicationInfo.isDirectBootAware();
6474
6475                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6476                        && (!mSafeMode || isSystemApp(p))
6477                        && (matchesUnaware || matchesAware)) {
6478                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6479                    if (ps != null) {
6480                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6481                                ps.readUserState(userId), userId);
6482                        if (ai != null) {
6483                            finalList.add(ai);
6484                        }
6485                    }
6486                }
6487            }
6488        }
6489
6490        return finalList;
6491    }
6492
6493    @Override
6494    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6495        if (!sUserManager.exists(userId)) return null;
6496        flags = updateFlagsForComponent(flags, userId, name);
6497        // reader
6498        synchronized (mPackages) {
6499            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6500            PackageSetting ps = provider != null
6501                    ? mSettings.mPackages.get(provider.owner.packageName)
6502                    : null;
6503            return ps != null
6504                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6505                    ? PackageParser.generateProviderInfo(provider, flags,
6506                            ps.readUserState(userId), userId)
6507                    : null;
6508        }
6509    }
6510
6511    /**
6512     * @deprecated
6513     */
6514    @Deprecated
6515    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6516        // reader
6517        synchronized (mPackages) {
6518            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6519                    .entrySet().iterator();
6520            final int userId = UserHandle.getCallingUserId();
6521            while (i.hasNext()) {
6522                Map.Entry<String, PackageParser.Provider> entry = i.next();
6523                PackageParser.Provider p = entry.getValue();
6524                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6525
6526                if (ps != null && p.syncable
6527                        && (!mSafeMode || (p.info.applicationInfo.flags
6528                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6529                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6530                            ps.readUserState(userId), userId);
6531                    if (info != null) {
6532                        outNames.add(entry.getKey());
6533                        outInfo.add(info);
6534                    }
6535                }
6536            }
6537        }
6538    }
6539
6540    @Override
6541    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6542            int uid, int flags) {
6543        final int userId = processName != null ? UserHandle.getUserId(uid)
6544                : UserHandle.getCallingUserId();
6545        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6546        flags = updateFlagsForComponent(flags, userId, processName);
6547
6548        ArrayList<ProviderInfo> finalList = null;
6549        // reader
6550        synchronized (mPackages) {
6551            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6552            while (i.hasNext()) {
6553                final PackageParser.Provider p = i.next();
6554                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6555                if (ps != null && p.info.authority != null
6556                        && (processName == null
6557                                || (p.info.processName.equals(processName)
6558                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6559                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6560                    if (finalList == null) {
6561                        finalList = new ArrayList<ProviderInfo>(3);
6562                    }
6563                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6564                            ps.readUserState(userId), userId);
6565                    if (info != null) {
6566                        finalList.add(info);
6567                    }
6568                }
6569            }
6570        }
6571
6572        if (finalList != null) {
6573            Collections.sort(finalList, mProviderInitOrderSorter);
6574            return new ParceledListSlice<ProviderInfo>(finalList);
6575        }
6576
6577        return ParceledListSlice.emptyList();
6578    }
6579
6580    @Override
6581    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6582        // reader
6583        synchronized (mPackages) {
6584            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6585            return PackageParser.generateInstrumentationInfo(i, flags);
6586        }
6587    }
6588
6589    @Override
6590    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6591            String targetPackage, int flags) {
6592        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6593    }
6594
6595    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6596            int flags) {
6597        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6598
6599        // reader
6600        synchronized (mPackages) {
6601            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6602            while (i.hasNext()) {
6603                final PackageParser.Instrumentation p = i.next();
6604                if (targetPackage == null
6605                        || targetPackage.equals(p.info.targetPackage)) {
6606                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6607                            flags);
6608                    if (ii != null) {
6609                        finalList.add(ii);
6610                    }
6611                }
6612            }
6613        }
6614
6615        return finalList;
6616    }
6617
6618    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6619        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6620        if (overlays == null) {
6621            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6622            return;
6623        }
6624        for (PackageParser.Package opkg : overlays.values()) {
6625            // Not much to do if idmap fails: we already logged the error
6626            // and we certainly don't want to abort installation of pkg simply
6627            // because an overlay didn't fit properly. For these reasons,
6628            // ignore the return value of createIdmapForPackagePairLI.
6629            createIdmapForPackagePairLI(pkg, opkg);
6630        }
6631    }
6632
6633    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6634            PackageParser.Package opkg) {
6635        if (!opkg.mTrustedOverlay) {
6636            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6637                    opkg.baseCodePath + ": overlay not trusted");
6638            return false;
6639        }
6640        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6641        if (overlaySet == null) {
6642            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6643                    opkg.baseCodePath + " but target package has no known overlays");
6644            return false;
6645        }
6646        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6647        // TODO: generate idmap for split APKs
6648        try {
6649            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6650        } catch (InstallerException e) {
6651            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6652                    + opkg.baseCodePath);
6653            return false;
6654        }
6655        PackageParser.Package[] overlayArray =
6656            overlaySet.values().toArray(new PackageParser.Package[0]);
6657        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6658            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6659                return p1.mOverlayPriority - p2.mOverlayPriority;
6660            }
6661        };
6662        Arrays.sort(overlayArray, cmp);
6663
6664        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6665        int i = 0;
6666        for (PackageParser.Package p : overlayArray) {
6667            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6668        }
6669        return true;
6670    }
6671
6672    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6673        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6674        try {
6675            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6676        } finally {
6677            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6678        }
6679    }
6680
6681    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6682        final File[] files = dir.listFiles();
6683        if (ArrayUtils.isEmpty(files)) {
6684            Log.d(TAG, "No files in app dir " + dir);
6685            return;
6686        }
6687
6688        if (DEBUG_PACKAGE_SCANNING) {
6689            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6690                    + " flags=0x" + Integer.toHexString(parseFlags));
6691        }
6692
6693        for (File file : files) {
6694            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6695                    && !PackageInstallerService.isStageName(file.getName());
6696            if (!isPackage) {
6697                // Ignore entries which are not packages
6698                continue;
6699            }
6700            try {
6701                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6702                        scanFlags, currentTime, null);
6703            } catch (PackageManagerException e) {
6704                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6705
6706                // Delete invalid userdata apps
6707                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6708                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6709                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6710                    removeCodePathLI(file);
6711                }
6712            }
6713        }
6714    }
6715
6716    private static File getSettingsProblemFile() {
6717        File dataDir = Environment.getDataDirectory();
6718        File systemDir = new File(dataDir, "system");
6719        File fname = new File(systemDir, "uiderrors.txt");
6720        return fname;
6721    }
6722
6723    static void reportSettingsProblem(int priority, String msg) {
6724        logCriticalInfo(priority, msg);
6725    }
6726
6727    static void logCriticalInfo(int priority, String msg) {
6728        Slog.println(priority, TAG, msg);
6729        EventLogTags.writePmCriticalInfo(msg);
6730        try {
6731            File fname = getSettingsProblemFile();
6732            FileOutputStream out = new FileOutputStream(fname, true);
6733            PrintWriter pw = new FastPrintWriter(out);
6734            SimpleDateFormat formatter = new SimpleDateFormat();
6735            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6736            pw.println(dateString + ": " + msg);
6737            pw.close();
6738            FileUtils.setPermissions(
6739                    fname.toString(),
6740                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6741                    -1, -1);
6742        } catch (java.io.IOException e) {
6743        }
6744    }
6745
6746    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6747        if (srcFile.isDirectory()) {
6748            final File baseFile = new File(pkg.baseCodePath);
6749            long maxModifiedTime = baseFile.lastModified();
6750            if (pkg.splitCodePaths != null) {
6751                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6752                    final File splitFile = new File(pkg.splitCodePaths[i]);
6753                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6754                }
6755            }
6756            return maxModifiedTime;
6757        }
6758        return srcFile.lastModified();
6759    }
6760
6761    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6762            final int policyFlags) throws PackageManagerException {
6763        // When upgrading from pre-N MR1, verify the package time stamp using the package
6764        // directory and not the APK file.
6765        final long lastModifiedTime = mIsPreNMR1Upgrade
6766                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6767        if (ps != null
6768                && ps.codePath.equals(srcFile)
6769                && ps.timeStamp == lastModifiedTime
6770                && !isCompatSignatureUpdateNeeded(pkg)
6771                && !isRecoverSignatureUpdateNeeded(pkg)) {
6772            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6773            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6774            ArraySet<PublicKey> signingKs;
6775            synchronized (mPackages) {
6776                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6777            }
6778            if (ps.signatures.mSignatures != null
6779                    && ps.signatures.mSignatures.length != 0
6780                    && signingKs != null) {
6781                // Optimization: reuse the existing cached certificates
6782                // if the package appears to be unchanged.
6783                pkg.mSignatures = ps.signatures.mSignatures;
6784                pkg.mSigningKeys = signingKs;
6785                return;
6786            }
6787
6788            Slog.w(TAG, "PackageSetting for " + ps.name
6789                    + " is missing signatures.  Collecting certs again to recover them.");
6790        } else {
6791            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6792        }
6793
6794        try {
6795            PackageParser.collectCertificates(pkg, policyFlags);
6796        } catch (PackageParserException e) {
6797            throw PackageManagerException.from(e);
6798        }
6799    }
6800
6801    /**
6802     *  Traces a package scan.
6803     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6804     */
6805    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6806            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6807        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6808        try {
6809            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6810        } finally {
6811            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6812        }
6813    }
6814
6815    /**
6816     *  Scans a package and returns the newly parsed package.
6817     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6818     */
6819    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6820            long currentTime, UserHandle user) throws PackageManagerException {
6821        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6822        PackageParser pp = new PackageParser();
6823        pp.setSeparateProcesses(mSeparateProcesses);
6824        pp.setOnlyCoreApps(mOnlyCore);
6825        pp.setDisplayMetrics(mMetrics);
6826
6827        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6828            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6829        }
6830
6831        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6832        final PackageParser.Package pkg;
6833        try {
6834            pkg = pp.parsePackage(scanFile, parseFlags);
6835        } catch (PackageParserException e) {
6836            throw PackageManagerException.from(e);
6837        } finally {
6838            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6839        }
6840
6841        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6842    }
6843
6844    /**
6845     *  Scans a package and returns the newly parsed package.
6846     *  @throws PackageManagerException on a parse error.
6847     */
6848    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6849            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6850            throws PackageManagerException {
6851        // If the package has children and this is the first dive in the function
6852        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6853        // packages (parent and children) would be successfully scanned before the
6854        // actual scan since scanning mutates internal state and we want to atomically
6855        // install the package and its children.
6856        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6857            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6858                scanFlags |= SCAN_CHECK_ONLY;
6859            }
6860        } else {
6861            scanFlags &= ~SCAN_CHECK_ONLY;
6862        }
6863
6864        // Scan the parent
6865        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6866                scanFlags, currentTime, user);
6867
6868        // Scan the children
6869        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6870        for (int i = 0; i < childCount; i++) {
6871            PackageParser.Package childPackage = pkg.childPackages.get(i);
6872            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6873                    currentTime, user);
6874        }
6875
6876
6877        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6878            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6879        }
6880
6881        return scannedPkg;
6882    }
6883
6884    /**
6885     *  Scans a package and returns the newly parsed package.
6886     *  @throws PackageManagerException on a parse error.
6887     */
6888    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6889            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6890            throws PackageManagerException {
6891        PackageSetting ps = null;
6892        PackageSetting updatedPkg;
6893        // reader
6894        synchronized (mPackages) {
6895            // Look to see if we already know about this package.
6896            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6897            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6898                // This package has been renamed to its original name.  Let's
6899                // use that.
6900                ps = mSettings.peekPackageLPr(oldName);
6901            }
6902            // If there was no original package, see one for the real package name.
6903            if (ps == null) {
6904                ps = mSettings.peekPackageLPr(pkg.packageName);
6905            }
6906            // Check to see if this package could be hiding/updating a system
6907            // package.  Must look for it either under the original or real
6908            // package name depending on our state.
6909            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6910            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6911
6912            // If this is a package we don't know about on the system partition, we
6913            // may need to remove disabled child packages on the system partition
6914            // or may need to not add child packages if the parent apk is updated
6915            // on the data partition and no longer defines this child package.
6916            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6917                // If this is a parent package for an updated system app and this system
6918                // app got an OTA update which no longer defines some of the child packages
6919                // we have to prune them from the disabled system packages.
6920                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6921                if (disabledPs != null) {
6922                    final int scannedChildCount = (pkg.childPackages != null)
6923                            ? pkg.childPackages.size() : 0;
6924                    final int disabledChildCount = disabledPs.childPackageNames != null
6925                            ? disabledPs.childPackageNames.size() : 0;
6926                    for (int i = 0; i < disabledChildCount; i++) {
6927                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6928                        boolean disabledPackageAvailable = false;
6929                        for (int j = 0; j < scannedChildCount; j++) {
6930                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6931                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6932                                disabledPackageAvailable = true;
6933                                break;
6934                            }
6935                         }
6936                         if (!disabledPackageAvailable) {
6937                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6938                         }
6939                    }
6940                }
6941            }
6942        }
6943
6944        boolean updatedPkgBetter = false;
6945        // First check if this is a system package that may involve an update
6946        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6947            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6948            // it needs to drop FLAG_PRIVILEGED.
6949            if (locationIsPrivileged(scanFile)) {
6950                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6951            } else {
6952                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6953            }
6954
6955            if (ps != null && !ps.codePath.equals(scanFile)) {
6956                // The path has changed from what was last scanned...  check the
6957                // version of the new path against what we have stored to determine
6958                // what to do.
6959                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6960                if (pkg.mVersionCode <= ps.versionCode) {
6961                    // The system package has been updated and the code path does not match
6962                    // Ignore entry. Skip it.
6963                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6964                            + " ignored: updated version " + ps.versionCode
6965                            + " better than this " + pkg.mVersionCode);
6966                    if (!updatedPkg.codePath.equals(scanFile)) {
6967                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6968                                + ps.name + " changing from " + updatedPkg.codePathString
6969                                + " to " + scanFile);
6970                        updatedPkg.codePath = scanFile;
6971                        updatedPkg.codePathString = scanFile.toString();
6972                        updatedPkg.resourcePath = scanFile;
6973                        updatedPkg.resourcePathString = scanFile.toString();
6974                    }
6975                    updatedPkg.pkg = pkg;
6976                    updatedPkg.versionCode = pkg.mVersionCode;
6977
6978                    // Update the disabled system child packages to point to the package too.
6979                    final int childCount = updatedPkg.childPackageNames != null
6980                            ? updatedPkg.childPackageNames.size() : 0;
6981                    for (int i = 0; i < childCount; i++) {
6982                        String childPackageName = updatedPkg.childPackageNames.get(i);
6983                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6984                                childPackageName);
6985                        if (updatedChildPkg != null) {
6986                            updatedChildPkg.pkg = pkg;
6987                            updatedChildPkg.versionCode = pkg.mVersionCode;
6988                        }
6989                    }
6990
6991                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6992                            + scanFile + " ignored: updated version " + ps.versionCode
6993                            + " better than this " + pkg.mVersionCode);
6994                } else {
6995                    // The current app on the system partition is better than
6996                    // what we have updated to on the data partition; switch
6997                    // back to the system partition version.
6998                    // At this point, its safely assumed that package installation for
6999                    // apps in system partition will go through. If not there won't be a working
7000                    // version of the app
7001                    // writer
7002                    synchronized (mPackages) {
7003                        // Just remove the loaded entries from package lists.
7004                        mPackages.remove(ps.name);
7005                    }
7006
7007                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7008                            + " reverting from " + ps.codePathString
7009                            + ": new version " + pkg.mVersionCode
7010                            + " better than installed " + ps.versionCode);
7011
7012                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7013                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7014                    synchronized (mInstallLock) {
7015                        args.cleanUpResourcesLI();
7016                    }
7017                    synchronized (mPackages) {
7018                        mSettings.enableSystemPackageLPw(ps.name);
7019                    }
7020                    updatedPkgBetter = true;
7021                }
7022            }
7023        }
7024
7025        if (updatedPkg != null) {
7026            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7027            // initially
7028            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7029
7030            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7031            // flag set initially
7032            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7033                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7034            }
7035        }
7036
7037        // Verify certificates against what was last scanned
7038        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7039
7040        /*
7041         * A new system app appeared, but we already had a non-system one of the
7042         * same name installed earlier.
7043         */
7044        boolean shouldHideSystemApp = false;
7045        if (updatedPkg == null && ps != null
7046                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7047            /*
7048             * Check to make sure the signatures match first. If they don't,
7049             * wipe the installed application and its data.
7050             */
7051            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7052                    != PackageManager.SIGNATURE_MATCH) {
7053                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7054                        + " signatures don't match existing userdata copy; removing");
7055                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7056                        "scanPackageInternalLI")) {
7057                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7058                }
7059                ps = null;
7060            } else {
7061                /*
7062                 * If the newly-added system app is an older version than the
7063                 * already installed version, hide it. It will be scanned later
7064                 * and re-added like an update.
7065                 */
7066                if (pkg.mVersionCode <= ps.versionCode) {
7067                    shouldHideSystemApp = true;
7068                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7069                            + " but new version " + pkg.mVersionCode + " better than installed "
7070                            + ps.versionCode + "; hiding system");
7071                } else {
7072                    /*
7073                     * The newly found system app is a newer version that the
7074                     * one previously installed. Simply remove the
7075                     * already-installed application and replace it with our own
7076                     * while keeping the application data.
7077                     */
7078                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7079                            + " reverting from " + ps.codePathString + ": new version "
7080                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7081                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7082                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7083                    synchronized (mInstallLock) {
7084                        args.cleanUpResourcesLI();
7085                    }
7086                }
7087            }
7088        }
7089
7090        // The apk is forward locked (not public) if its code and resources
7091        // are kept in different files. (except for app in either system or
7092        // vendor path).
7093        // TODO grab this value from PackageSettings
7094        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7095            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7096                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7097            }
7098        }
7099
7100        // TODO: extend to support forward-locked splits
7101        String resourcePath = null;
7102        String baseResourcePath = null;
7103        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7104            if (ps != null && ps.resourcePathString != null) {
7105                resourcePath = ps.resourcePathString;
7106                baseResourcePath = ps.resourcePathString;
7107            } else {
7108                // Should not happen at all. Just log an error.
7109                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7110            }
7111        } else {
7112            resourcePath = pkg.codePath;
7113            baseResourcePath = pkg.baseCodePath;
7114        }
7115
7116        // Set application objects path explicitly.
7117        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7118        pkg.setApplicationInfoCodePath(pkg.codePath);
7119        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7120        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7121        pkg.setApplicationInfoResourcePath(resourcePath);
7122        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7123        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7124
7125        // Note that we invoke the following method only if we are about to unpack an application
7126        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7127                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7128
7129        /*
7130         * If the system app should be overridden by a previously installed
7131         * data, hide the system app now and let the /data/app scan pick it up
7132         * again.
7133         */
7134        if (shouldHideSystemApp) {
7135            synchronized (mPackages) {
7136                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7137            }
7138        }
7139
7140        return scannedPkg;
7141    }
7142
7143    private static String fixProcessName(String defProcessName,
7144            String processName, int uid) {
7145        if (processName == null) {
7146            return defProcessName;
7147        }
7148        return processName;
7149    }
7150
7151    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7152            throws PackageManagerException {
7153        if (pkgSetting.signatures.mSignatures != null) {
7154            // Already existing package. Make sure signatures match
7155            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7156                    == PackageManager.SIGNATURE_MATCH;
7157            if (!match) {
7158                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7159                        == PackageManager.SIGNATURE_MATCH;
7160            }
7161            if (!match) {
7162                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7163                        == PackageManager.SIGNATURE_MATCH;
7164            }
7165            if (!match) {
7166                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7167                        + pkg.packageName + " signatures do not match the "
7168                        + "previously installed version; ignoring!");
7169            }
7170        }
7171
7172        // Check for shared user signatures
7173        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7174            // Already existing package. Make sure signatures match
7175            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7176                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7177            if (!match) {
7178                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7179                        == PackageManager.SIGNATURE_MATCH;
7180            }
7181            if (!match) {
7182                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7183                        == PackageManager.SIGNATURE_MATCH;
7184            }
7185            if (!match) {
7186                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7187                        "Package " + pkg.packageName
7188                        + " has no signatures that match those in shared user "
7189                        + pkgSetting.sharedUser.name + "; ignoring!");
7190            }
7191        }
7192    }
7193
7194    /**
7195     * Enforces that only the system UID or root's UID can call a method exposed
7196     * via Binder.
7197     *
7198     * @param message used as message if SecurityException is thrown
7199     * @throws SecurityException if the caller is not system or root
7200     */
7201    private static final void enforceSystemOrRoot(String message) {
7202        final int uid = Binder.getCallingUid();
7203        if (uid != Process.SYSTEM_UID && uid != 0) {
7204            throw new SecurityException(message);
7205        }
7206    }
7207
7208    @Override
7209    public void performFstrimIfNeeded() {
7210        enforceSystemOrRoot("Only the system can request fstrim");
7211
7212        // Before everything else, see whether we need to fstrim.
7213        try {
7214            IMountService ms = PackageHelper.getMountService();
7215            if (ms != null) {
7216                boolean doTrim = false;
7217                final long interval = android.provider.Settings.Global.getLong(
7218                        mContext.getContentResolver(),
7219                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7220                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7221                if (interval > 0) {
7222                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7223                    if (timeSinceLast > interval) {
7224                        doTrim = true;
7225                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7226                                + "; running immediately");
7227                    }
7228                }
7229                if (doTrim) {
7230                    final boolean dexOptDialogShown;
7231                    synchronized (mPackages) {
7232                        dexOptDialogShown = mDexOptDialogShown;
7233                    }
7234                    if (!isFirstBoot() && dexOptDialogShown) {
7235                        try {
7236                            ActivityManagerNative.getDefault().showBootMessage(
7237                                    mContext.getResources().getString(
7238                                            R.string.android_upgrading_fstrim), true);
7239                        } catch (RemoteException e) {
7240                        }
7241                    }
7242                    ms.runMaintenance();
7243                }
7244            } else {
7245                Slog.e(TAG, "Mount service unavailable!");
7246            }
7247        } catch (RemoteException e) {
7248            // Can't happen; MountService is local
7249        }
7250    }
7251
7252    @Override
7253    public void updatePackagesIfNeeded() {
7254        enforceSystemOrRoot("Only the system can request package update");
7255
7256        // We need to re-extract after an OTA.
7257        boolean causeUpgrade = isUpgrade();
7258
7259        // First boot or factory reset.
7260        // Note: we also handle devices that are upgrading to N right now as if it is their
7261        //       first boot, as they do not have profile data.
7262        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7263
7264        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7265        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7266
7267        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7268            return;
7269        }
7270
7271        List<PackageParser.Package> pkgs;
7272        synchronized (mPackages) {
7273            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7274        }
7275
7276        final long startTime = System.nanoTime();
7277        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7278                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7279
7280        final int elapsedTimeSeconds =
7281                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7282
7283        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7284        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7285        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7286        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7287        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7288    }
7289
7290    /**
7291     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7292     * containing statistics about the invocation. The array consists of three elements,
7293     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7294     * and {@code numberOfPackagesFailed}.
7295     */
7296    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7297            String compilerFilter) {
7298
7299        int numberOfPackagesVisited = 0;
7300        int numberOfPackagesOptimized = 0;
7301        int numberOfPackagesSkipped = 0;
7302        int numberOfPackagesFailed = 0;
7303        final int numberOfPackagesToDexopt = pkgs.size();
7304
7305        for (PackageParser.Package pkg : pkgs) {
7306            numberOfPackagesVisited++;
7307
7308            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7309                if (DEBUG_DEXOPT) {
7310                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7311                }
7312                numberOfPackagesSkipped++;
7313                continue;
7314            }
7315
7316            if (DEBUG_DEXOPT) {
7317                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7318                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7319            }
7320
7321            if (showDialog) {
7322                try {
7323                    ActivityManagerNative.getDefault().showBootMessage(
7324                            mContext.getResources().getString(R.string.android_upgrading_apk,
7325                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7326                } catch (RemoteException e) {
7327                }
7328                synchronized (mPackages) {
7329                    mDexOptDialogShown = true;
7330                }
7331            }
7332
7333            // If the OTA updates a system app which was previously preopted to a non-preopted state
7334            // the app might end up being verified at runtime. That's because by default the apps
7335            // are verify-profile but for preopted apps there's no profile.
7336            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7337            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7338            // filter (by default interpret-only).
7339            // Note that at this stage unused apps are already filtered.
7340            if (isSystemApp(pkg) &&
7341                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7342                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7343                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7344            }
7345
7346            // If the OTA updates a system app which was previously preopted to a non-preopted state
7347            // the app might end up being verified at runtime. That's because by default the apps
7348            // are verify-profile but for preopted apps there's no profile.
7349            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7350            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7351            // filter (by default interpret-only).
7352            // Note that at this stage unused apps are already filtered.
7353            if (isSystemApp(pkg) &&
7354                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7355                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7356                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7357            }
7358
7359            // checkProfiles is false to avoid merging profiles during boot which
7360            // might interfere with background compilation (b/28612421).
7361            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7362            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7363            // trade-off worth doing to save boot time work.
7364            int dexOptStatus = performDexOptTraced(pkg.packageName,
7365                    false /* checkProfiles */,
7366                    compilerFilter,
7367                    false /* force */);
7368            switch (dexOptStatus) {
7369                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7370                    numberOfPackagesOptimized++;
7371                    break;
7372                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7373                    numberOfPackagesSkipped++;
7374                    break;
7375                case PackageDexOptimizer.DEX_OPT_FAILED:
7376                    numberOfPackagesFailed++;
7377                    break;
7378                default:
7379                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7380                    break;
7381            }
7382        }
7383
7384        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7385                numberOfPackagesFailed };
7386    }
7387
7388    @Override
7389    public void notifyPackageUse(String packageName, int reason) {
7390        synchronized (mPackages) {
7391            PackageParser.Package p = mPackages.get(packageName);
7392            if (p == null) {
7393                return;
7394            }
7395            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7396        }
7397    }
7398
7399    @Override
7400    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
7401        int userId = UserHandle.getCallingUserId();
7402        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
7403        if (ai == null) {
7404            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
7405                + loadingPackageName + ", user=" + userId);
7406            return;
7407        }
7408        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
7409    }
7410
7411    // TODO: this is not used nor needed. Delete it.
7412    @Override
7413    public boolean performDexOptIfNeeded(String packageName) {
7414        int dexOptStatus = performDexOptTraced(packageName,
7415                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7416        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7417    }
7418
7419    @Override
7420    public boolean performDexOpt(String packageName,
7421            boolean checkProfiles, int compileReason, boolean force) {
7422        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7423                getCompilerFilterForReason(compileReason), force);
7424        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7425    }
7426
7427    @Override
7428    public boolean performDexOptMode(String packageName,
7429            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7430        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7431                targetCompilerFilter, force);
7432        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7433    }
7434
7435    private int performDexOptTraced(String packageName,
7436                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7437        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7438        try {
7439            return performDexOptInternal(packageName, checkProfiles,
7440                    targetCompilerFilter, force);
7441        } finally {
7442            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7443        }
7444    }
7445
7446    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7447    // if the package can now be considered up to date for the given filter.
7448    private int performDexOptInternal(String packageName,
7449                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7450        PackageParser.Package p;
7451        synchronized (mPackages) {
7452            p = mPackages.get(packageName);
7453            if (p == null) {
7454                // Package could not be found. Report failure.
7455                return PackageDexOptimizer.DEX_OPT_FAILED;
7456            }
7457            mPackageUsage.maybeWriteAsync(mPackages);
7458            mCompilerStats.maybeWriteAsync();
7459        }
7460        long callingId = Binder.clearCallingIdentity();
7461        try {
7462            synchronized (mInstallLock) {
7463                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7464                        targetCompilerFilter, force);
7465            }
7466        } finally {
7467            Binder.restoreCallingIdentity(callingId);
7468        }
7469    }
7470
7471    public ArraySet<String> getOptimizablePackages() {
7472        ArraySet<String> pkgs = new ArraySet<String>();
7473        synchronized (mPackages) {
7474            for (PackageParser.Package p : mPackages.values()) {
7475                if (PackageDexOptimizer.canOptimizePackage(p)) {
7476                    pkgs.add(p.packageName);
7477                }
7478            }
7479        }
7480        return pkgs;
7481    }
7482
7483    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7484            boolean checkProfiles, String targetCompilerFilter,
7485            boolean force) {
7486        // Select the dex optimizer based on the force parameter.
7487        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7488        //       allocate an object here.
7489        PackageDexOptimizer pdo = force
7490                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7491                : mPackageDexOptimizer;
7492
7493        // Optimize all dependencies first. Note: we ignore the return value and march on
7494        // on errors.
7495        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7496        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7497        if (!deps.isEmpty()) {
7498            for (PackageParser.Package depPackage : deps) {
7499                // TODO: Analyze and investigate if we (should) profile libraries.
7500                // Currently this will do a full compilation of the library by default.
7501                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7502                        false /* checkProfiles */,
7503                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7504                        getOrCreateCompilerPackageStats(depPackage));
7505            }
7506        }
7507        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7508                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7509    }
7510
7511    // Performs dexopt on the used secondary dex files belonging to the given package.
7512    // Returns true if all dex files were process successfully (which could mean either dexopt or
7513    // skip). Returns false if any of the files caused errors.
7514    @Override
7515    public boolean performDexOptSecondary(String packageName, String compilerFilter,
7516            boolean force) {
7517        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
7518    }
7519
7520    /**
7521     * Reconcile the information we have about the secondary dex files belonging to
7522     * {@code packagName} and the actual dex files. For all dex files that were
7523     * deleted, update the internal records and delete the generated oat files.
7524     */
7525    @Override
7526    public void reconcileSecondaryDexFiles(String packageName) {
7527        mDexManager.reconcileSecondaryDexFiles(packageName);
7528    }
7529
7530    /**
7531     * Execute the background dexopt job immediately.
7532     */
7533    @Override
7534    public boolean runBackgroundDexoptJob() {
7535        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
7536    }
7537
7538    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7539        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7540            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7541            Set<String> collectedNames = new HashSet<>();
7542            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7543
7544            retValue.remove(p);
7545
7546            return retValue;
7547        } else {
7548            return Collections.emptyList();
7549        }
7550    }
7551
7552    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7553            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7554        if (!collectedNames.contains(p.packageName)) {
7555            collectedNames.add(p.packageName);
7556            collected.add(p);
7557
7558            if (p.usesLibraries != null) {
7559                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7560            }
7561            if (p.usesOptionalLibraries != null) {
7562                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7563                        collectedNames);
7564            }
7565        }
7566    }
7567
7568    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7569            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7570        for (String libName : libs) {
7571            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7572            if (libPkg != null) {
7573                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7574            }
7575        }
7576    }
7577
7578    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7579        synchronized (mPackages) {
7580            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7581            if (lib != null && lib.apk != null) {
7582                return mPackages.get(lib.apk);
7583            }
7584        }
7585        return null;
7586    }
7587
7588    public void shutdown() {
7589        mPackageUsage.writeNow(mPackages);
7590        mCompilerStats.writeNow();
7591    }
7592
7593    @Override
7594    public void dumpProfiles(String packageName) {
7595        PackageParser.Package pkg;
7596        synchronized (mPackages) {
7597            pkg = mPackages.get(packageName);
7598            if (pkg == null) {
7599                throw new IllegalArgumentException("Unknown package: " + packageName);
7600            }
7601        }
7602        /* Only the shell, root, or the app user should be able to dump profiles. */
7603        int callingUid = Binder.getCallingUid();
7604        if (callingUid != Process.SHELL_UID &&
7605            callingUid != Process.ROOT_UID &&
7606            callingUid != pkg.applicationInfo.uid) {
7607            throw new SecurityException("dumpProfiles");
7608        }
7609
7610        synchronized (mInstallLock) {
7611            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7612            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7613            try {
7614                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7615                String codePaths = TextUtils.join(";", allCodePaths);
7616                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
7617            } catch (InstallerException e) {
7618                Slog.w(TAG, "Failed to dump profiles", e);
7619            }
7620            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7621        }
7622    }
7623
7624    @Override
7625    public void forceDexOpt(String packageName) {
7626        enforceSystemOrRoot("forceDexOpt");
7627
7628        PackageParser.Package pkg;
7629        synchronized (mPackages) {
7630            pkg = mPackages.get(packageName);
7631            if (pkg == null) {
7632                throw new IllegalArgumentException("Unknown package: " + packageName);
7633            }
7634        }
7635
7636        synchronized (mInstallLock) {
7637            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7638
7639            // Whoever is calling forceDexOpt wants a fully compiled package.
7640            // Don't use profiles since that may cause compilation to be skipped.
7641            final int res = performDexOptInternalWithDependenciesLI(pkg,
7642                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7643                    true /* force */);
7644
7645            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7646            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7647                throw new IllegalStateException("Failed to dexopt: " + res);
7648            }
7649        }
7650    }
7651
7652    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7653        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7654            Slog.w(TAG, "Unable to update from " + oldPkg.name
7655                    + " to " + newPkg.packageName
7656                    + ": old package not in system partition");
7657            return false;
7658        } else if (mPackages.get(oldPkg.name) != null) {
7659            Slog.w(TAG, "Unable to update from " + oldPkg.name
7660                    + " to " + newPkg.packageName
7661                    + ": old package still exists");
7662            return false;
7663        }
7664        return true;
7665    }
7666
7667    void removeCodePathLI(File codePath) {
7668        if (codePath.isDirectory()) {
7669            try {
7670                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7671            } catch (InstallerException e) {
7672                Slog.w(TAG, "Failed to remove code path", e);
7673            }
7674        } else {
7675            codePath.delete();
7676        }
7677    }
7678
7679    private int[] resolveUserIds(int userId) {
7680        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7681    }
7682
7683    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7684        if (pkg == null) {
7685            Slog.wtf(TAG, "Package was null!", new Throwable());
7686            return;
7687        }
7688        clearAppDataLeafLIF(pkg, userId, flags);
7689        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7690        for (int i = 0; i < childCount; i++) {
7691            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7692        }
7693    }
7694
7695    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7696        final PackageSetting ps;
7697        synchronized (mPackages) {
7698            ps = mSettings.mPackages.get(pkg.packageName);
7699        }
7700        for (int realUserId : resolveUserIds(userId)) {
7701            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7702            try {
7703                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7704                        ceDataInode);
7705            } catch (InstallerException e) {
7706                Slog.w(TAG, String.valueOf(e));
7707            }
7708        }
7709    }
7710
7711    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7712        if (pkg == null) {
7713            Slog.wtf(TAG, "Package was null!", new Throwable());
7714            return;
7715        }
7716        destroyAppDataLeafLIF(pkg, userId, flags);
7717        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7718        for (int i = 0; i < childCount; i++) {
7719            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7720        }
7721    }
7722
7723    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7724        final PackageSetting ps;
7725        synchronized (mPackages) {
7726            ps = mSettings.mPackages.get(pkg.packageName);
7727        }
7728        for (int realUserId : resolveUserIds(userId)) {
7729            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7730            try {
7731                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7732                        ceDataInode);
7733            } catch (InstallerException e) {
7734                Slog.w(TAG, String.valueOf(e));
7735            }
7736        }
7737    }
7738
7739    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7740        if (pkg == null) {
7741            Slog.wtf(TAG, "Package was null!", new Throwable());
7742            return;
7743        }
7744        destroyAppProfilesLeafLIF(pkg);
7745        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7746        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7747        for (int i = 0; i < childCount; i++) {
7748            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7749            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7750                    true /* removeBaseMarker */);
7751        }
7752    }
7753
7754    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7755            boolean removeBaseMarker) {
7756        if (pkg.isForwardLocked()) {
7757            return;
7758        }
7759
7760        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7761            try {
7762                path = PackageManagerServiceUtils.realpath(new File(path));
7763            } catch (IOException e) {
7764                // TODO: Should we return early here ?
7765                Slog.w(TAG, "Failed to get canonical path", e);
7766                continue;
7767            }
7768
7769            final String useMarker = path.replace('/', '@');
7770            for (int realUserId : resolveUserIds(userId)) {
7771                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7772                if (removeBaseMarker) {
7773                    File foreignUseMark = new File(profileDir, useMarker);
7774                    if (foreignUseMark.exists()) {
7775                        if (!foreignUseMark.delete()) {
7776                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7777                                    + pkg.packageName);
7778                        }
7779                    }
7780                }
7781
7782                File[] markers = profileDir.listFiles();
7783                if (markers != null) {
7784                    final String searchString = "@" + pkg.packageName + "@";
7785                    // We also delete all markers that contain the package name we're
7786                    // uninstalling. These are associated with secondary dex-files belonging
7787                    // to the package. Reconstructing the path of these dex files is messy
7788                    // in general.
7789                    for (File marker : markers) {
7790                        if (marker.getName().indexOf(searchString) > 0) {
7791                            if (!marker.delete()) {
7792                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7793                                    + pkg.packageName);
7794                            }
7795                        }
7796                    }
7797                }
7798            }
7799        }
7800    }
7801
7802    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7803        try {
7804            mInstaller.destroyAppProfiles(pkg.packageName);
7805        } catch (InstallerException e) {
7806            Slog.w(TAG, String.valueOf(e));
7807        }
7808    }
7809
7810    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7811        if (pkg == null) {
7812            Slog.wtf(TAG, "Package was null!", new Throwable());
7813            return;
7814        }
7815        clearAppProfilesLeafLIF(pkg);
7816        // We don't remove the base foreign use marker when clearing profiles because
7817        // we will rename it when the app is updated. Unlike the actual profile contents,
7818        // the foreign use marker is good across installs.
7819        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7820        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7821        for (int i = 0; i < childCount; i++) {
7822            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7823        }
7824    }
7825
7826    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7827        try {
7828            mInstaller.clearAppProfiles(pkg.packageName);
7829        } catch (InstallerException e) {
7830            Slog.w(TAG, String.valueOf(e));
7831        }
7832    }
7833
7834    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7835            long lastUpdateTime) {
7836        // Set parent install/update time
7837        PackageSetting ps = (PackageSetting) pkg.mExtras;
7838        if (ps != null) {
7839            ps.firstInstallTime = firstInstallTime;
7840            ps.lastUpdateTime = lastUpdateTime;
7841        }
7842        // Set children install/update time
7843        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7844        for (int i = 0; i < childCount; i++) {
7845            PackageParser.Package childPkg = pkg.childPackages.get(i);
7846            ps = (PackageSetting) childPkg.mExtras;
7847            if (ps != null) {
7848                ps.firstInstallTime = firstInstallTime;
7849                ps.lastUpdateTime = lastUpdateTime;
7850            }
7851        }
7852    }
7853
7854    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7855            PackageParser.Package changingLib) {
7856        if (file.path != null) {
7857            usesLibraryFiles.add(file.path);
7858            return;
7859        }
7860        PackageParser.Package p = mPackages.get(file.apk);
7861        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7862            // If we are doing this while in the middle of updating a library apk,
7863            // then we need to make sure to use that new apk for determining the
7864            // dependencies here.  (We haven't yet finished committing the new apk
7865            // to the package manager state.)
7866            if (p == null || p.packageName.equals(changingLib.packageName)) {
7867                p = changingLib;
7868            }
7869        }
7870        if (p != null) {
7871            usesLibraryFiles.addAll(p.getAllCodePaths());
7872        }
7873    }
7874
7875    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7876            PackageParser.Package changingLib) throws PackageManagerException {
7877        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7878            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7879            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7880            for (int i=0; i<N; i++) {
7881                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7882                if (file == null) {
7883                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7884                            "Package " + pkg.packageName + " requires unavailable shared library "
7885                            + pkg.usesLibraries.get(i) + "; failing!");
7886                }
7887                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7888            }
7889            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7890            for (int i=0; i<N; i++) {
7891                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7892                if (file == null) {
7893                    Slog.w(TAG, "Package " + pkg.packageName
7894                            + " desires unavailable shared library "
7895                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7896                } else {
7897                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7898                }
7899            }
7900            N = usesLibraryFiles.size();
7901            if (N > 0) {
7902                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7903            } else {
7904                pkg.usesLibraryFiles = null;
7905            }
7906        }
7907    }
7908
7909    private static boolean hasString(List<String> list, List<String> which) {
7910        if (list == null) {
7911            return false;
7912        }
7913        for (int i=list.size()-1; i>=0; i--) {
7914            for (int j=which.size()-1; j>=0; j--) {
7915                if (which.get(j).equals(list.get(i))) {
7916                    return true;
7917                }
7918            }
7919        }
7920        return false;
7921    }
7922
7923    private void updateAllSharedLibrariesLPw() {
7924        for (PackageParser.Package pkg : mPackages.values()) {
7925            try {
7926                updateSharedLibrariesLPw(pkg, null);
7927            } catch (PackageManagerException e) {
7928                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7929            }
7930        }
7931    }
7932
7933    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7934            PackageParser.Package changingPkg) {
7935        ArrayList<PackageParser.Package> res = null;
7936        for (PackageParser.Package pkg : mPackages.values()) {
7937            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7938                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7939                if (res == null) {
7940                    res = new ArrayList<PackageParser.Package>();
7941                }
7942                res.add(pkg);
7943                try {
7944                    updateSharedLibrariesLPw(pkg, changingPkg);
7945                } catch (PackageManagerException e) {
7946                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7947                }
7948            }
7949        }
7950        return res;
7951    }
7952
7953    /**
7954     * Derive the value of the {@code cpuAbiOverride} based on the provided
7955     * value and an optional stored value from the package settings.
7956     */
7957    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7958        String cpuAbiOverride = null;
7959
7960        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7961            cpuAbiOverride = null;
7962        } else if (abiOverride != null) {
7963            cpuAbiOverride = abiOverride;
7964        } else if (settings != null) {
7965            cpuAbiOverride = settings.cpuAbiOverrideString;
7966        }
7967
7968        return cpuAbiOverride;
7969    }
7970
7971    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7972            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7973                    throws PackageManagerException {
7974        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7975        // If the package has children and this is the first dive in the function
7976        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7977        // whether all packages (parent and children) would be successfully scanned
7978        // before the actual scan since scanning mutates internal state and we want
7979        // to atomically install the package and its children.
7980        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7981            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7982                scanFlags |= SCAN_CHECK_ONLY;
7983            }
7984        } else {
7985            scanFlags &= ~SCAN_CHECK_ONLY;
7986        }
7987
7988        final PackageParser.Package scannedPkg;
7989        try {
7990            // Scan the parent
7991            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7992            // Scan the children
7993            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7994            for (int i = 0; i < childCount; i++) {
7995                PackageParser.Package childPkg = pkg.childPackages.get(i);
7996                scanPackageLI(childPkg, policyFlags,
7997                        scanFlags, currentTime, user);
7998            }
7999        } finally {
8000            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8001        }
8002
8003        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8004            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8005        }
8006
8007        return scannedPkg;
8008    }
8009
8010    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8011            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8012        boolean success = false;
8013        try {
8014            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8015                    currentTime, user);
8016            success = true;
8017            return res;
8018        } finally {
8019            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8020                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8021                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8022                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8023                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8024            }
8025        }
8026    }
8027
8028    /**
8029     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8030     */
8031    private static boolean apkHasCode(String fileName) {
8032        StrictJarFile jarFile = null;
8033        try {
8034            jarFile = new StrictJarFile(fileName,
8035                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8036            return jarFile.findEntry("classes.dex") != null;
8037        } catch (IOException ignore) {
8038        } finally {
8039            try {
8040                if (jarFile != null) {
8041                    jarFile.close();
8042                }
8043            } catch (IOException ignore) {}
8044        }
8045        return false;
8046    }
8047
8048    /**
8049     * Enforces code policy for the package. This ensures that if an APK has
8050     * declared hasCode="true" in its manifest that the APK actually contains
8051     * code.
8052     *
8053     * @throws PackageManagerException If bytecode could not be found when it should exist
8054     */
8055    private static void enforceCodePolicy(PackageParser.Package pkg)
8056            throws PackageManagerException {
8057        final boolean shouldHaveCode =
8058                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8059        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8060            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8061                    "Package " + pkg.baseCodePath + " code is missing");
8062        }
8063
8064        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8065            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8066                final boolean splitShouldHaveCode =
8067                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8068                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8069                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8070                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8071                }
8072            }
8073        }
8074    }
8075
8076    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8077            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8078            throws PackageManagerException {
8079        final File scanFile = new File(pkg.codePath);
8080        if (pkg.applicationInfo.getCodePath() == null ||
8081                pkg.applicationInfo.getResourcePath() == null) {
8082            // Bail out. The resource and code paths haven't been set.
8083            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8084                    "Code and resource paths haven't been set correctly");
8085        }
8086
8087        // Apply policy
8088        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8089            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8090            if (pkg.applicationInfo.isDirectBootAware()) {
8091                // we're direct boot aware; set for all components
8092                for (PackageParser.Service s : pkg.services) {
8093                    s.info.encryptionAware = s.info.directBootAware = true;
8094                }
8095                for (PackageParser.Provider p : pkg.providers) {
8096                    p.info.encryptionAware = p.info.directBootAware = true;
8097                }
8098                for (PackageParser.Activity a : pkg.activities) {
8099                    a.info.encryptionAware = a.info.directBootAware = true;
8100                }
8101                for (PackageParser.Activity r : pkg.receivers) {
8102                    r.info.encryptionAware = r.info.directBootAware = true;
8103                }
8104            }
8105        } else {
8106            // Only allow system apps to be flagged as core apps.
8107            pkg.coreApp = false;
8108            // clear flags not applicable to regular apps
8109            pkg.applicationInfo.privateFlags &=
8110                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8111            pkg.applicationInfo.privateFlags &=
8112                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8113        }
8114        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8115
8116        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8117            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8118        }
8119
8120        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8121            enforceCodePolicy(pkg);
8122        }
8123
8124        if (mCustomResolverComponentName != null &&
8125                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8126            setUpCustomResolverActivity(pkg);
8127        }
8128
8129        if (pkg.packageName.equals("android")) {
8130            synchronized (mPackages) {
8131                if (mAndroidApplication != null) {
8132                    Slog.w(TAG, "*************************************************");
8133                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8134                    Slog.w(TAG, " file=" + scanFile);
8135                    Slog.w(TAG, "*************************************************");
8136                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8137                            "Core android package being redefined.  Skipping.");
8138                }
8139
8140                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8141                    // Set up information for our fall-back user intent resolution activity.
8142                    mPlatformPackage = pkg;
8143                    pkg.mVersionCode = mSdkVersion;
8144                    mAndroidApplication = pkg.applicationInfo;
8145
8146                    if (!mResolverReplaced) {
8147                        mResolveActivity.applicationInfo = mAndroidApplication;
8148                        mResolveActivity.name = ResolverActivity.class.getName();
8149                        mResolveActivity.packageName = mAndroidApplication.packageName;
8150                        mResolveActivity.processName = "system:ui";
8151                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8152                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8153                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8154                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8155                        mResolveActivity.exported = true;
8156                        mResolveActivity.enabled = true;
8157                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8158                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8159                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8160                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8161                                | ActivityInfo.CONFIG_ORIENTATION
8162                                | ActivityInfo.CONFIG_KEYBOARD
8163                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8164                        mResolveInfo.activityInfo = mResolveActivity;
8165                        mResolveInfo.priority = 0;
8166                        mResolveInfo.preferredOrder = 0;
8167                        mResolveInfo.match = 0;
8168                        mResolveComponentName = new ComponentName(
8169                                mAndroidApplication.packageName, mResolveActivity.name);
8170                    }
8171                }
8172            }
8173        }
8174
8175        if (DEBUG_PACKAGE_SCANNING) {
8176            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8177                Log.d(TAG, "Scanning package " + pkg.packageName);
8178        }
8179
8180        synchronized (mPackages) {
8181            if (mPackages.containsKey(pkg.packageName)
8182                    || mSharedLibraries.containsKey(pkg.packageName)) {
8183                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8184                        "Application package " + pkg.packageName
8185                                + " already installed.  Skipping duplicate.");
8186            }
8187
8188            // If we're only installing presumed-existing packages, require that the
8189            // scanned APK is both already known and at the path previously established
8190            // for it.  Previously unknown packages we pick up normally, but if we have an
8191            // a priori expectation about this package's install presence, enforce it.
8192            // With a singular exception for new system packages. When an OTA contains
8193            // a new system package, we allow the codepath to change from a system location
8194            // to the user-installed location. If we don't allow this change, any newer,
8195            // user-installed version of the application will be ignored.
8196            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8197                if (mExpectingBetter.containsKey(pkg.packageName)) {
8198                    logCriticalInfo(Log.WARN,
8199                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8200                } else {
8201                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8202                    if (known != null) {
8203                        if (DEBUG_PACKAGE_SCANNING) {
8204                            Log.d(TAG, "Examining " + pkg.codePath
8205                                    + " and requiring known paths " + known.codePathString
8206                                    + " & " + known.resourcePathString);
8207                        }
8208                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8209                                || !pkg.applicationInfo.getResourcePath().equals(
8210                                known.resourcePathString)) {
8211                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8212                                    "Application package " + pkg.packageName
8213                                            + " found at " + pkg.applicationInfo.getCodePath()
8214                                            + " but expected at " + known.codePathString
8215                                            + "; ignoring.");
8216                        }
8217                    }
8218                }
8219            }
8220        }
8221
8222        // Initialize package source and resource directories
8223        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8224        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8225
8226        SharedUserSetting suid = null;
8227        PackageSetting pkgSetting = null;
8228
8229        if (!isSystemApp(pkg)) {
8230            // Only system apps can use these features.
8231            pkg.mOriginalPackages = null;
8232            pkg.mRealPackage = null;
8233            pkg.mAdoptPermissions = null;
8234        }
8235
8236        // Getting the package setting may have a side-effect, so if we
8237        // are only checking if scan would succeed, stash a copy of the
8238        // old setting to restore at the end.
8239        PackageSetting nonMutatedPs = null;
8240
8241        // writer
8242        synchronized (mPackages) {
8243            if (pkg.mSharedUserId != null) {
8244                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8245                if (suid == null) {
8246                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8247                            "Creating application package " + pkg.packageName
8248                            + " for shared user failed");
8249                }
8250                if (DEBUG_PACKAGE_SCANNING) {
8251                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8252                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8253                                + "): packages=" + suid.packages);
8254                }
8255            }
8256
8257            // Check if we are renaming from an original package name.
8258            PackageSetting origPackage = null;
8259            String realName = null;
8260            if (pkg.mOriginalPackages != null) {
8261                // This package may need to be renamed to a previously
8262                // installed name.  Let's check on that...
8263                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8264                if (pkg.mOriginalPackages.contains(renamed)) {
8265                    // This package had originally been installed as the
8266                    // original name, and we have already taken care of
8267                    // transitioning to the new one.  Just update the new
8268                    // one to continue using the old name.
8269                    realName = pkg.mRealPackage;
8270                    if (!pkg.packageName.equals(renamed)) {
8271                        // Callers into this function may have already taken
8272                        // care of renaming the package; only do it here if
8273                        // it is not already done.
8274                        pkg.setPackageName(renamed);
8275                    }
8276
8277                } else {
8278                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8279                        if ((origPackage = mSettings.peekPackageLPr(
8280                                pkg.mOriginalPackages.get(i))) != null) {
8281                            // We do have the package already installed under its
8282                            // original name...  should we use it?
8283                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8284                                // New package is not compatible with original.
8285                                origPackage = null;
8286                                continue;
8287                            } else if (origPackage.sharedUser != null) {
8288                                // Make sure uid is compatible between packages.
8289                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8290                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8291                                            + " to " + pkg.packageName + ": old uid "
8292                                            + origPackage.sharedUser.name
8293                                            + " differs from " + pkg.mSharedUserId);
8294                                    origPackage = null;
8295                                    continue;
8296                                }
8297                                // TODO: Add case when shared user id is added [b/28144775]
8298                            } else {
8299                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8300                                        + pkg.packageName + " to old name " + origPackage.name);
8301                            }
8302                            break;
8303                        }
8304                    }
8305                }
8306            }
8307
8308            if (mTransferedPackages.contains(pkg.packageName)) {
8309                Slog.w(TAG, "Package " + pkg.packageName
8310                        + " was transferred to another, but its .apk remains");
8311            }
8312
8313            // See comments in nonMutatedPs declaration
8314            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8315                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8316                if (foundPs != null) {
8317                    nonMutatedPs = new PackageSetting(foundPs);
8318                }
8319            }
8320
8321            // Just create the setting, don't add it yet. For already existing packages
8322            // the PkgSetting exists already and doesn't have to be created.
8323            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8324                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8325                    pkg.applicationInfo.primaryCpuAbi,
8326                    pkg.applicationInfo.secondaryCpuAbi,
8327                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8328                    user, false);
8329            if (pkgSetting == null) {
8330                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8331                        "Creating application package " + pkg.packageName + " failed");
8332            }
8333
8334            if (pkgSetting.origPackage != null) {
8335                // If we are first transitioning from an original package,
8336                // fix up the new package's name now.  We need to do this after
8337                // looking up the package under its new name, so getPackageLP
8338                // can take care of fiddling things correctly.
8339                pkg.setPackageName(origPackage.name);
8340
8341                // File a report about this.
8342                String msg = "New package " + pkgSetting.realName
8343                        + " renamed to replace old package " + pkgSetting.name;
8344                reportSettingsProblem(Log.WARN, msg);
8345
8346                // Make a note of it.
8347                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8348                    mTransferedPackages.add(origPackage.name);
8349                }
8350
8351                // No longer need to retain this.
8352                pkgSetting.origPackage = null;
8353            }
8354
8355            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8356                // Make a note of it.
8357                mTransferedPackages.add(pkg.packageName);
8358            }
8359
8360            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8361                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8362            }
8363
8364            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8365                // Check all shared libraries and map to their actual file path.
8366                // We only do this here for apps not on a system dir, because those
8367                // are the only ones that can fail an install due to this.  We
8368                // will take care of the system apps by updating all of their
8369                // library paths after the scan is done.
8370                updateSharedLibrariesLPw(pkg, null);
8371            }
8372
8373            if (mFoundPolicyFile) {
8374                SELinuxMMAC.assignSeinfoValue(pkg);
8375            }
8376
8377            pkg.applicationInfo.uid = pkgSetting.appId;
8378            pkg.mExtras = pkgSetting;
8379            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8380                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8381                    // We just determined the app is signed correctly, so bring
8382                    // over the latest parsed certs.
8383                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8384                } else {
8385                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8386                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8387                                "Package " + pkg.packageName + " upgrade keys do not match the "
8388                                + "previously installed version");
8389                    } else {
8390                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8391                        String msg = "System package " + pkg.packageName
8392                            + " signature changed; retaining data.";
8393                        reportSettingsProblem(Log.WARN, msg);
8394                    }
8395                }
8396            } else {
8397                try {
8398                    verifySignaturesLP(pkgSetting, pkg);
8399                    // We just determined the app is signed correctly, so bring
8400                    // over the latest parsed certs.
8401                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8402                } catch (PackageManagerException e) {
8403                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8404                        throw e;
8405                    }
8406                    // The signature has changed, but this package is in the system
8407                    // image...  let's recover!
8408                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8409                    // However...  if this package is part of a shared user, but it
8410                    // doesn't match the signature of the shared user, let's fail.
8411                    // What this means is that you can't change the signatures
8412                    // associated with an overall shared user, which doesn't seem all
8413                    // that unreasonable.
8414                    if (pkgSetting.sharedUser != null) {
8415                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8416                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8417                            throw new PackageManagerException(
8418                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8419                                            "Signature mismatch for shared user: "
8420                                            + pkgSetting.sharedUser);
8421                        }
8422                    }
8423                    // File a report about this.
8424                    String msg = "System package " + pkg.packageName
8425                        + " signature changed; retaining data.";
8426                    reportSettingsProblem(Log.WARN, msg);
8427                }
8428            }
8429            // Verify that this new package doesn't have any content providers
8430            // that conflict with existing packages.  Only do this if the
8431            // package isn't already installed, since we don't want to break
8432            // things that are installed.
8433            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8434                final int N = pkg.providers.size();
8435                int i;
8436                for (i=0; i<N; i++) {
8437                    PackageParser.Provider p = pkg.providers.get(i);
8438                    if (p.info.authority != null) {
8439                        String names[] = p.info.authority.split(";");
8440                        for (int j = 0; j < names.length; j++) {
8441                            if (mProvidersByAuthority.containsKey(names[j])) {
8442                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8443                                final String otherPackageName =
8444                                        ((other != null && other.getComponentName() != null) ?
8445                                                other.getComponentName().getPackageName() : "?");
8446                                throw new PackageManagerException(
8447                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8448                                                "Can't install because provider name " + names[j]
8449                                                + " (in package " + pkg.applicationInfo.packageName
8450                                                + ") is already used by " + otherPackageName);
8451                            }
8452                        }
8453                    }
8454                }
8455            }
8456
8457            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8458                // This package wants to adopt ownership of permissions from
8459                // another package.
8460                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8461                    final String origName = pkg.mAdoptPermissions.get(i);
8462                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8463                    if (orig != null) {
8464                        if (verifyPackageUpdateLPr(orig, pkg)) {
8465                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8466                                    + pkg.packageName);
8467                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8468                        }
8469                    }
8470                }
8471            }
8472        }
8473
8474        final String pkgName = pkg.packageName;
8475
8476        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8477        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8478        pkg.applicationInfo.processName = fixProcessName(
8479                pkg.applicationInfo.packageName,
8480                pkg.applicationInfo.processName,
8481                pkg.applicationInfo.uid);
8482
8483        if (pkg != mPlatformPackage) {
8484            // Get all of our default paths setup
8485            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8486        }
8487
8488        final String path = scanFile.getPath();
8489        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8490
8491        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8492            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8493
8494            // Some system apps still use directory structure for native libraries
8495            // in which case we might end up not detecting abi solely based on apk
8496            // structure. Try to detect abi based on directory structure.
8497            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8498                    pkg.applicationInfo.primaryCpuAbi == null) {
8499                setBundledAppAbisAndRoots(pkg, pkgSetting);
8500                setNativeLibraryPaths(pkg);
8501            }
8502
8503        } else {
8504            if ((scanFlags & SCAN_MOVE) != 0) {
8505                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8506                // but we already have this packages package info in the PackageSetting. We just
8507                // use that and derive the native library path based on the new codepath.
8508                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8509                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8510            }
8511
8512            // Set native library paths again. For moves, the path will be updated based on the
8513            // ABIs we've determined above. For non-moves, the path will be updated based on the
8514            // ABIs we determined during compilation, but the path will depend on the final
8515            // package path (after the rename away from the stage path).
8516            setNativeLibraryPaths(pkg);
8517        }
8518
8519        // This is a special case for the "system" package, where the ABI is
8520        // dictated by the zygote configuration (and init.rc). We should keep track
8521        // of this ABI so that we can deal with "normal" applications that run under
8522        // the same UID correctly.
8523        if (mPlatformPackage == pkg) {
8524            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8525                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8526        }
8527
8528        // If there's a mismatch between the abi-override in the package setting
8529        // and the abiOverride specified for the install. Warn about this because we
8530        // would've already compiled the app without taking the package setting into
8531        // account.
8532        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8533            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8534                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8535                        " for package " + pkg.packageName);
8536            }
8537        }
8538
8539        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8540        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8541        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8542
8543        // Copy the derived override back to the parsed package, so that we can
8544        // update the package settings accordingly.
8545        pkg.cpuAbiOverride = cpuAbiOverride;
8546
8547        if (DEBUG_ABI_SELECTION) {
8548            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8549                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8550                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8551        }
8552
8553        // Push the derived path down into PackageSettings so we know what to
8554        // clean up at uninstall time.
8555        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8556
8557        if (DEBUG_ABI_SELECTION) {
8558            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8559                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8560                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8561        }
8562
8563        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8564            // We don't do this here during boot because we can do it all
8565            // at once after scanning all existing packages.
8566            //
8567            // We also do this *before* we perform dexopt on this package, so that
8568            // we can avoid redundant dexopts, and also to make sure we've got the
8569            // code and package path correct.
8570            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8571                    pkg, true /* boot complete */);
8572        }
8573
8574        if (mFactoryTest && pkg.requestedPermissions.contains(
8575                android.Manifest.permission.FACTORY_TEST)) {
8576            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8577        }
8578
8579        if (isSystemApp(pkg)) {
8580            pkgSetting.isOrphaned = true;
8581        }
8582
8583        ArrayList<PackageParser.Package> clientLibPkgs = null;
8584
8585        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8586            if (nonMutatedPs != null) {
8587                synchronized (mPackages) {
8588                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8589                }
8590            }
8591            return pkg;
8592        }
8593
8594        // Only privileged apps and updated privileged apps can add child packages.
8595        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8596            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8597                throw new PackageManagerException("Only privileged apps and updated "
8598                        + "privileged apps can add child packages. Ignoring package "
8599                        + pkg.packageName);
8600            }
8601            final int childCount = pkg.childPackages.size();
8602            for (int i = 0; i < childCount; i++) {
8603                PackageParser.Package childPkg = pkg.childPackages.get(i);
8604                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8605                        childPkg.packageName)) {
8606                    throw new PackageManagerException("Cannot override a child package of "
8607                            + "another disabled system app. Ignoring package " + pkg.packageName);
8608                }
8609            }
8610        }
8611
8612        // writer
8613        synchronized (mPackages) {
8614            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8615                // Only system apps can add new shared libraries.
8616                if (pkg.libraryNames != null) {
8617                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8618                        String name = pkg.libraryNames.get(i);
8619                        boolean allowed = false;
8620                        if (pkg.isUpdatedSystemApp()) {
8621                            // New library entries can only be added through the
8622                            // system image.  This is important to get rid of a lot
8623                            // of nasty edge cases: for example if we allowed a non-
8624                            // system update of the app to add a library, then uninstalling
8625                            // the update would make the library go away, and assumptions
8626                            // we made such as through app install filtering would now
8627                            // have allowed apps on the device which aren't compatible
8628                            // with it.  Better to just have the restriction here, be
8629                            // conservative, and create many fewer cases that can negatively
8630                            // impact the user experience.
8631                            final PackageSetting sysPs = mSettings
8632                                    .getDisabledSystemPkgLPr(pkg.packageName);
8633                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8634                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8635                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8636                                        allowed = true;
8637                                        break;
8638                                    }
8639                                }
8640                            }
8641                        } else {
8642                            allowed = true;
8643                        }
8644                        if (allowed) {
8645                            if (!mSharedLibraries.containsKey(name)) {
8646                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8647                            } else if (!name.equals(pkg.packageName)) {
8648                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8649                                        + name + " already exists; skipping");
8650                            }
8651                        } else {
8652                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8653                                    + name + " that is not declared on system image; skipping");
8654                        }
8655                    }
8656                    if ((scanFlags & SCAN_BOOTING) == 0) {
8657                        // If we are not booting, we need to update any applications
8658                        // that are clients of our shared library.  If we are booting,
8659                        // this will all be done once the scan is complete.
8660                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8661                    }
8662                }
8663            }
8664        }
8665
8666        if ((scanFlags & SCAN_BOOTING) != 0) {
8667            // No apps can run during boot scan, so they don't need to be frozen
8668        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8669            // Caller asked to not kill app, so it's probably not frozen
8670        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8671            // Caller asked us to ignore frozen check for some reason; they
8672            // probably didn't know the package name
8673        } else {
8674            // We're doing major surgery on this package, so it better be frozen
8675            // right now to keep it from launching
8676            checkPackageFrozen(pkgName);
8677        }
8678
8679        // Also need to kill any apps that are dependent on the library.
8680        if (clientLibPkgs != null) {
8681            for (int i=0; i<clientLibPkgs.size(); i++) {
8682                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8683                killApplication(clientPkg.applicationInfo.packageName,
8684                        clientPkg.applicationInfo.uid, "update lib");
8685            }
8686        }
8687
8688        // Make sure we're not adding any bogus keyset info
8689        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8690        ksms.assertScannedPackageValid(pkg);
8691
8692        // writer
8693        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8694
8695        boolean createIdmapFailed = false;
8696        synchronized (mPackages) {
8697            // We don't expect installation to fail beyond this point
8698
8699            if (pkgSetting.pkg != null) {
8700                // Note that |user| might be null during the initial boot scan. If a codePath
8701                // for an app has changed during a boot scan, it's due to an app update that's
8702                // part of the system partition and marker changes must be applied to all users.
8703                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8704                    (user != null) ? user : UserHandle.ALL);
8705            }
8706
8707            // Add the new setting to mSettings
8708            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8709            // Add the new setting to mPackages
8710            mPackages.put(pkg.applicationInfo.packageName, pkg);
8711            // Make sure we don't accidentally delete its data.
8712            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8713            while (iter.hasNext()) {
8714                PackageCleanItem item = iter.next();
8715                if (pkgName.equals(item.packageName)) {
8716                    iter.remove();
8717                }
8718            }
8719
8720            // Take care of first install / last update times.
8721            if (currentTime != 0) {
8722                if (pkgSetting.firstInstallTime == 0) {
8723                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8724                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8725                    pkgSetting.lastUpdateTime = currentTime;
8726                }
8727            } else if (pkgSetting.firstInstallTime == 0) {
8728                // We need *something*.  Take time time stamp of the file.
8729                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8730            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8731                if (scanFileTime != pkgSetting.timeStamp) {
8732                    // A package on the system image has changed; consider this
8733                    // to be an update.
8734                    pkgSetting.lastUpdateTime = scanFileTime;
8735                }
8736            }
8737
8738            // Add the package's KeySets to the global KeySetManagerService
8739            ksms.addScannedPackageLPw(pkg);
8740
8741            int N = pkg.providers.size();
8742            StringBuilder r = null;
8743            int i;
8744            for (i=0; i<N; i++) {
8745                PackageParser.Provider p = pkg.providers.get(i);
8746                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8747                        p.info.processName, pkg.applicationInfo.uid);
8748                mProviders.addProvider(p);
8749                p.syncable = p.info.isSyncable;
8750                if (p.info.authority != null) {
8751                    String names[] = p.info.authority.split(";");
8752                    p.info.authority = null;
8753                    for (int j = 0; j < names.length; j++) {
8754                        if (j == 1 && p.syncable) {
8755                            // We only want the first authority for a provider to possibly be
8756                            // syncable, so if we already added this provider using a different
8757                            // authority clear the syncable flag. We copy the provider before
8758                            // changing it because the mProviders object contains a reference
8759                            // to a provider that we don't want to change.
8760                            // Only do this for the second authority since the resulting provider
8761                            // object can be the same for all future authorities for this provider.
8762                            p = new PackageParser.Provider(p);
8763                            p.syncable = false;
8764                        }
8765                        if (!mProvidersByAuthority.containsKey(names[j])) {
8766                            mProvidersByAuthority.put(names[j], p);
8767                            if (p.info.authority == null) {
8768                                p.info.authority = names[j];
8769                            } else {
8770                                p.info.authority = p.info.authority + ";" + names[j];
8771                            }
8772                            if (DEBUG_PACKAGE_SCANNING) {
8773                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8774                                    Log.d(TAG, "Registered content provider: " + names[j]
8775                                            + ", className = " + p.info.name + ", isSyncable = "
8776                                            + p.info.isSyncable);
8777                            }
8778                        } else {
8779                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8780                            Slog.w(TAG, "Skipping provider name " + names[j] +
8781                                    " (in package " + pkg.applicationInfo.packageName +
8782                                    "): name already used by "
8783                                    + ((other != null && other.getComponentName() != null)
8784                                            ? other.getComponentName().getPackageName() : "?"));
8785                        }
8786                    }
8787                }
8788                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8789                    if (r == null) {
8790                        r = new StringBuilder(256);
8791                    } else {
8792                        r.append(' ');
8793                    }
8794                    r.append(p.info.name);
8795                }
8796            }
8797            if (r != null) {
8798                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8799            }
8800
8801            N = pkg.services.size();
8802            r = null;
8803            for (i=0; i<N; i++) {
8804                PackageParser.Service s = pkg.services.get(i);
8805                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8806                        s.info.processName, pkg.applicationInfo.uid);
8807                mServices.addService(s);
8808                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8809                    if (r == null) {
8810                        r = new StringBuilder(256);
8811                    } else {
8812                        r.append(' ');
8813                    }
8814                    r.append(s.info.name);
8815                }
8816            }
8817            if (r != null) {
8818                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8819            }
8820
8821            N = pkg.receivers.size();
8822            r = null;
8823            for (i=0; i<N; i++) {
8824                PackageParser.Activity a = pkg.receivers.get(i);
8825                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8826                        a.info.processName, pkg.applicationInfo.uid);
8827                mReceivers.addActivity(a, "receiver");
8828                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8829                    if (r == null) {
8830                        r = new StringBuilder(256);
8831                    } else {
8832                        r.append(' ');
8833                    }
8834                    r.append(a.info.name);
8835                }
8836            }
8837            if (r != null) {
8838                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8839            }
8840
8841            N = pkg.activities.size();
8842            r = null;
8843            for (i=0; i<N; i++) {
8844                PackageParser.Activity a = pkg.activities.get(i);
8845                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8846                        a.info.processName, pkg.applicationInfo.uid);
8847                mActivities.addActivity(a, "activity");
8848                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8849                    if (r == null) {
8850                        r = new StringBuilder(256);
8851                    } else {
8852                        r.append(' ');
8853                    }
8854                    r.append(a.info.name);
8855                }
8856            }
8857            if (r != null) {
8858                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8859            }
8860
8861            N = pkg.permissionGroups.size();
8862            r = null;
8863            for (i=0; i<N; i++) {
8864                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8865                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8866                final String curPackageName = cur == null ? null : cur.info.packageName;
8867                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8868                if (cur == null || isPackageUpdate) {
8869                    mPermissionGroups.put(pg.info.name, pg);
8870                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8871                        if (r == null) {
8872                            r = new StringBuilder(256);
8873                        } else {
8874                            r.append(' ');
8875                        }
8876                        if (isPackageUpdate) {
8877                            r.append("UPD:");
8878                        }
8879                        r.append(pg.info.name);
8880                    }
8881                } else {
8882                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8883                            + pg.info.packageName + " ignored: original from "
8884                            + cur.info.packageName);
8885                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8886                        if (r == null) {
8887                            r = new StringBuilder(256);
8888                        } else {
8889                            r.append(' ');
8890                        }
8891                        r.append("DUP:");
8892                        r.append(pg.info.name);
8893                    }
8894                }
8895            }
8896            if (r != null) {
8897                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8898            }
8899
8900            N = pkg.permissions.size();
8901            r = null;
8902            for (i=0; i<N; i++) {
8903                PackageParser.Permission p = pkg.permissions.get(i);
8904
8905                // Assume by default that we did not install this permission into the system.
8906                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8907
8908                // Now that permission groups have a special meaning, we ignore permission
8909                // groups for legacy apps to prevent unexpected behavior. In particular,
8910                // permissions for one app being granted to someone just becase they happen
8911                // to be in a group defined by another app (before this had no implications).
8912                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8913                    p.group = mPermissionGroups.get(p.info.group);
8914                    // Warn for a permission in an unknown group.
8915                    if (p.info.group != null && p.group == null) {
8916                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8917                                + p.info.packageName + " in an unknown group " + p.info.group);
8918                    }
8919                }
8920
8921                ArrayMap<String, BasePermission> permissionMap =
8922                        p.tree ? mSettings.mPermissionTrees
8923                                : mSettings.mPermissions;
8924                BasePermission bp = permissionMap.get(p.info.name);
8925
8926                // Allow system apps to redefine non-system permissions
8927                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8928                    final boolean currentOwnerIsSystem = (bp.perm != null
8929                            && isSystemApp(bp.perm.owner));
8930                    if (isSystemApp(p.owner)) {
8931                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8932                            // It's a built-in permission and no owner, take ownership now
8933                            bp.packageSetting = pkgSetting;
8934                            bp.perm = p;
8935                            bp.uid = pkg.applicationInfo.uid;
8936                            bp.sourcePackage = p.info.packageName;
8937                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8938                        } else if (!currentOwnerIsSystem) {
8939                            String msg = "New decl " + p.owner + " of permission  "
8940                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8941                            reportSettingsProblem(Log.WARN, msg);
8942                            bp = null;
8943                        }
8944                    }
8945                }
8946
8947                if (bp == null) {
8948                    bp = new BasePermission(p.info.name, p.info.packageName,
8949                            BasePermission.TYPE_NORMAL);
8950                    permissionMap.put(p.info.name, bp);
8951                }
8952
8953                if (bp.perm == null) {
8954                    if (bp.sourcePackage == null
8955                            || bp.sourcePackage.equals(p.info.packageName)) {
8956                        BasePermission tree = findPermissionTreeLP(p.info.name);
8957                        if (tree == null
8958                                || tree.sourcePackage.equals(p.info.packageName)) {
8959                            bp.packageSetting = pkgSetting;
8960                            bp.perm = p;
8961                            bp.uid = pkg.applicationInfo.uid;
8962                            bp.sourcePackage = p.info.packageName;
8963                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8964                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8965                                if (r == null) {
8966                                    r = new StringBuilder(256);
8967                                } else {
8968                                    r.append(' ');
8969                                }
8970                                r.append(p.info.name);
8971                            }
8972                        } else {
8973                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8974                                    + p.info.packageName + " ignored: base tree "
8975                                    + tree.name + " is from package "
8976                                    + tree.sourcePackage);
8977                        }
8978                    } else {
8979                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8980                                + p.info.packageName + " ignored: original from "
8981                                + bp.sourcePackage);
8982                    }
8983                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8984                    if (r == null) {
8985                        r = new StringBuilder(256);
8986                    } else {
8987                        r.append(' ');
8988                    }
8989                    r.append("DUP:");
8990                    r.append(p.info.name);
8991                }
8992                if (bp.perm == p) {
8993                    bp.protectionLevel = p.info.protectionLevel;
8994                }
8995            }
8996
8997            if (r != null) {
8998                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8999            }
9000
9001            N = pkg.instrumentation.size();
9002            r = null;
9003            for (i=0; i<N; i++) {
9004                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9005                a.info.packageName = pkg.applicationInfo.packageName;
9006                a.info.sourceDir = pkg.applicationInfo.sourceDir;
9007                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
9008                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
9009                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
9010                a.info.dataDir = pkg.applicationInfo.dataDir;
9011                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
9012                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
9013
9014                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
9015                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
9016                mInstrumentation.put(a.getComponentName(), a);
9017                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
9018                    if (r == null) {
9019                        r = new StringBuilder(256);
9020                    } else {
9021                        r.append(' ');
9022                    }
9023                    r.append(a.info.name);
9024                }
9025            }
9026            if (r != null) {
9027                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
9028            }
9029
9030            if (pkg.protectedBroadcasts != null) {
9031                N = pkg.protectedBroadcasts.size();
9032                for (i=0; i<N; i++) {
9033                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
9034                }
9035            }
9036
9037            pkgSetting.setTimeStamp(scanFileTime);
9038
9039            // Create idmap files for pairs of (packages, overlay packages).
9040            // Note: "android", ie framework-res.apk, is handled by native layers.
9041            if (pkg.mOverlayTarget != null) {
9042                // This is an overlay package.
9043                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9044                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9045                        mOverlays.put(pkg.mOverlayTarget,
9046                                new ArrayMap<String, PackageParser.Package>());
9047                    }
9048                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9049                    map.put(pkg.packageName, pkg);
9050                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9051                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9052                        createIdmapFailed = true;
9053                    }
9054                }
9055            } else if (mOverlays.containsKey(pkg.packageName) &&
9056                    !pkg.packageName.equals("android")) {
9057                // This is a regular package, with one or more known overlay packages.
9058                createIdmapsForPackageLI(pkg);
9059            }
9060        }
9061
9062        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9063
9064        if (createIdmapFailed) {
9065            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9066                    "scanPackageLI failed to createIdmap");
9067        }
9068        return pkg;
9069    }
9070
9071    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9072            PackageParser.Package update, UserHandle user) {
9073        if (existing.applicationInfo == null || update.applicationInfo == null) {
9074            // This isn't due to an app installation.
9075            return;
9076        }
9077
9078        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9079        final File newCodePath = new File(update.applicationInfo.getCodePath());
9080
9081        // The codePath hasn't changed, so there's nothing for us to do.
9082        if (Objects.equals(oldCodePath, newCodePath)) {
9083            return;
9084        }
9085
9086        File canonicalNewCodePath;
9087        try {
9088            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9089        } catch (IOException e) {
9090            Slog.w(TAG, "Failed to get canonical path.", e);
9091            return;
9092        }
9093
9094        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9095        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9096        // that the last component of the path (i.e, the name) doesn't need canonicalization
9097        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9098        // but may change in the future. Hopefully this function won't exist at that point.
9099        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9100                oldCodePath.getName());
9101
9102        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9103        // with "@".
9104        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9105        if (!oldMarkerPrefix.endsWith("@")) {
9106            oldMarkerPrefix += "@";
9107        }
9108        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9109        if (!newMarkerPrefix.endsWith("@")) {
9110            newMarkerPrefix += "@";
9111        }
9112
9113        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9114        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9115        for (String updatedPath : updatedPaths) {
9116            String updatedPathName = new File(updatedPath).getName();
9117            markerSuffixes.add(updatedPathName.replace('/', '@'));
9118        }
9119
9120        for (int userId : resolveUserIds(user.getIdentifier())) {
9121            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9122
9123            for (String markerSuffix : markerSuffixes) {
9124                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9125                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9126                if (oldForeignUseMark.exists()) {
9127                    try {
9128                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9129                                newForeignUseMark.getAbsolutePath());
9130                    } catch (ErrnoException e) {
9131                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9132                        oldForeignUseMark.delete();
9133                    }
9134                }
9135            }
9136        }
9137    }
9138
9139    /**
9140     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9141     * is derived purely on the basis of the contents of {@code scanFile} and
9142     * {@code cpuAbiOverride}.
9143     *
9144     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9145     */
9146    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9147                                 String cpuAbiOverride, boolean extractLibs)
9148            throws PackageManagerException {
9149        // TODO: We can probably be smarter about this stuff. For installed apps,
9150        // we can calculate this information at install time once and for all. For
9151        // system apps, we can probably assume that this information doesn't change
9152        // after the first boot scan. As things stand, we do lots of unnecessary work.
9153
9154        // Give ourselves some initial paths; we'll come back for another
9155        // pass once we've determined ABI below.
9156        setNativeLibraryPaths(pkg);
9157
9158        // We would never need to extract libs for forward-locked and external packages,
9159        // since the container service will do it for us. We shouldn't attempt to
9160        // extract libs from system app when it was not updated.
9161        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9162                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9163            extractLibs = false;
9164        }
9165
9166        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9167        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9168
9169        NativeLibraryHelper.Handle handle = null;
9170        try {
9171            handle = NativeLibraryHelper.Handle.create(pkg);
9172            // TODO(multiArch): This can be null for apps that didn't go through the
9173            // usual installation process. We can calculate it again, like we
9174            // do during install time.
9175            //
9176            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9177            // unnecessary.
9178            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9179
9180            // Null out the abis so that they can be recalculated.
9181            pkg.applicationInfo.primaryCpuAbi = null;
9182            pkg.applicationInfo.secondaryCpuAbi = null;
9183            if (isMultiArch(pkg.applicationInfo)) {
9184                // Warn if we've set an abiOverride for multi-lib packages..
9185                // By definition, we need to copy both 32 and 64 bit libraries for
9186                // such packages.
9187                if (pkg.cpuAbiOverride != null
9188                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9189                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9190                }
9191
9192                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9193                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9194                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9195                    if (extractLibs) {
9196                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9197                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9198                                useIsaSpecificSubdirs);
9199                    } else {
9200                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9201                    }
9202                }
9203
9204                maybeThrowExceptionForMultiArchCopy(
9205                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9206
9207                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9208                    if (extractLibs) {
9209                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9210                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9211                                useIsaSpecificSubdirs);
9212                    } else {
9213                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9214                    }
9215                }
9216
9217                maybeThrowExceptionForMultiArchCopy(
9218                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9219
9220                if (abi64 >= 0) {
9221                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9222                }
9223
9224                if (abi32 >= 0) {
9225                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9226                    if (abi64 >= 0) {
9227                        if (pkg.use32bitAbi) {
9228                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9229                            pkg.applicationInfo.primaryCpuAbi = abi;
9230                        } else {
9231                            pkg.applicationInfo.secondaryCpuAbi = abi;
9232                        }
9233                    } else {
9234                        pkg.applicationInfo.primaryCpuAbi = abi;
9235                    }
9236                }
9237
9238            } else {
9239                String[] abiList = (cpuAbiOverride != null) ?
9240                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9241
9242                // Enable gross and lame hacks for apps that are built with old
9243                // SDK tools. We must scan their APKs for renderscript bitcode and
9244                // not launch them if it's present. Don't bother checking on devices
9245                // that don't have 64 bit support.
9246                boolean needsRenderScriptOverride = false;
9247                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9248                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9249                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9250                    needsRenderScriptOverride = true;
9251                }
9252
9253                final int copyRet;
9254                if (extractLibs) {
9255                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9256                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9257                } else {
9258                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9259                }
9260
9261                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9262                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9263                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9264                }
9265
9266                if (copyRet >= 0) {
9267                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9268                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9269                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9270                } else if (needsRenderScriptOverride) {
9271                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9272                }
9273            }
9274        } catch (IOException ioe) {
9275            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9276        } finally {
9277            IoUtils.closeQuietly(handle);
9278        }
9279
9280        // Now that we've calculated the ABIs and determined if it's an internal app,
9281        // we will go ahead and populate the nativeLibraryPath.
9282        setNativeLibraryPaths(pkg);
9283    }
9284
9285    /**
9286     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9287     * i.e, so that all packages can be run inside a single process if required.
9288     *
9289     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9290     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9291     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9292     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9293     * updating a package that belongs to a shared user.
9294     *
9295     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9296     * adds unnecessary complexity.
9297     */
9298    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9299            PackageParser.Package scannedPackage, boolean bootComplete) {
9300        String requiredInstructionSet = null;
9301        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9302            requiredInstructionSet = VMRuntime.getInstructionSet(
9303                     scannedPackage.applicationInfo.primaryCpuAbi);
9304        }
9305
9306        PackageSetting requirer = null;
9307        for (PackageSetting ps : packagesForUser) {
9308            // If packagesForUser contains scannedPackage, we skip it. This will happen
9309            // when scannedPackage is an update of an existing package. Without this check,
9310            // we will never be able to change the ABI of any package belonging to a shared
9311            // user, even if it's compatible with other packages.
9312            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9313                if (ps.primaryCpuAbiString == null) {
9314                    continue;
9315                }
9316
9317                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9318                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9319                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9320                    // this but there's not much we can do.
9321                    String errorMessage = "Instruction set mismatch, "
9322                            + ((requirer == null) ? "[caller]" : requirer)
9323                            + " requires " + requiredInstructionSet + " whereas " + ps
9324                            + " requires " + instructionSet;
9325                    Slog.w(TAG, errorMessage);
9326                }
9327
9328                if (requiredInstructionSet == null) {
9329                    requiredInstructionSet = instructionSet;
9330                    requirer = ps;
9331                }
9332            }
9333        }
9334
9335        if (requiredInstructionSet != null) {
9336            String adjustedAbi;
9337            if (requirer != null) {
9338                // requirer != null implies that either scannedPackage was null or that scannedPackage
9339                // did not require an ABI, in which case we have to adjust scannedPackage to match
9340                // the ABI of the set (which is the same as requirer's ABI)
9341                adjustedAbi = requirer.primaryCpuAbiString;
9342                if (scannedPackage != null) {
9343                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9344                }
9345            } else {
9346                // requirer == null implies that we're updating all ABIs in the set to
9347                // match scannedPackage.
9348                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9349            }
9350
9351            for (PackageSetting ps : packagesForUser) {
9352                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9353                    if (ps.primaryCpuAbiString != null) {
9354                        continue;
9355                    }
9356
9357                    ps.primaryCpuAbiString = adjustedAbi;
9358                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9359                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9360                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9361                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9362                                + " (requirer="
9363                                + (requirer == null ? "null" : requirer.pkg.packageName)
9364                                + ", scannedPackage="
9365                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9366                                + ")");
9367                        try {
9368                            mInstaller.rmdex(ps.codePathString,
9369                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9370                        } catch (InstallerException ignored) {
9371                        }
9372                    }
9373                }
9374            }
9375        }
9376    }
9377
9378    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9379        synchronized (mPackages) {
9380            mResolverReplaced = true;
9381            // Set up information for custom user intent resolution activity.
9382            mResolveActivity.applicationInfo = pkg.applicationInfo;
9383            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9384            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9385            mResolveActivity.processName = pkg.applicationInfo.packageName;
9386            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9387            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9388                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9389            mResolveActivity.theme = 0;
9390            mResolveActivity.exported = true;
9391            mResolveActivity.enabled = true;
9392            mResolveInfo.activityInfo = mResolveActivity;
9393            mResolveInfo.priority = 0;
9394            mResolveInfo.preferredOrder = 0;
9395            mResolveInfo.match = 0;
9396            mResolveComponentName = mCustomResolverComponentName;
9397            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9398                    mResolveComponentName);
9399        }
9400    }
9401
9402    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9403        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9404
9405        // Set up information for ephemeral installer activity
9406        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9407        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9408        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9409        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9410        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9411        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9412                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9413        mEphemeralInstallerActivity.theme = 0;
9414        mEphemeralInstallerActivity.exported = true;
9415        mEphemeralInstallerActivity.enabled = true;
9416        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9417        mEphemeralInstallerInfo.priority = 0;
9418        mEphemeralInstallerInfo.preferredOrder = 1;
9419        mEphemeralInstallerInfo.isDefault = true;
9420        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9421                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9422
9423        if (DEBUG_EPHEMERAL) {
9424            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9425        }
9426    }
9427
9428    private static String calculateBundledApkRoot(final String codePathString) {
9429        final File codePath = new File(codePathString);
9430        final File codeRoot;
9431        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9432            codeRoot = Environment.getRootDirectory();
9433        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9434            codeRoot = Environment.getOemDirectory();
9435        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9436            codeRoot = Environment.getVendorDirectory();
9437        } else {
9438            // Unrecognized code path; take its top real segment as the apk root:
9439            // e.g. /something/app/blah.apk => /something
9440            try {
9441                File f = codePath.getCanonicalFile();
9442                File parent = f.getParentFile();    // non-null because codePath is a file
9443                File tmp;
9444                while ((tmp = parent.getParentFile()) != null) {
9445                    f = parent;
9446                    parent = tmp;
9447                }
9448                codeRoot = f;
9449                Slog.w(TAG, "Unrecognized code path "
9450                        + codePath + " - using " + codeRoot);
9451            } catch (IOException e) {
9452                // Can't canonicalize the code path -- shenanigans?
9453                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9454                return Environment.getRootDirectory().getPath();
9455            }
9456        }
9457        return codeRoot.getPath();
9458    }
9459
9460    /**
9461     * Derive and set the location of native libraries for the given package,
9462     * which varies depending on where and how the package was installed.
9463     */
9464    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9465        final ApplicationInfo info = pkg.applicationInfo;
9466        final String codePath = pkg.codePath;
9467        final File codeFile = new File(codePath);
9468        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9469        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9470
9471        info.nativeLibraryRootDir = null;
9472        info.nativeLibraryRootRequiresIsa = false;
9473        info.nativeLibraryDir = null;
9474        info.secondaryNativeLibraryDir = null;
9475
9476        if (isApkFile(codeFile)) {
9477            // Monolithic install
9478            if (bundledApp) {
9479                // If "/system/lib64/apkname" exists, assume that is the per-package
9480                // native library directory to use; otherwise use "/system/lib/apkname".
9481                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9482                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9483                        getPrimaryInstructionSet(info));
9484
9485                // This is a bundled system app so choose the path based on the ABI.
9486                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9487                // is just the default path.
9488                final String apkName = deriveCodePathName(codePath);
9489                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9490                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9491                        apkName).getAbsolutePath();
9492
9493                if (info.secondaryCpuAbi != null) {
9494                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9495                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9496                            secondaryLibDir, apkName).getAbsolutePath();
9497                }
9498            } else if (asecApp) {
9499                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9500                        .getAbsolutePath();
9501            } else {
9502                final String apkName = deriveCodePathName(codePath);
9503                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9504                        .getAbsolutePath();
9505            }
9506
9507            info.nativeLibraryRootRequiresIsa = false;
9508            info.nativeLibraryDir = info.nativeLibraryRootDir;
9509        } else {
9510            // Cluster install
9511            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9512            info.nativeLibraryRootRequiresIsa = true;
9513
9514            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9515                    getPrimaryInstructionSet(info)).getAbsolutePath();
9516
9517            if (info.secondaryCpuAbi != null) {
9518                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9519                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9520            }
9521        }
9522    }
9523
9524    /**
9525     * Calculate the abis and roots for a bundled app. These can uniquely
9526     * be determined from the contents of the system partition, i.e whether
9527     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9528     * of this information, and instead assume that the system was built
9529     * sensibly.
9530     */
9531    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9532                                           PackageSetting pkgSetting) {
9533        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9534
9535        // If "/system/lib64/apkname" exists, assume that is the per-package
9536        // native library directory to use; otherwise use "/system/lib/apkname".
9537        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9538        setBundledAppAbi(pkg, apkRoot, apkName);
9539        // pkgSetting might be null during rescan following uninstall of updates
9540        // to a bundled app, so accommodate that possibility.  The settings in
9541        // that case will be established later from the parsed package.
9542        //
9543        // If the settings aren't null, sync them up with what we've just derived.
9544        // note that apkRoot isn't stored in the package settings.
9545        if (pkgSetting != null) {
9546            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9547            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9548        }
9549    }
9550
9551    /**
9552     * Deduces the ABI of a bundled app and sets the relevant fields on the
9553     * parsed pkg object.
9554     *
9555     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9556     *        under which system libraries are installed.
9557     * @param apkName the name of the installed package.
9558     */
9559    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9560        final File codeFile = new File(pkg.codePath);
9561
9562        final boolean has64BitLibs;
9563        final boolean has32BitLibs;
9564        if (isApkFile(codeFile)) {
9565            // Monolithic install
9566            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9567            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9568        } else {
9569            // Cluster install
9570            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9571            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9572                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9573                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9574                has64BitLibs = (new File(rootDir, isa)).exists();
9575            } else {
9576                has64BitLibs = false;
9577            }
9578            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9579                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9580                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9581                has32BitLibs = (new File(rootDir, isa)).exists();
9582            } else {
9583                has32BitLibs = false;
9584            }
9585        }
9586
9587        if (has64BitLibs && !has32BitLibs) {
9588            // The package has 64 bit libs, but not 32 bit libs. Its primary
9589            // ABI should be 64 bit. We can safely assume here that the bundled
9590            // native libraries correspond to the most preferred ABI in the list.
9591
9592            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9593            pkg.applicationInfo.secondaryCpuAbi = null;
9594        } else if (has32BitLibs && !has64BitLibs) {
9595            // The package has 32 bit libs but not 64 bit libs. Its primary
9596            // ABI should be 32 bit.
9597
9598            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9599            pkg.applicationInfo.secondaryCpuAbi = null;
9600        } else if (has32BitLibs && has64BitLibs) {
9601            // The application has both 64 and 32 bit bundled libraries. We check
9602            // here that the app declares multiArch support, and warn if it doesn't.
9603            //
9604            // We will be lenient here and record both ABIs. The primary will be the
9605            // ABI that's higher on the list, i.e, a device that's configured to prefer
9606            // 64 bit apps will see a 64 bit primary ABI,
9607
9608            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9609                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9610            }
9611
9612            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9613                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9614                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9615            } else {
9616                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9617                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9618            }
9619        } else {
9620            pkg.applicationInfo.primaryCpuAbi = null;
9621            pkg.applicationInfo.secondaryCpuAbi = null;
9622        }
9623    }
9624
9625    private void killApplication(String pkgName, int appId, String reason) {
9626        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9627    }
9628
9629    private void killApplication(String pkgName, int appId, int userId, String reason) {
9630        // Request the ActivityManager to kill the process(only for existing packages)
9631        // so that we do not end up in a confused state while the user is still using the older
9632        // version of the application while the new one gets installed.
9633        final long token = Binder.clearCallingIdentity();
9634        try {
9635            IActivityManager am = ActivityManagerNative.getDefault();
9636            if (am != null) {
9637                try {
9638                    am.killApplication(pkgName, appId, userId, reason);
9639                } catch (RemoteException e) {
9640                }
9641            }
9642        } finally {
9643            Binder.restoreCallingIdentity(token);
9644        }
9645    }
9646
9647    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9648        // Remove the parent package setting
9649        PackageSetting ps = (PackageSetting) pkg.mExtras;
9650        if (ps != null) {
9651            removePackageLI(ps, chatty);
9652        }
9653        // Remove the child package setting
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            ps = (PackageSetting) childPkg.mExtras;
9658            if (ps != null) {
9659                removePackageLI(ps, chatty);
9660            }
9661        }
9662    }
9663
9664    void removePackageLI(PackageSetting ps, boolean chatty) {
9665        if (DEBUG_INSTALL) {
9666            if (chatty)
9667                Log.d(TAG, "Removing package " + ps.name);
9668        }
9669
9670        // writer
9671        synchronized (mPackages) {
9672            mPackages.remove(ps.name);
9673            final PackageParser.Package pkg = ps.pkg;
9674            if (pkg != null) {
9675                cleanPackageDataStructuresLILPw(pkg, chatty);
9676            }
9677        }
9678    }
9679
9680    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9681        if (DEBUG_INSTALL) {
9682            if (chatty)
9683                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9684        }
9685
9686        // writer
9687        synchronized (mPackages) {
9688            // Remove the parent package
9689            mPackages.remove(pkg.applicationInfo.packageName);
9690            cleanPackageDataStructuresLILPw(pkg, chatty);
9691
9692            // Remove the child packages
9693            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9694            for (int i = 0; i < childCount; i++) {
9695                PackageParser.Package childPkg = pkg.childPackages.get(i);
9696                mPackages.remove(childPkg.applicationInfo.packageName);
9697                cleanPackageDataStructuresLILPw(childPkg, chatty);
9698            }
9699        }
9700    }
9701
9702    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9703        int N = pkg.providers.size();
9704        StringBuilder r = null;
9705        int i;
9706        for (i=0; i<N; i++) {
9707            PackageParser.Provider p = pkg.providers.get(i);
9708            mProviders.removeProvider(p);
9709            if (p.info.authority == null) {
9710
9711                /* There was another ContentProvider with this authority when
9712                 * this app was installed so this authority is null,
9713                 * Ignore it as we don't have to unregister the provider.
9714                 */
9715                continue;
9716            }
9717            String names[] = p.info.authority.split(";");
9718            for (int j = 0; j < names.length; j++) {
9719                if (mProvidersByAuthority.get(names[j]) == p) {
9720                    mProvidersByAuthority.remove(names[j]);
9721                    if (DEBUG_REMOVE) {
9722                        if (chatty)
9723                            Log.d(TAG, "Unregistered content provider: " + names[j]
9724                                    + ", className = " + p.info.name + ", isSyncable = "
9725                                    + p.info.isSyncable);
9726                    }
9727                }
9728            }
9729            if (DEBUG_REMOVE && chatty) {
9730                if (r == null) {
9731                    r = new StringBuilder(256);
9732                } else {
9733                    r.append(' ');
9734                }
9735                r.append(p.info.name);
9736            }
9737        }
9738        if (r != null) {
9739            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9740        }
9741
9742        N = pkg.services.size();
9743        r = null;
9744        for (i=0; i<N; i++) {
9745            PackageParser.Service s = pkg.services.get(i);
9746            mServices.removeService(s);
9747            if (chatty) {
9748                if (r == null) {
9749                    r = new StringBuilder(256);
9750                } else {
9751                    r.append(' ');
9752                }
9753                r.append(s.info.name);
9754            }
9755        }
9756        if (r != null) {
9757            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9758        }
9759
9760        N = pkg.receivers.size();
9761        r = null;
9762        for (i=0; i<N; i++) {
9763            PackageParser.Activity a = pkg.receivers.get(i);
9764            mReceivers.removeActivity(a, "receiver");
9765            if (DEBUG_REMOVE && chatty) {
9766                if (r == null) {
9767                    r = new StringBuilder(256);
9768                } else {
9769                    r.append(' ');
9770                }
9771                r.append(a.info.name);
9772            }
9773        }
9774        if (r != null) {
9775            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9776        }
9777
9778        N = pkg.activities.size();
9779        r = null;
9780        for (i=0; i<N; i++) {
9781            PackageParser.Activity a = pkg.activities.get(i);
9782            mActivities.removeActivity(a, "activity");
9783            if (DEBUG_REMOVE && chatty) {
9784                if (r == null) {
9785                    r = new StringBuilder(256);
9786                } else {
9787                    r.append(' ');
9788                }
9789                r.append(a.info.name);
9790            }
9791        }
9792        if (r != null) {
9793            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9794        }
9795
9796        N = pkg.permissions.size();
9797        r = null;
9798        for (i=0; i<N; i++) {
9799            PackageParser.Permission p = pkg.permissions.get(i);
9800            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9801            if (bp == null) {
9802                bp = mSettings.mPermissionTrees.get(p.info.name);
9803            }
9804            if (bp != null && bp.perm == p) {
9805                bp.perm = null;
9806                if (DEBUG_REMOVE && chatty) {
9807                    if (r == null) {
9808                        r = new StringBuilder(256);
9809                    } else {
9810                        r.append(' ');
9811                    }
9812                    r.append(p.info.name);
9813                }
9814            }
9815            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9816                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9817                if (appOpPkgs != null) {
9818                    appOpPkgs.remove(pkg.packageName);
9819                }
9820            }
9821        }
9822        if (r != null) {
9823            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9824        }
9825
9826        N = pkg.requestedPermissions.size();
9827        r = null;
9828        for (i=0; i<N; i++) {
9829            String perm = pkg.requestedPermissions.get(i);
9830            BasePermission bp = mSettings.mPermissions.get(perm);
9831            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9832                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9833                if (appOpPkgs != null) {
9834                    appOpPkgs.remove(pkg.packageName);
9835                    if (appOpPkgs.isEmpty()) {
9836                        mAppOpPermissionPackages.remove(perm);
9837                    }
9838                }
9839            }
9840        }
9841        if (r != null) {
9842            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9843        }
9844
9845        N = pkg.instrumentation.size();
9846        r = null;
9847        for (i=0; i<N; i++) {
9848            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9849            mInstrumentation.remove(a.getComponentName());
9850            if (DEBUG_REMOVE && chatty) {
9851                if (r == null) {
9852                    r = new StringBuilder(256);
9853                } else {
9854                    r.append(' ');
9855                }
9856                r.append(a.info.name);
9857            }
9858        }
9859        if (r != null) {
9860            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9861        }
9862
9863        r = null;
9864        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9865            // Only system apps can hold shared libraries.
9866            if (pkg.libraryNames != null) {
9867                for (i=0; i<pkg.libraryNames.size(); i++) {
9868                    String name = pkg.libraryNames.get(i);
9869                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9870                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9871                        mSharedLibraries.remove(name);
9872                        if (DEBUG_REMOVE && chatty) {
9873                            if (r == null) {
9874                                r = new StringBuilder(256);
9875                            } else {
9876                                r.append(' ');
9877                            }
9878                            r.append(name);
9879                        }
9880                    }
9881                }
9882            }
9883        }
9884        if (r != null) {
9885            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9886        }
9887    }
9888
9889    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9890        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9891            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9892                return true;
9893            }
9894        }
9895        return false;
9896    }
9897
9898    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9899    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9900    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9901
9902    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9903        // Update the parent permissions
9904        updatePermissionsLPw(pkg.packageName, pkg, flags);
9905        // Update the child permissions
9906        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9907        for (int i = 0; i < childCount; i++) {
9908            PackageParser.Package childPkg = pkg.childPackages.get(i);
9909            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9910        }
9911    }
9912
9913    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9914            int flags) {
9915        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9916        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9917    }
9918
9919    private void updatePermissionsLPw(String changingPkg,
9920            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9921        // Make sure there are no dangling permission trees.
9922        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9923        while (it.hasNext()) {
9924            final BasePermission bp = it.next();
9925            if (bp.packageSetting == null) {
9926                // We may not yet have parsed the package, so just see if
9927                // we still know about its settings.
9928                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9929            }
9930            if (bp.packageSetting == null) {
9931                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9932                        + " from package " + bp.sourcePackage);
9933                it.remove();
9934            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9935                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9936                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9937                            + " from package " + bp.sourcePackage);
9938                    flags |= UPDATE_PERMISSIONS_ALL;
9939                    it.remove();
9940                }
9941            }
9942        }
9943
9944        // Make sure all dynamic permissions have been assigned to a package,
9945        // and make sure there are no dangling permissions.
9946        it = mSettings.mPermissions.values().iterator();
9947        while (it.hasNext()) {
9948            final BasePermission bp = it.next();
9949            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9950                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9951                        + bp.name + " pkg=" + bp.sourcePackage
9952                        + " info=" + bp.pendingInfo);
9953                if (bp.packageSetting == null && bp.pendingInfo != null) {
9954                    final BasePermission tree = findPermissionTreeLP(bp.name);
9955                    if (tree != null && tree.perm != null) {
9956                        bp.packageSetting = tree.packageSetting;
9957                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9958                                new PermissionInfo(bp.pendingInfo));
9959                        bp.perm.info.packageName = tree.perm.info.packageName;
9960                        bp.perm.info.name = bp.name;
9961                        bp.uid = tree.uid;
9962                    }
9963                }
9964            }
9965            if (bp.packageSetting == null) {
9966                // We may not yet have parsed the package, so just see if
9967                // we still know about its settings.
9968                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9969            }
9970            if (bp.packageSetting == null) {
9971                Slog.w(TAG, "Removing dangling permission: " + bp.name
9972                        + " from package " + bp.sourcePackage);
9973                it.remove();
9974            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9975                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9976                    Slog.i(TAG, "Removing old permission: " + bp.name
9977                            + " from package " + bp.sourcePackage);
9978                    flags |= UPDATE_PERMISSIONS_ALL;
9979                    it.remove();
9980                }
9981            }
9982        }
9983
9984        // Now update the permissions for all packages, in particular
9985        // replace the granted permissions of the system packages.
9986        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9987            for (PackageParser.Package pkg : mPackages.values()) {
9988                if (pkg != pkgInfo) {
9989                    // Only replace for packages on requested volume
9990                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9991                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9992                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9993                    grantPermissionsLPw(pkg, replace, changingPkg);
9994                }
9995            }
9996        }
9997
9998        if (pkgInfo != null) {
9999            // Only replace for packages on requested volume
10000            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
10001            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
10002                    && Objects.equals(replaceVolumeUuid, volumeUuid);
10003            grantPermissionsLPw(pkgInfo, replace, changingPkg);
10004        }
10005    }
10006
10007    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
10008            String packageOfInterest) {
10009        // IMPORTANT: There are two types of permissions: install and runtime.
10010        // Install time permissions are granted when the app is installed to
10011        // all device users and users added in the future. Runtime permissions
10012        // are granted at runtime explicitly to specific users. Normal and signature
10013        // protected permissions are install time permissions. Dangerous permissions
10014        // are install permissions if the app's target SDK is Lollipop MR1 or older,
10015        // otherwise they are runtime permissions. This function does not manage
10016        // runtime permissions except for the case an app targeting Lollipop MR1
10017        // being upgraded to target a newer SDK, in which case dangerous permissions
10018        // are transformed from install time to runtime ones.
10019
10020        final PackageSetting ps = (PackageSetting) pkg.mExtras;
10021        if (ps == null) {
10022            return;
10023        }
10024
10025        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
10026
10027        PermissionsState permissionsState = ps.getPermissionsState();
10028        PermissionsState origPermissions = permissionsState;
10029
10030        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
10031
10032        boolean runtimePermissionsRevoked = false;
10033        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
10034
10035        boolean changedInstallPermission = false;
10036
10037        if (replace) {
10038            ps.installPermissionsFixed = false;
10039            if (!ps.isSharedUser()) {
10040                origPermissions = new PermissionsState(permissionsState);
10041                permissionsState.reset();
10042            } else {
10043                // We need to know only about runtime permission changes since the
10044                // calling code always writes the install permissions state but
10045                // the runtime ones are written only if changed. The only cases of
10046                // changed runtime permissions here are promotion of an install to
10047                // runtime and revocation of a runtime from a shared user.
10048                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
10049                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
10050                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10051                    runtimePermissionsRevoked = true;
10052                }
10053            }
10054        }
10055
10056        permissionsState.setGlobalGids(mGlobalGids);
10057
10058        final int N = pkg.requestedPermissions.size();
10059        for (int i=0; i<N; i++) {
10060            final String name = pkg.requestedPermissions.get(i);
10061            final BasePermission bp = mSettings.mPermissions.get(name);
10062
10063            if (DEBUG_INSTALL) {
10064                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10065            }
10066
10067            if (bp == null || bp.packageSetting == null) {
10068                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10069                    Slog.w(TAG, "Unknown permission " + name
10070                            + " in package " + pkg.packageName);
10071                }
10072                continue;
10073            }
10074
10075            final String perm = bp.name;
10076            boolean allowedSig = false;
10077            int grant = GRANT_DENIED;
10078
10079            // Keep track of app op permissions.
10080            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10081                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10082                if (pkgs == null) {
10083                    pkgs = new ArraySet<>();
10084                    mAppOpPermissionPackages.put(bp.name, pkgs);
10085                }
10086                pkgs.add(pkg.packageName);
10087            }
10088
10089            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10090            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10091                    >= Build.VERSION_CODES.M;
10092            switch (level) {
10093                case PermissionInfo.PROTECTION_NORMAL: {
10094                    // For all apps normal permissions are install time ones.
10095                    grant = GRANT_INSTALL;
10096                } break;
10097
10098                case PermissionInfo.PROTECTION_DANGEROUS: {
10099                    // If a permission review is required for legacy apps we represent
10100                    // their permissions as always granted runtime ones since we need
10101                    // to keep the review required permission flag per user while an
10102                    // install permission's state is shared across all users.
10103                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired
10104                            && !Build.PERMISSIONS_REVIEW_REQUIRED) {
10105                        // For legacy apps dangerous permissions are install time ones.
10106                        grant = GRANT_INSTALL;
10107                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10108                        // For legacy apps that became modern, install becomes runtime.
10109                        grant = GRANT_UPGRADE;
10110                    } else if (mPromoteSystemApps
10111                            && isSystemApp(ps)
10112                            && mExistingSystemPackages.contains(ps.name)) {
10113                        // For legacy system apps, install becomes runtime.
10114                        // We cannot check hasInstallPermission() for system apps since those
10115                        // permissions were granted implicitly and not persisted pre-M.
10116                        grant = GRANT_UPGRADE;
10117                    } else {
10118                        // For modern apps keep runtime permissions unchanged.
10119                        grant = GRANT_RUNTIME;
10120                    }
10121                } break;
10122
10123                case PermissionInfo.PROTECTION_SIGNATURE: {
10124                    // For all apps signature permissions are install time ones.
10125                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10126                    if (allowedSig) {
10127                        grant = GRANT_INSTALL;
10128                    }
10129                } break;
10130            }
10131
10132            if (DEBUG_INSTALL) {
10133                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10134            }
10135
10136            if (grant != GRANT_DENIED) {
10137                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10138                    // If this is an existing, non-system package, then
10139                    // we can't add any new permissions to it.
10140                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10141                        // Except...  if this is a permission that was added
10142                        // to the platform (note: need to only do this when
10143                        // updating the platform).
10144                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10145                            grant = GRANT_DENIED;
10146                        }
10147                    }
10148                }
10149
10150                switch (grant) {
10151                    case GRANT_INSTALL: {
10152                        // Revoke this as runtime permission to handle the case of
10153                        // a runtime permission being downgraded to an install one.
10154                        // Also in permission review mode we keep dangerous permissions
10155                        // for legacy apps
10156                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10157                            if (origPermissions.getRuntimePermissionState(
10158                                    bp.name, userId) != null) {
10159                                // Revoke the runtime permission and clear the flags.
10160                                origPermissions.revokeRuntimePermission(bp, userId);
10161                                origPermissions.updatePermissionFlags(bp, userId,
10162                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10163                                // If we revoked a permission permission, we have to write.
10164                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10165                                        changedRuntimePermissionUserIds, userId);
10166                            }
10167                        }
10168                        // Grant an install permission.
10169                        if (permissionsState.grantInstallPermission(bp) !=
10170                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10171                            changedInstallPermission = true;
10172                        }
10173                    } break;
10174
10175                    case GRANT_RUNTIME: {
10176                        // Grant previously granted runtime permissions.
10177                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10178                            PermissionState permissionState = origPermissions
10179                                    .getRuntimePermissionState(bp.name, userId);
10180                            int flags = permissionState != null
10181                                    ? permissionState.getFlags() : 0;
10182                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10183                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10184                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10185                                    // If we cannot put the permission as it was, we have to write.
10186                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10187                                            changedRuntimePermissionUserIds, userId);
10188                                }
10189                                // If the app supports runtime permissions no need for a review.
10190                                if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
10191                                        && appSupportsRuntimePermissions
10192                                        && (flags & PackageManager
10193                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10194                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10195                                    // Since we changed the flags, we have to write.
10196                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10197                                            changedRuntimePermissionUserIds, userId);
10198                                }
10199                            } else if ((mPermissionReviewRequired
10200                                        || Build.PERMISSIONS_REVIEW_REQUIRED)
10201                                    && !appSupportsRuntimePermissions) {
10202                                // For legacy apps that need a permission review, every new
10203                                // runtime permission is granted but it is pending a review.
10204                                // We also need to review only platform defined runtime
10205                                // permissions as these are the only ones the platform knows
10206                                // how to disable the API to simulate revocation as legacy
10207                                // apps don't expect to run with revoked permissions.
10208                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10209                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10210                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10211                                        // We changed the flags, hence have to write.
10212                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10213                                                changedRuntimePermissionUserIds, userId);
10214                                    }
10215                                }
10216                                if (permissionsState.grantRuntimePermission(bp, userId)
10217                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10218                                    // We changed the permission, hence have to write.
10219                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10220                                            changedRuntimePermissionUserIds, userId);
10221                                }
10222                            }
10223                            // Propagate the permission flags.
10224                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10225                        }
10226                    } break;
10227
10228                    case GRANT_UPGRADE: {
10229                        // Grant runtime permissions for a previously held install permission.
10230                        PermissionState permissionState = origPermissions
10231                                .getInstallPermissionState(bp.name);
10232                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10233
10234                        if (origPermissions.revokeInstallPermission(bp)
10235                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10236                            // We will be transferring the permission flags, so clear them.
10237                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10238                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10239                            changedInstallPermission = true;
10240                        }
10241
10242                        // If the permission is not to be promoted to runtime we ignore it and
10243                        // also its other flags as they are not applicable to install permissions.
10244                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10245                            for (int userId : currentUserIds) {
10246                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10247                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10248                                    // Transfer the permission flags.
10249                                    permissionsState.updatePermissionFlags(bp, userId,
10250                                            flags, flags);
10251                                    // If we granted the permission, we have to write.
10252                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10253                                            changedRuntimePermissionUserIds, userId);
10254                                }
10255                            }
10256                        }
10257                    } break;
10258
10259                    default: {
10260                        if (packageOfInterest == null
10261                                || packageOfInterest.equals(pkg.packageName)) {
10262                            Slog.w(TAG, "Not granting permission " + perm
10263                                    + " to package " + pkg.packageName
10264                                    + " because it was previously installed without");
10265                        }
10266                    } break;
10267                }
10268            } else {
10269                if (permissionsState.revokeInstallPermission(bp) !=
10270                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10271                    // Also drop the permission flags.
10272                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10273                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10274                    changedInstallPermission = true;
10275                    Slog.i(TAG, "Un-granting permission " + perm
10276                            + " from package " + pkg.packageName
10277                            + " (protectionLevel=" + bp.protectionLevel
10278                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10279                            + ")");
10280                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10281                    // Don't print warning for app op permissions, since it is fine for them
10282                    // not to be granted, there is a UI for the user to decide.
10283                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10284                        Slog.w(TAG, "Not granting permission " + perm
10285                                + " to package " + pkg.packageName
10286                                + " (protectionLevel=" + bp.protectionLevel
10287                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10288                                + ")");
10289                    }
10290                }
10291            }
10292        }
10293
10294        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10295                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10296            // This is the first that we have heard about this package, so the
10297            // permissions we have now selected are fixed until explicitly
10298            // changed.
10299            ps.installPermissionsFixed = true;
10300        }
10301
10302        // Persist the runtime permissions state for users with changes. If permissions
10303        // were revoked because no app in the shared user declares them we have to
10304        // write synchronously to avoid losing runtime permissions state.
10305        for (int userId : changedRuntimePermissionUserIds) {
10306            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10307        }
10308
10309        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10310    }
10311
10312    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10313        boolean allowed = false;
10314        final int NP = PackageParser.NEW_PERMISSIONS.length;
10315        for (int ip=0; ip<NP; ip++) {
10316            final PackageParser.NewPermissionInfo npi
10317                    = PackageParser.NEW_PERMISSIONS[ip];
10318            if (npi.name.equals(perm)
10319                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10320                allowed = true;
10321                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10322                        + pkg.packageName);
10323                break;
10324            }
10325        }
10326        return allowed;
10327    }
10328
10329    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10330            BasePermission bp, PermissionsState origPermissions) {
10331        boolean allowed;
10332        allowed = (compareSignatures(
10333                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10334                        == PackageManager.SIGNATURE_MATCH)
10335                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10336                        == PackageManager.SIGNATURE_MATCH);
10337        if (!allowed && (bp.protectionLevel
10338                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10339            if (isSystemApp(pkg)) {
10340                // For updated system applications, a system permission
10341                // is granted only if it had been defined by the original application.
10342                if (pkg.isUpdatedSystemApp()) {
10343                    final PackageSetting sysPs = mSettings
10344                            .getDisabledSystemPkgLPr(pkg.packageName);
10345                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10346                        // If the original was granted this permission, we take
10347                        // that grant decision as read and propagate it to the
10348                        // update.
10349                        if (sysPs.isPrivileged()) {
10350                            allowed = true;
10351                        }
10352                    } else {
10353                        // The system apk may have been updated with an older
10354                        // version of the one on the data partition, but which
10355                        // granted a new system permission that it didn't have
10356                        // before.  In this case we do want to allow the app to
10357                        // now get the new permission if the ancestral apk is
10358                        // privileged to get it.
10359                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10360                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10361                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10362                                    allowed = true;
10363                                    break;
10364                                }
10365                            }
10366                        }
10367                        // Also if a privileged parent package on the system image or any of
10368                        // its children requested a privileged permission, the updated child
10369                        // packages can also get the permission.
10370                        if (pkg.parentPackage != null) {
10371                            final PackageSetting disabledSysParentPs = mSettings
10372                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10373                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10374                                    && disabledSysParentPs.isPrivileged()) {
10375                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10376                                    allowed = true;
10377                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10378                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10379                                    for (int i = 0; i < count; i++) {
10380                                        PackageParser.Package disabledSysChildPkg =
10381                                                disabledSysParentPs.pkg.childPackages.get(i);
10382                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10383                                                perm)) {
10384                                            allowed = true;
10385                                            break;
10386                                        }
10387                                    }
10388                                }
10389                            }
10390                        }
10391                    }
10392                } else {
10393                    allowed = isPrivilegedApp(pkg);
10394                }
10395            }
10396        }
10397        if (!allowed) {
10398            if (!allowed && (bp.protectionLevel
10399                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10400                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10401                // If this was a previously normal/dangerous permission that got moved
10402                // to a system permission as part of the runtime permission redesign, then
10403                // we still want to blindly grant it to old apps.
10404                allowed = true;
10405            }
10406            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10407                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10408                // If this permission is to be granted to the system installer and
10409                // this app is an installer, then it gets the permission.
10410                allowed = true;
10411            }
10412            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10413                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10414                // If this permission is to be granted to the system verifier and
10415                // this app is a verifier, then it gets the permission.
10416                allowed = true;
10417            }
10418            if (!allowed && (bp.protectionLevel
10419                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10420                    && isSystemApp(pkg)) {
10421                // Any pre-installed system app is allowed to get this permission.
10422                allowed = true;
10423            }
10424            if (!allowed && (bp.protectionLevel
10425                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10426                // For development permissions, a development permission
10427                // is granted only if it was already granted.
10428                allowed = origPermissions.hasInstallPermission(perm);
10429            }
10430            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10431                    && pkg.packageName.equals(mSetupWizardPackage)) {
10432                // If this permission is to be granted to the system setup wizard and
10433                // this app is a setup wizard, then it gets the permission.
10434                allowed = true;
10435            }
10436        }
10437        return allowed;
10438    }
10439
10440    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10441        final int permCount = pkg.requestedPermissions.size();
10442        for (int j = 0; j < permCount; j++) {
10443            String requestedPermission = pkg.requestedPermissions.get(j);
10444            if (permission.equals(requestedPermission)) {
10445                return true;
10446            }
10447        }
10448        return false;
10449    }
10450
10451    final class ActivityIntentResolver
10452            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10453        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10454                boolean defaultOnly, int userId) {
10455            if (!sUserManager.exists(userId)) return null;
10456            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10457            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10458        }
10459
10460        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10461                int userId) {
10462            if (!sUserManager.exists(userId)) return null;
10463            mFlags = flags;
10464            return super.queryIntent(intent, resolvedType,
10465                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10466        }
10467
10468        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10469                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10470            if (!sUserManager.exists(userId)) return null;
10471            if (packageActivities == null) {
10472                return null;
10473            }
10474            mFlags = flags;
10475            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10476            final int N = packageActivities.size();
10477            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10478                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10479
10480            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10481            for (int i = 0; i < N; ++i) {
10482                intentFilters = packageActivities.get(i).intents;
10483                if (intentFilters != null && intentFilters.size() > 0) {
10484                    PackageParser.ActivityIntentInfo[] array =
10485                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10486                    intentFilters.toArray(array);
10487                    listCut.add(array);
10488                }
10489            }
10490            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10491        }
10492
10493        /**
10494         * Finds a privileged activity that matches the specified activity names.
10495         */
10496        private PackageParser.Activity findMatchingActivity(
10497                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10498            for (PackageParser.Activity sysActivity : activityList) {
10499                if (sysActivity.info.name.equals(activityInfo.name)) {
10500                    return sysActivity;
10501                }
10502                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10503                    return sysActivity;
10504                }
10505                if (sysActivity.info.targetActivity != null) {
10506                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10507                        return sysActivity;
10508                    }
10509                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10510                        return sysActivity;
10511                    }
10512                }
10513            }
10514            return null;
10515        }
10516
10517        public class IterGenerator<E> {
10518            public Iterator<E> generate(ActivityIntentInfo info) {
10519                return null;
10520            }
10521        }
10522
10523        public class ActionIterGenerator extends IterGenerator<String> {
10524            @Override
10525            public Iterator<String> generate(ActivityIntentInfo info) {
10526                return info.actionsIterator();
10527            }
10528        }
10529
10530        public class CategoriesIterGenerator extends IterGenerator<String> {
10531            @Override
10532            public Iterator<String> generate(ActivityIntentInfo info) {
10533                return info.categoriesIterator();
10534            }
10535        }
10536
10537        public class SchemesIterGenerator extends IterGenerator<String> {
10538            @Override
10539            public Iterator<String> generate(ActivityIntentInfo info) {
10540                return info.schemesIterator();
10541            }
10542        }
10543
10544        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10545            @Override
10546            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10547                return info.authoritiesIterator();
10548            }
10549        }
10550
10551        /**
10552         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10553         * MODIFIED. Do not pass in a list that should not be changed.
10554         */
10555        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10556                IterGenerator<T> generator, Iterator<T> searchIterator) {
10557            // loop through the set of actions; every one must be found in the intent filter
10558            while (searchIterator.hasNext()) {
10559                // we must have at least one filter in the list to consider a match
10560                if (intentList.size() == 0) {
10561                    break;
10562                }
10563
10564                final T searchAction = searchIterator.next();
10565
10566                // loop through the set of intent filters
10567                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10568                while (intentIter.hasNext()) {
10569                    final ActivityIntentInfo intentInfo = intentIter.next();
10570                    boolean selectionFound = false;
10571
10572                    // loop through the intent filter's selection criteria; at least one
10573                    // of them must match the searched criteria
10574                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10575                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10576                        final T intentSelection = intentSelectionIter.next();
10577                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10578                            selectionFound = true;
10579                            break;
10580                        }
10581                    }
10582
10583                    // the selection criteria wasn't found in this filter's set; this filter
10584                    // is not a potential match
10585                    if (!selectionFound) {
10586                        intentIter.remove();
10587                    }
10588                }
10589            }
10590        }
10591
10592        private boolean isProtectedAction(ActivityIntentInfo filter) {
10593            final Iterator<String> actionsIter = filter.actionsIterator();
10594            while (actionsIter != null && actionsIter.hasNext()) {
10595                final String filterAction = actionsIter.next();
10596                if (PROTECTED_ACTIONS.contains(filterAction)) {
10597                    return true;
10598                }
10599            }
10600            return false;
10601        }
10602
10603        /**
10604         * Adjusts the priority of the given intent filter according to policy.
10605         * <p>
10606         * <ul>
10607         * <li>The priority for non privileged applications is capped to '0'</li>
10608         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10609         * <li>The priority for unbundled updates to privileged applications is capped to the
10610         *      priority defined on the system partition</li>
10611         * </ul>
10612         * <p>
10613         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10614         * allowed to obtain any priority on any action.
10615         */
10616        private void adjustPriority(
10617                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10618            // nothing to do; priority is fine as-is
10619            if (intent.getPriority() <= 0) {
10620                return;
10621            }
10622
10623            final ActivityInfo activityInfo = intent.activity.info;
10624            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10625
10626            final boolean privilegedApp =
10627                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10628            if (!privilegedApp) {
10629                // non-privileged applications can never define a priority >0
10630                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10631                        + " package: " + applicationInfo.packageName
10632                        + " activity: " + intent.activity.className
10633                        + " origPrio: " + intent.getPriority());
10634                intent.setPriority(0);
10635                return;
10636            }
10637
10638            if (systemActivities == null) {
10639                // the system package is not disabled; we're parsing the system partition
10640                if (isProtectedAction(intent)) {
10641                    if (mDeferProtectedFilters) {
10642                        // We can't deal with these just yet. No component should ever obtain a
10643                        // >0 priority for a protected actions, with ONE exception -- the setup
10644                        // wizard. The setup wizard, however, cannot be known until we're able to
10645                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10646                        // until all intent filters have been processed. Chicken, meet egg.
10647                        // Let the filter temporarily have a high priority and rectify the
10648                        // priorities after all system packages have been scanned.
10649                        mProtectedFilters.add(intent);
10650                        if (DEBUG_FILTERS) {
10651                            Slog.i(TAG, "Protected action; save for later;"
10652                                    + " package: " + applicationInfo.packageName
10653                                    + " activity: " + intent.activity.className
10654                                    + " origPrio: " + intent.getPriority());
10655                        }
10656                        return;
10657                    } else {
10658                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10659                            Slog.i(TAG, "No setup wizard;"
10660                                + " All protected intents capped to priority 0");
10661                        }
10662                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10663                            if (DEBUG_FILTERS) {
10664                                Slog.i(TAG, "Found setup wizard;"
10665                                    + " allow priority " + intent.getPriority() + ";"
10666                                    + " package: " + intent.activity.info.packageName
10667                                    + " activity: " + intent.activity.className
10668                                    + " priority: " + intent.getPriority());
10669                            }
10670                            // setup wizard gets whatever it wants
10671                            return;
10672                        }
10673                        Slog.w(TAG, "Protected action; cap priority to 0;"
10674                                + " package: " + intent.activity.info.packageName
10675                                + " activity: " + intent.activity.className
10676                                + " origPrio: " + intent.getPriority());
10677                        intent.setPriority(0);
10678                        return;
10679                    }
10680                }
10681                // privileged apps on the system image get whatever priority they request
10682                return;
10683            }
10684
10685            // privileged app unbundled update ... try to find the same activity
10686            final PackageParser.Activity foundActivity =
10687                    findMatchingActivity(systemActivities, activityInfo);
10688            if (foundActivity == null) {
10689                // this is a new activity; it cannot obtain >0 priority
10690                if (DEBUG_FILTERS) {
10691                    Slog.i(TAG, "New activity; cap priority to 0;"
10692                            + " package: " + applicationInfo.packageName
10693                            + " activity: " + intent.activity.className
10694                            + " origPrio: " + intent.getPriority());
10695                }
10696                intent.setPriority(0);
10697                return;
10698            }
10699
10700            // found activity, now check for filter equivalence
10701
10702            // a shallow copy is enough; we modify the list, not its contents
10703            final List<ActivityIntentInfo> intentListCopy =
10704                    new ArrayList<>(foundActivity.intents);
10705            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10706
10707            // find matching action subsets
10708            final Iterator<String> actionsIterator = intent.actionsIterator();
10709            if (actionsIterator != null) {
10710                getIntentListSubset(
10711                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10712                if (intentListCopy.size() == 0) {
10713                    // no more intents to match; we're not equivalent
10714                    if (DEBUG_FILTERS) {
10715                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10716                                + " package: " + applicationInfo.packageName
10717                                + " activity: " + intent.activity.className
10718                                + " origPrio: " + intent.getPriority());
10719                    }
10720                    intent.setPriority(0);
10721                    return;
10722                }
10723            }
10724
10725            // find matching category subsets
10726            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10727            if (categoriesIterator != null) {
10728                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10729                        categoriesIterator);
10730                if (intentListCopy.size() == 0) {
10731                    // no more intents to match; we're not equivalent
10732                    if (DEBUG_FILTERS) {
10733                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10734                                + " package: " + applicationInfo.packageName
10735                                + " activity: " + intent.activity.className
10736                                + " origPrio: " + intent.getPriority());
10737                    }
10738                    intent.setPriority(0);
10739                    return;
10740                }
10741            }
10742
10743            // find matching schemes subsets
10744            final Iterator<String> schemesIterator = intent.schemesIterator();
10745            if (schemesIterator != null) {
10746                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10747                        schemesIterator);
10748                if (intentListCopy.size() == 0) {
10749                    // no more intents to match; we're not equivalent
10750                    if (DEBUG_FILTERS) {
10751                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10752                                + " package: " + applicationInfo.packageName
10753                                + " activity: " + intent.activity.className
10754                                + " origPrio: " + intent.getPriority());
10755                    }
10756                    intent.setPriority(0);
10757                    return;
10758                }
10759            }
10760
10761            // find matching authorities subsets
10762            final Iterator<IntentFilter.AuthorityEntry>
10763                    authoritiesIterator = intent.authoritiesIterator();
10764            if (authoritiesIterator != null) {
10765                getIntentListSubset(intentListCopy,
10766                        new AuthoritiesIterGenerator(),
10767                        authoritiesIterator);
10768                if (intentListCopy.size() == 0) {
10769                    // no more intents to match; we're not equivalent
10770                    if (DEBUG_FILTERS) {
10771                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10772                                + " package: " + applicationInfo.packageName
10773                                + " activity: " + intent.activity.className
10774                                + " origPrio: " + intent.getPriority());
10775                    }
10776                    intent.setPriority(0);
10777                    return;
10778                }
10779            }
10780
10781            // we found matching filter(s); app gets the max priority of all intents
10782            int cappedPriority = 0;
10783            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10784                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10785            }
10786            if (intent.getPriority() > cappedPriority) {
10787                if (DEBUG_FILTERS) {
10788                    Slog.i(TAG, "Found matching filter(s);"
10789                            + " cap priority to " + cappedPriority + ";"
10790                            + " package: " + applicationInfo.packageName
10791                            + " activity: " + intent.activity.className
10792                            + " origPrio: " + intent.getPriority());
10793                }
10794                intent.setPriority(cappedPriority);
10795                return;
10796            }
10797            // all this for nothing; the requested priority was <= what was on the system
10798        }
10799
10800        public final void addActivity(PackageParser.Activity a, String type) {
10801            mActivities.put(a.getComponentName(), a);
10802            if (DEBUG_SHOW_INFO)
10803                Log.v(
10804                TAG, "  " + type + " " +
10805                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10806            if (DEBUG_SHOW_INFO)
10807                Log.v(TAG, "    Class=" + a.info.name);
10808            final int NI = a.intents.size();
10809            for (int j=0; j<NI; j++) {
10810                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10811                if ("activity".equals(type)) {
10812                    final PackageSetting ps =
10813                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10814                    final List<PackageParser.Activity> systemActivities =
10815                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10816                    adjustPriority(systemActivities, intent);
10817                }
10818                if (DEBUG_SHOW_INFO) {
10819                    Log.v(TAG, "    IntentFilter:");
10820                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10821                }
10822                if (!intent.debugCheck()) {
10823                    Log.w(TAG, "==> For Activity " + a.info.name);
10824                }
10825                addFilter(intent);
10826            }
10827        }
10828
10829        public final void removeActivity(PackageParser.Activity a, String type) {
10830            mActivities.remove(a.getComponentName());
10831            if (DEBUG_SHOW_INFO) {
10832                Log.v(TAG, "  " + type + " "
10833                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10834                                : a.info.name) + ":");
10835                Log.v(TAG, "    Class=" + a.info.name);
10836            }
10837            final int NI = a.intents.size();
10838            for (int j=0; j<NI; j++) {
10839                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10840                if (DEBUG_SHOW_INFO) {
10841                    Log.v(TAG, "    IntentFilter:");
10842                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10843                }
10844                removeFilter(intent);
10845            }
10846        }
10847
10848        @Override
10849        protected boolean allowFilterResult(
10850                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10851            ActivityInfo filterAi = filter.activity.info;
10852            for (int i=dest.size()-1; i>=0; i--) {
10853                ActivityInfo destAi = dest.get(i).activityInfo;
10854                if (destAi.name == filterAi.name
10855                        && destAi.packageName == filterAi.packageName) {
10856                    return false;
10857                }
10858            }
10859            return true;
10860        }
10861
10862        @Override
10863        protected ActivityIntentInfo[] newArray(int size) {
10864            return new ActivityIntentInfo[size];
10865        }
10866
10867        @Override
10868        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10869            if (!sUserManager.exists(userId)) return true;
10870            PackageParser.Package p = filter.activity.owner;
10871            if (p != null) {
10872                PackageSetting ps = (PackageSetting)p.mExtras;
10873                if (ps != null) {
10874                    // System apps are never considered stopped for purposes of
10875                    // filtering, because there may be no way for the user to
10876                    // actually re-launch them.
10877                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10878                            && ps.getStopped(userId);
10879                }
10880            }
10881            return false;
10882        }
10883
10884        @Override
10885        protected boolean isPackageForFilter(String packageName,
10886                PackageParser.ActivityIntentInfo info) {
10887            return packageName.equals(info.activity.owner.packageName);
10888        }
10889
10890        @Override
10891        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10892                int match, int userId) {
10893            if (!sUserManager.exists(userId)) return null;
10894            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10895                return null;
10896            }
10897            final PackageParser.Activity activity = info.activity;
10898            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10899            if (ps == null) {
10900                return null;
10901            }
10902            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10903                    ps.readUserState(userId), userId);
10904            if (ai == null) {
10905                return null;
10906            }
10907            final ResolveInfo res = new ResolveInfo();
10908            res.activityInfo = ai;
10909            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10910                res.filter = info;
10911            }
10912            if (info != null) {
10913                res.handleAllWebDataURI = info.handleAllWebDataURI();
10914            }
10915            res.priority = info.getPriority();
10916            res.preferredOrder = activity.owner.mPreferredOrder;
10917            //System.out.println("Result: " + res.activityInfo.className +
10918            //                   " = " + res.priority);
10919            res.match = match;
10920            res.isDefault = info.hasDefault;
10921            res.labelRes = info.labelRes;
10922            res.nonLocalizedLabel = info.nonLocalizedLabel;
10923            if (userNeedsBadging(userId)) {
10924                res.noResourceId = true;
10925            } else {
10926                res.icon = info.icon;
10927            }
10928            res.iconResourceId = info.icon;
10929            res.system = res.activityInfo.applicationInfo.isSystemApp();
10930            return res;
10931        }
10932
10933        @Override
10934        protected void sortResults(List<ResolveInfo> results) {
10935            Collections.sort(results, mResolvePrioritySorter);
10936        }
10937
10938        @Override
10939        protected void dumpFilter(PrintWriter out, String prefix,
10940                PackageParser.ActivityIntentInfo filter) {
10941            out.print(prefix); out.print(
10942                    Integer.toHexString(System.identityHashCode(filter.activity)));
10943                    out.print(' ');
10944                    filter.activity.printComponentShortName(out);
10945                    out.print(" filter ");
10946                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10947        }
10948
10949        @Override
10950        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10951            return filter.activity;
10952        }
10953
10954        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10955            PackageParser.Activity activity = (PackageParser.Activity)label;
10956            out.print(prefix); out.print(
10957                    Integer.toHexString(System.identityHashCode(activity)));
10958                    out.print(' ');
10959                    activity.printComponentShortName(out);
10960            if (count > 1) {
10961                out.print(" ("); out.print(count); out.print(" filters)");
10962            }
10963            out.println();
10964        }
10965
10966        // Keys are String (activity class name), values are Activity.
10967        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10968                = new ArrayMap<ComponentName, PackageParser.Activity>();
10969        private int mFlags;
10970    }
10971
10972    private final class ServiceIntentResolver
10973            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10974        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10975                boolean defaultOnly, int userId) {
10976            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10977            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10978        }
10979
10980        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10981                int userId) {
10982            if (!sUserManager.exists(userId)) return null;
10983            mFlags = flags;
10984            return super.queryIntent(intent, resolvedType,
10985                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10986        }
10987
10988        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10989                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10990            if (!sUserManager.exists(userId)) return null;
10991            if (packageServices == null) {
10992                return null;
10993            }
10994            mFlags = flags;
10995            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10996            final int N = packageServices.size();
10997            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10998                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10999
11000            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
11001            for (int i = 0; i < N; ++i) {
11002                intentFilters = packageServices.get(i).intents;
11003                if (intentFilters != null && intentFilters.size() > 0) {
11004                    PackageParser.ServiceIntentInfo[] array =
11005                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
11006                    intentFilters.toArray(array);
11007                    listCut.add(array);
11008                }
11009            }
11010            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11011        }
11012
11013        public final void addService(PackageParser.Service s) {
11014            mServices.put(s.getComponentName(), s);
11015            if (DEBUG_SHOW_INFO) {
11016                Log.v(TAG, "  "
11017                        + (s.info.nonLocalizedLabel != null
11018                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11019                Log.v(TAG, "    Class=" + s.info.name);
11020            }
11021            final int NI = s.intents.size();
11022            int j;
11023            for (j=0; j<NI; j++) {
11024                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11025                if (DEBUG_SHOW_INFO) {
11026                    Log.v(TAG, "    IntentFilter:");
11027                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11028                }
11029                if (!intent.debugCheck()) {
11030                    Log.w(TAG, "==> For Service " + s.info.name);
11031                }
11032                addFilter(intent);
11033            }
11034        }
11035
11036        public final void removeService(PackageParser.Service s) {
11037            mServices.remove(s.getComponentName());
11038            if (DEBUG_SHOW_INFO) {
11039                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
11040                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11041                Log.v(TAG, "    Class=" + s.info.name);
11042            }
11043            final int NI = s.intents.size();
11044            int j;
11045            for (j=0; j<NI; j++) {
11046                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11047                if (DEBUG_SHOW_INFO) {
11048                    Log.v(TAG, "    IntentFilter:");
11049                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11050                }
11051                removeFilter(intent);
11052            }
11053        }
11054
11055        @Override
11056        protected boolean allowFilterResult(
11057                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11058            ServiceInfo filterSi = filter.service.info;
11059            for (int i=dest.size()-1; i>=0; i--) {
11060                ServiceInfo destAi = dest.get(i).serviceInfo;
11061                if (destAi.name == filterSi.name
11062                        && destAi.packageName == filterSi.packageName) {
11063                    return false;
11064                }
11065            }
11066            return true;
11067        }
11068
11069        @Override
11070        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11071            return new PackageParser.ServiceIntentInfo[size];
11072        }
11073
11074        @Override
11075        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11076            if (!sUserManager.exists(userId)) return true;
11077            PackageParser.Package p = filter.service.owner;
11078            if (p != null) {
11079                PackageSetting ps = (PackageSetting)p.mExtras;
11080                if (ps != null) {
11081                    // System apps are never considered stopped for purposes of
11082                    // filtering, because there may be no way for the user to
11083                    // actually re-launch them.
11084                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11085                            && ps.getStopped(userId);
11086                }
11087            }
11088            return false;
11089        }
11090
11091        @Override
11092        protected boolean isPackageForFilter(String packageName,
11093                PackageParser.ServiceIntentInfo info) {
11094            return packageName.equals(info.service.owner.packageName);
11095        }
11096
11097        @Override
11098        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11099                int match, int userId) {
11100            if (!sUserManager.exists(userId)) return null;
11101            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11102            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11103                return null;
11104            }
11105            final PackageParser.Service service = info.service;
11106            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11107            if (ps == null) {
11108                return null;
11109            }
11110            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11111                    ps.readUserState(userId), userId);
11112            if (si == null) {
11113                return null;
11114            }
11115            final ResolveInfo res = new ResolveInfo();
11116            res.serviceInfo = si;
11117            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11118                res.filter = filter;
11119            }
11120            res.priority = info.getPriority();
11121            res.preferredOrder = service.owner.mPreferredOrder;
11122            res.match = match;
11123            res.isDefault = info.hasDefault;
11124            res.labelRes = info.labelRes;
11125            res.nonLocalizedLabel = info.nonLocalizedLabel;
11126            res.icon = info.icon;
11127            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11128            return res;
11129        }
11130
11131        @Override
11132        protected void sortResults(List<ResolveInfo> results) {
11133            Collections.sort(results, mResolvePrioritySorter);
11134        }
11135
11136        @Override
11137        protected void dumpFilter(PrintWriter out, String prefix,
11138                PackageParser.ServiceIntentInfo filter) {
11139            out.print(prefix); out.print(
11140                    Integer.toHexString(System.identityHashCode(filter.service)));
11141                    out.print(' ');
11142                    filter.service.printComponentShortName(out);
11143                    out.print(" filter ");
11144                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11145        }
11146
11147        @Override
11148        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11149            return filter.service;
11150        }
11151
11152        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11153            PackageParser.Service service = (PackageParser.Service)label;
11154            out.print(prefix); out.print(
11155                    Integer.toHexString(System.identityHashCode(service)));
11156                    out.print(' ');
11157                    service.printComponentShortName(out);
11158            if (count > 1) {
11159                out.print(" ("); out.print(count); out.print(" filters)");
11160            }
11161            out.println();
11162        }
11163
11164//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11165//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11166//            final List<ResolveInfo> retList = Lists.newArrayList();
11167//            while (i.hasNext()) {
11168//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11169//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11170//                    retList.add(resolveInfo);
11171//                }
11172//            }
11173//            return retList;
11174//        }
11175
11176        // Keys are String (activity class name), values are Activity.
11177        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11178                = new ArrayMap<ComponentName, PackageParser.Service>();
11179        private int mFlags;
11180    };
11181
11182    private final class ProviderIntentResolver
11183            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11184        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11185                boolean defaultOnly, int userId) {
11186            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11187            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11188        }
11189
11190        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11191                int userId) {
11192            if (!sUserManager.exists(userId))
11193                return null;
11194            mFlags = flags;
11195            return super.queryIntent(intent, resolvedType,
11196                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11197        }
11198
11199        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11200                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11201            if (!sUserManager.exists(userId))
11202                return null;
11203            if (packageProviders == null) {
11204                return null;
11205            }
11206            mFlags = flags;
11207            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11208            final int N = packageProviders.size();
11209            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11210                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11211
11212            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11213            for (int i = 0; i < N; ++i) {
11214                intentFilters = packageProviders.get(i).intents;
11215                if (intentFilters != null && intentFilters.size() > 0) {
11216                    PackageParser.ProviderIntentInfo[] array =
11217                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11218                    intentFilters.toArray(array);
11219                    listCut.add(array);
11220                }
11221            }
11222            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11223        }
11224
11225        public final void addProvider(PackageParser.Provider p) {
11226            if (mProviders.containsKey(p.getComponentName())) {
11227                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11228                return;
11229            }
11230
11231            mProviders.put(p.getComponentName(), p);
11232            if (DEBUG_SHOW_INFO) {
11233                Log.v(TAG, "  "
11234                        + (p.info.nonLocalizedLabel != null
11235                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11236                Log.v(TAG, "    Class=" + p.info.name);
11237            }
11238            final int NI = p.intents.size();
11239            int j;
11240            for (j = 0; j < NI; j++) {
11241                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11242                if (DEBUG_SHOW_INFO) {
11243                    Log.v(TAG, "    IntentFilter:");
11244                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11245                }
11246                if (!intent.debugCheck()) {
11247                    Log.w(TAG, "==> For Provider " + p.info.name);
11248                }
11249                addFilter(intent);
11250            }
11251        }
11252
11253        public final void removeProvider(PackageParser.Provider p) {
11254            mProviders.remove(p.getComponentName());
11255            if (DEBUG_SHOW_INFO) {
11256                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11257                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11258                Log.v(TAG, "    Class=" + p.info.name);
11259            }
11260            final int NI = p.intents.size();
11261            int j;
11262            for (j = 0; j < NI; j++) {
11263                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11264                if (DEBUG_SHOW_INFO) {
11265                    Log.v(TAG, "    IntentFilter:");
11266                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11267                }
11268                removeFilter(intent);
11269            }
11270        }
11271
11272        @Override
11273        protected boolean allowFilterResult(
11274                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11275            ProviderInfo filterPi = filter.provider.info;
11276            for (int i = dest.size() - 1; i >= 0; i--) {
11277                ProviderInfo destPi = dest.get(i).providerInfo;
11278                if (destPi.name == filterPi.name
11279                        && destPi.packageName == filterPi.packageName) {
11280                    return false;
11281                }
11282            }
11283            return true;
11284        }
11285
11286        @Override
11287        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11288            return new PackageParser.ProviderIntentInfo[size];
11289        }
11290
11291        @Override
11292        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11293            if (!sUserManager.exists(userId))
11294                return true;
11295            PackageParser.Package p = filter.provider.owner;
11296            if (p != null) {
11297                PackageSetting ps = (PackageSetting) p.mExtras;
11298                if (ps != null) {
11299                    // System apps are never considered stopped for purposes of
11300                    // filtering, because there may be no way for the user to
11301                    // actually re-launch them.
11302                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11303                            && ps.getStopped(userId);
11304                }
11305            }
11306            return false;
11307        }
11308
11309        @Override
11310        protected boolean isPackageForFilter(String packageName,
11311                PackageParser.ProviderIntentInfo info) {
11312            return packageName.equals(info.provider.owner.packageName);
11313        }
11314
11315        @Override
11316        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11317                int match, int userId) {
11318            if (!sUserManager.exists(userId))
11319                return null;
11320            final PackageParser.ProviderIntentInfo info = filter;
11321            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11322                return null;
11323            }
11324            final PackageParser.Provider provider = info.provider;
11325            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11326            if (ps == null) {
11327                return null;
11328            }
11329            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11330                    ps.readUserState(userId), userId);
11331            if (pi == null) {
11332                return null;
11333            }
11334            final ResolveInfo res = new ResolveInfo();
11335            res.providerInfo = pi;
11336            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11337                res.filter = filter;
11338            }
11339            res.priority = info.getPriority();
11340            res.preferredOrder = provider.owner.mPreferredOrder;
11341            res.match = match;
11342            res.isDefault = info.hasDefault;
11343            res.labelRes = info.labelRes;
11344            res.nonLocalizedLabel = info.nonLocalizedLabel;
11345            res.icon = info.icon;
11346            res.system = res.providerInfo.applicationInfo.isSystemApp();
11347            return res;
11348        }
11349
11350        @Override
11351        protected void sortResults(List<ResolveInfo> results) {
11352            Collections.sort(results, mResolvePrioritySorter);
11353        }
11354
11355        @Override
11356        protected void dumpFilter(PrintWriter out, String prefix,
11357                PackageParser.ProviderIntentInfo filter) {
11358            out.print(prefix);
11359            out.print(
11360                    Integer.toHexString(System.identityHashCode(filter.provider)));
11361            out.print(' ');
11362            filter.provider.printComponentShortName(out);
11363            out.print(" filter ");
11364            out.println(Integer.toHexString(System.identityHashCode(filter)));
11365        }
11366
11367        @Override
11368        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11369            return filter.provider;
11370        }
11371
11372        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11373            PackageParser.Provider provider = (PackageParser.Provider)label;
11374            out.print(prefix); out.print(
11375                    Integer.toHexString(System.identityHashCode(provider)));
11376                    out.print(' ');
11377                    provider.printComponentShortName(out);
11378            if (count > 1) {
11379                out.print(" ("); out.print(count); out.print(" filters)");
11380            }
11381            out.println();
11382        }
11383
11384        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11385                = new ArrayMap<ComponentName, PackageParser.Provider>();
11386        private int mFlags;
11387    }
11388
11389    private static final class EphemeralIntentResolver
11390            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11391        /**
11392         * The result that has the highest defined order. Ordering applies on a
11393         * per-package basis. Mapping is from package name to Pair of order and
11394         * EphemeralResolveInfo.
11395         * <p>
11396         * NOTE: This is implemented as a field variable for convenience and efficiency.
11397         * By having a field variable, we're able to track filter ordering as soon as
11398         * a non-zero order is defined. Otherwise, multiple loops across the result set
11399         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11400         * this needs to be contained entirely within {@link #filterResults()}.
11401         */
11402        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11403
11404        @Override
11405        protected EphemeralResolveIntentInfo[] newArray(int size) {
11406            return new EphemeralResolveIntentInfo[size];
11407        }
11408
11409        @Override
11410        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11411            return true;
11412        }
11413
11414        @Override
11415        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11416                int userId) {
11417            if (!sUserManager.exists(userId)) {
11418                return null;
11419            }
11420            final String packageName = info.getEphemeralResolveInfo().getPackageName();
11421            final Integer order = info.getOrder();
11422            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11423                    mOrderResult.get(packageName);
11424            // ordering is enabled and this item's order isn't high enough
11425            if (lastOrderResult != null && lastOrderResult.first >= order) {
11426                return null;
11427            }
11428            final EphemeralResolveInfo res = info.getEphemeralResolveInfo();
11429            if (order > 0) {
11430                // non-zero order, enable ordering
11431                mOrderResult.put(packageName, new Pair<>(order, res));
11432            }
11433            return res;
11434        }
11435
11436        @Override
11437        protected void filterResults(List<EphemeralResolveInfo> results) {
11438            // only do work if ordering is enabled [most of the time it won't be]
11439            if (mOrderResult.size() == 0) {
11440                return;
11441            }
11442            int resultSize = results.size();
11443            for (int i = 0; i < resultSize; i++) {
11444                final EphemeralResolveInfo info = results.get(i);
11445                final String packageName = info.getPackageName();
11446                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11447                if (savedInfo == null) {
11448                    // package doesn't having ordering
11449                    continue;
11450                }
11451                if (savedInfo.second == info) {
11452                    // circled back to the highest ordered item; remove from order list
11453                    mOrderResult.remove(savedInfo);
11454                    if (mOrderResult.size() == 0) {
11455                        // no more ordered items
11456                        break;
11457                    }
11458                    continue;
11459                }
11460                // item has a worse order, remove it from the result list
11461                results.remove(i);
11462                resultSize--;
11463                i--;
11464            }
11465        }
11466    }
11467
11468    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11469            new Comparator<ResolveInfo>() {
11470        public int compare(ResolveInfo r1, ResolveInfo r2) {
11471            int v1 = r1.priority;
11472            int v2 = r2.priority;
11473            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11474            if (v1 != v2) {
11475                return (v1 > v2) ? -1 : 1;
11476            }
11477            v1 = r1.preferredOrder;
11478            v2 = r2.preferredOrder;
11479            if (v1 != v2) {
11480                return (v1 > v2) ? -1 : 1;
11481            }
11482            if (r1.isDefault != r2.isDefault) {
11483                return r1.isDefault ? -1 : 1;
11484            }
11485            v1 = r1.match;
11486            v2 = r2.match;
11487            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11488            if (v1 != v2) {
11489                return (v1 > v2) ? -1 : 1;
11490            }
11491            if (r1.system != r2.system) {
11492                return r1.system ? -1 : 1;
11493            }
11494            if (r1.activityInfo != null) {
11495                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11496            }
11497            if (r1.serviceInfo != null) {
11498                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11499            }
11500            if (r1.providerInfo != null) {
11501                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11502            }
11503            return 0;
11504        }
11505    };
11506
11507    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11508            new Comparator<ProviderInfo>() {
11509        public int compare(ProviderInfo p1, ProviderInfo p2) {
11510            final int v1 = p1.initOrder;
11511            final int v2 = p2.initOrder;
11512            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11513        }
11514    };
11515
11516    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11517            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11518            final int[] userIds) {
11519        mHandler.post(new Runnable() {
11520            @Override
11521            public void run() {
11522                try {
11523                    final IActivityManager am = ActivityManagerNative.getDefault();
11524                    if (am == null) return;
11525                    final int[] resolvedUserIds;
11526                    if (userIds == null) {
11527                        resolvedUserIds = am.getRunningUserIds();
11528                    } else {
11529                        resolvedUserIds = userIds;
11530                    }
11531                    for (int id : resolvedUserIds) {
11532                        final Intent intent = new Intent(action,
11533                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11534                        if (extras != null) {
11535                            intent.putExtras(extras);
11536                        }
11537                        if (targetPkg != null) {
11538                            intent.setPackage(targetPkg);
11539                        }
11540                        // Modify the UID when posting to other users
11541                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11542                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11543                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11544                            intent.putExtra(Intent.EXTRA_UID, uid);
11545                        }
11546                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11547                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11548                        if (DEBUG_BROADCASTS) {
11549                            RuntimeException here = new RuntimeException("here");
11550                            here.fillInStackTrace();
11551                            Slog.d(TAG, "Sending to user " + id + ": "
11552                                    + intent.toShortString(false, true, false, false)
11553                                    + " " + intent.getExtras(), here);
11554                        }
11555                        am.broadcastIntent(null, intent, null, finishedReceiver,
11556                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11557                                null, finishedReceiver != null, false, id);
11558                    }
11559                } catch (RemoteException ex) {
11560                }
11561            }
11562        });
11563    }
11564
11565    /**
11566     * Check if the external storage media is available. This is true if there
11567     * is a mounted external storage medium or if the external storage is
11568     * emulated.
11569     */
11570    private boolean isExternalMediaAvailable() {
11571        return mMediaMounted || Environment.isExternalStorageEmulated();
11572    }
11573
11574    @Override
11575    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11576        // writer
11577        synchronized (mPackages) {
11578            if (!isExternalMediaAvailable()) {
11579                // If the external storage is no longer mounted at this point,
11580                // the caller may not have been able to delete all of this
11581                // packages files and can not delete any more.  Bail.
11582                return null;
11583            }
11584            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11585            if (lastPackage != null) {
11586                pkgs.remove(lastPackage);
11587            }
11588            if (pkgs.size() > 0) {
11589                return pkgs.get(0);
11590            }
11591        }
11592        return null;
11593    }
11594
11595    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11596        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11597                userId, andCode ? 1 : 0, packageName);
11598        if (mSystemReady) {
11599            msg.sendToTarget();
11600        } else {
11601            if (mPostSystemReadyMessages == null) {
11602                mPostSystemReadyMessages = new ArrayList<>();
11603            }
11604            mPostSystemReadyMessages.add(msg);
11605        }
11606    }
11607
11608    void startCleaningPackages() {
11609        // reader
11610        if (!isExternalMediaAvailable()) {
11611            return;
11612        }
11613        synchronized (mPackages) {
11614            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11615                return;
11616            }
11617        }
11618        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11619        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11620        IActivityManager am = ActivityManagerNative.getDefault();
11621        if (am != null) {
11622            try {
11623                am.startService(null, intent, null, mContext.getOpPackageName(),
11624                        UserHandle.USER_SYSTEM);
11625            } catch (RemoteException e) {
11626            }
11627        }
11628    }
11629
11630    @Override
11631    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11632            int installFlags, String installerPackageName, int userId) {
11633        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11634
11635        final int callingUid = Binder.getCallingUid();
11636        enforceCrossUserPermission(callingUid, userId,
11637                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11638
11639        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11640            try {
11641                if (observer != null) {
11642                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11643                }
11644            } catch (RemoteException re) {
11645            }
11646            return;
11647        }
11648
11649        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11650            installFlags |= PackageManager.INSTALL_FROM_ADB;
11651
11652        } else {
11653            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11654            // about installerPackageName.
11655
11656            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11657            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11658        }
11659
11660        UserHandle user;
11661        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11662            user = UserHandle.ALL;
11663        } else {
11664            user = new UserHandle(userId);
11665        }
11666
11667        // Only system components can circumvent runtime permissions when installing.
11668        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11669                && mContext.checkCallingOrSelfPermission(Manifest.permission
11670                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11671            throw new SecurityException("You need the "
11672                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11673                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11674        }
11675
11676        final File originFile = new File(originPath);
11677        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11678
11679        final Message msg = mHandler.obtainMessage(INIT_COPY);
11680        final VerificationInfo verificationInfo = new VerificationInfo(
11681                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11682        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11683                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11684                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11685                null /*certificates*/);
11686        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11687        msg.obj = params;
11688
11689        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11690                System.identityHashCode(msg.obj));
11691        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11692                System.identityHashCode(msg.obj));
11693
11694        mHandler.sendMessage(msg);
11695    }
11696
11697    void installStage(String packageName, File stagedDir, String stagedCid,
11698            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11699            String installerPackageName, int installerUid, UserHandle user,
11700            Certificate[][] certificates) {
11701        if (DEBUG_EPHEMERAL) {
11702            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11703                Slog.d(TAG, "Ephemeral install of " + packageName);
11704            }
11705        }
11706        final VerificationInfo verificationInfo = new VerificationInfo(
11707                sessionParams.originatingUri, sessionParams.referrerUri,
11708                sessionParams.originatingUid, installerUid);
11709
11710        final OriginInfo origin;
11711        if (stagedDir != null) {
11712            origin = OriginInfo.fromStagedFile(stagedDir);
11713        } else {
11714            origin = OriginInfo.fromStagedContainer(stagedCid);
11715        }
11716
11717        final Message msg = mHandler.obtainMessage(INIT_COPY);
11718        final InstallParams params = new InstallParams(origin, null, observer,
11719                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11720                verificationInfo, user, sessionParams.abiOverride,
11721                sessionParams.grantedRuntimePermissions, certificates);
11722        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11723        msg.obj = params;
11724
11725        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11726                System.identityHashCode(msg.obj));
11727        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11728                System.identityHashCode(msg.obj));
11729
11730        mHandler.sendMessage(msg);
11731    }
11732
11733    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11734            int userId) {
11735        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11736        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11737    }
11738
11739    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11740            int appId, int userId) {
11741        Bundle extras = new Bundle(1);
11742        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11743
11744        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11745                packageName, extras, 0, null, null, new int[] {userId});
11746        try {
11747            IActivityManager am = ActivityManagerNative.getDefault();
11748            if (isSystem && am.isUserRunning(userId, 0)) {
11749                // The just-installed/enabled app is bundled on the system, so presumed
11750                // to be able to run automatically without needing an explicit launch.
11751                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11752                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11753                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11754                        .setPackage(packageName);
11755                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11756                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11757            }
11758        } catch (RemoteException e) {
11759            // shouldn't happen
11760            Slog.w(TAG, "Unable to bootstrap installed package", e);
11761        }
11762    }
11763
11764    @Override
11765    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11766            int userId) {
11767        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11768        PackageSetting pkgSetting;
11769        final int uid = Binder.getCallingUid();
11770        enforceCrossUserPermission(uid, userId,
11771                true /* requireFullPermission */, true /* checkShell */,
11772                "setApplicationHiddenSetting for user " + userId);
11773
11774        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11775            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11776            return false;
11777        }
11778
11779        long callingId = Binder.clearCallingIdentity();
11780        try {
11781            boolean sendAdded = false;
11782            boolean sendRemoved = false;
11783            // writer
11784            synchronized (mPackages) {
11785                pkgSetting = mSettings.mPackages.get(packageName);
11786                if (pkgSetting == null) {
11787                    return false;
11788                }
11789                // Do not allow "android" is being disabled
11790                if ("android".equals(packageName)) {
11791                    Slog.w(TAG, "Cannot hide package: android");
11792                    return false;
11793                }
11794                // Only allow protected packages to hide themselves.
11795                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11796                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11797                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11798                    return false;
11799                }
11800
11801                if (pkgSetting.getHidden(userId) != hidden) {
11802                    pkgSetting.setHidden(hidden, userId);
11803                    mSettings.writePackageRestrictionsLPr(userId);
11804                    if (hidden) {
11805                        sendRemoved = true;
11806                    } else {
11807                        sendAdded = true;
11808                    }
11809                }
11810            }
11811            if (sendAdded) {
11812                sendPackageAddedForUser(packageName, pkgSetting, userId);
11813                return true;
11814            }
11815            if (sendRemoved) {
11816                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11817                        "hiding pkg");
11818                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11819                return true;
11820            }
11821        } finally {
11822            Binder.restoreCallingIdentity(callingId);
11823        }
11824        return false;
11825    }
11826
11827    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11828            int userId) {
11829        final PackageRemovedInfo info = new PackageRemovedInfo();
11830        info.removedPackage = packageName;
11831        info.removedUsers = new int[] {userId};
11832        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11833        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11834    }
11835
11836    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11837        if (pkgList.length > 0) {
11838            Bundle extras = new Bundle(1);
11839            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11840
11841            sendPackageBroadcast(
11842                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11843                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11844                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11845                    new int[] {userId});
11846        }
11847    }
11848
11849    /**
11850     * Returns true if application is not found or there was an error. Otherwise it returns
11851     * the hidden state of the package for the given user.
11852     */
11853    @Override
11854    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11855        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11856        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11857                true /* requireFullPermission */, false /* checkShell */,
11858                "getApplicationHidden for user " + userId);
11859        PackageSetting pkgSetting;
11860        long callingId = Binder.clearCallingIdentity();
11861        try {
11862            // writer
11863            synchronized (mPackages) {
11864                pkgSetting = mSettings.mPackages.get(packageName);
11865                if (pkgSetting == null) {
11866                    return true;
11867                }
11868                return pkgSetting.getHidden(userId);
11869            }
11870        } finally {
11871            Binder.restoreCallingIdentity(callingId);
11872        }
11873    }
11874
11875    /**
11876     * @hide
11877     */
11878    @Override
11879    public int installExistingPackageAsUser(String packageName, int userId) {
11880        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11881                null);
11882        PackageSetting pkgSetting;
11883        final int uid = Binder.getCallingUid();
11884        enforceCrossUserPermission(uid, userId,
11885                true /* requireFullPermission */, true /* checkShell */,
11886                "installExistingPackage for user " + userId);
11887        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11888            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11889        }
11890
11891        long callingId = Binder.clearCallingIdentity();
11892        try {
11893            boolean installed = false;
11894
11895            // writer
11896            synchronized (mPackages) {
11897                pkgSetting = mSettings.mPackages.get(packageName);
11898                if (pkgSetting == null) {
11899                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11900                }
11901                if (!pkgSetting.getInstalled(userId)) {
11902                    pkgSetting.setInstalled(true, userId);
11903                    pkgSetting.setHidden(false, userId);
11904                    mSettings.writePackageRestrictionsLPr(userId);
11905                    installed = true;
11906                }
11907            }
11908
11909            if (installed) {
11910                if (pkgSetting.pkg != null) {
11911                    synchronized (mInstallLock) {
11912                        // We don't need to freeze for a brand new install
11913                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11914                    }
11915                }
11916                sendPackageAddedForUser(packageName, pkgSetting, userId);
11917            }
11918        } finally {
11919            Binder.restoreCallingIdentity(callingId);
11920        }
11921
11922        return PackageManager.INSTALL_SUCCEEDED;
11923    }
11924
11925    boolean isUserRestricted(int userId, String restrictionKey) {
11926        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11927        if (restrictions.getBoolean(restrictionKey, false)) {
11928            Log.w(TAG, "User is restricted: " + restrictionKey);
11929            return true;
11930        }
11931        return false;
11932    }
11933
11934    @Override
11935    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11936            int userId) {
11937        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11938        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11939                true /* requireFullPermission */, true /* checkShell */,
11940                "setPackagesSuspended for user " + userId);
11941
11942        if (ArrayUtils.isEmpty(packageNames)) {
11943            return packageNames;
11944        }
11945
11946        // List of package names for whom the suspended state has changed.
11947        List<String> changedPackages = new ArrayList<>(packageNames.length);
11948        // List of package names for whom the suspended state is not set as requested in this
11949        // method.
11950        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11951        long callingId = Binder.clearCallingIdentity();
11952        try {
11953            for (int i = 0; i < packageNames.length; i++) {
11954                String packageName = packageNames[i];
11955                boolean changed = false;
11956                final int appId;
11957                synchronized (mPackages) {
11958                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11959                    if (pkgSetting == null) {
11960                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11961                                + "\". Skipping suspending/un-suspending.");
11962                        unactionedPackages.add(packageName);
11963                        continue;
11964                    }
11965                    appId = pkgSetting.appId;
11966                    if (pkgSetting.getSuspended(userId) != suspended) {
11967                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11968                            unactionedPackages.add(packageName);
11969                            continue;
11970                        }
11971                        pkgSetting.setSuspended(suspended, userId);
11972                        mSettings.writePackageRestrictionsLPr(userId);
11973                        changed = true;
11974                        changedPackages.add(packageName);
11975                    }
11976                }
11977
11978                if (changed && suspended) {
11979                    killApplication(packageName, UserHandle.getUid(userId, appId),
11980                            "suspending package");
11981                }
11982            }
11983        } finally {
11984            Binder.restoreCallingIdentity(callingId);
11985        }
11986
11987        if (!changedPackages.isEmpty()) {
11988            sendPackagesSuspendedForUser(changedPackages.toArray(
11989                    new String[changedPackages.size()]), userId, suspended);
11990        }
11991
11992        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11993    }
11994
11995    @Override
11996    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11997        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11998                true /* requireFullPermission */, false /* checkShell */,
11999                "isPackageSuspendedForUser for user " + userId);
12000        synchronized (mPackages) {
12001            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12002            if (pkgSetting == null) {
12003                throw new IllegalArgumentException("Unknown target package: " + packageName);
12004            }
12005            return pkgSetting.getSuspended(userId);
12006        }
12007    }
12008
12009    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
12010        if (isPackageDeviceAdmin(packageName, userId)) {
12011            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12012                    + "\": has an active device admin");
12013            return false;
12014        }
12015
12016        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
12017        if (packageName.equals(activeLauncherPackageName)) {
12018            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12019                    + "\": contains the active launcher");
12020            return false;
12021        }
12022
12023        if (packageName.equals(mRequiredInstallerPackage)) {
12024            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12025                    + "\": required for package installation");
12026            return false;
12027        }
12028
12029        if (packageName.equals(mRequiredUninstallerPackage)) {
12030            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12031                    + "\": required for package uninstallation");
12032            return false;
12033        }
12034
12035        if (packageName.equals(mRequiredVerifierPackage)) {
12036            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12037                    + "\": required for package verification");
12038            return false;
12039        }
12040
12041        if (packageName.equals(getDefaultDialerPackageName(userId))) {
12042            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12043                    + "\": is the default dialer");
12044            return false;
12045        }
12046
12047        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12048            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12049                    + "\": protected package");
12050            return false;
12051        }
12052
12053        return true;
12054    }
12055
12056    private String getActiveLauncherPackageName(int userId) {
12057        Intent intent = new Intent(Intent.ACTION_MAIN);
12058        intent.addCategory(Intent.CATEGORY_HOME);
12059        ResolveInfo resolveInfo = resolveIntent(
12060                intent,
12061                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12062                PackageManager.MATCH_DEFAULT_ONLY,
12063                userId);
12064
12065        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12066    }
12067
12068    private String getDefaultDialerPackageName(int userId) {
12069        synchronized (mPackages) {
12070            return mSettings.getDefaultDialerPackageNameLPw(userId);
12071        }
12072    }
12073
12074    @Override
12075    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12076        mContext.enforceCallingOrSelfPermission(
12077                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12078                "Only package verification agents can verify applications");
12079
12080        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12081        final PackageVerificationResponse response = new PackageVerificationResponse(
12082                verificationCode, Binder.getCallingUid());
12083        msg.arg1 = id;
12084        msg.obj = response;
12085        mHandler.sendMessage(msg);
12086    }
12087
12088    @Override
12089    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12090            long millisecondsToDelay) {
12091        mContext.enforceCallingOrSelfPermission(
12092                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12093                "Only package verification agents can extend verification timeouts");
12094
12095        final PackageVerificationState state = mPendingVerification.get(id);
12096        final PackageVerificationResponse response = new PackageVerificationResponse(
12097                verificationCodeAtTimeout, Binder.getCallingUid());
12098
12099        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12100            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12101        }
12102        if (millisecondsToDelay < 0) {
12103            millisecondsToDelay = 0;
12104        }
12105        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12106                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12107            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12108        }
12109
12110        if ((state != null) && !state.timeoutExtended()) {
12111            state.extendTimeout();
12112
12113            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12114            msg.arg1 = id;
12115            msg.obj = response;
12116            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12117        }
12118    }
12119
12120    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12121            int verificationCode, UserHandle user) {
12122        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12123        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12124        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12125        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12126        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12127
12128        mContext.sendBroadcastAsUser(intent, user,
12129                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12130    }
12131
12132    private ComponentName matchComponentForVerifier(String packageName,
12133            List<ResolveInfo> receivers) {
12134        ActivityInfo targetReceiver = null;
12135
12136        final int NR = receivers.size();
12137        for (int i = 0; i < NR; i++) {
12138            final ResolveInfo info = receivers.get(i);
12139            if (info.activityInfo == null) {
12140                continue;
12141            }
12142
12143            if (packageName.equals(info.activityInfo.packageName)) {
12144                targetReceiver = info.activityInfo;
12145                break;
12146            }
12147        }
12148
12149        if (targetReceiver == null) {
12150            return null;
12151        }
12152
12153        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12154    }
12155
12156    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12157            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12158        if (pkgInfo.verifiers.length == 0) {
12159            return null;
12160        }
12161
12162        final int N = pkgInfo.verifiers.length;
12163        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12164        for (int i = 0; i < N; i++) {
12165            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12166
12167            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12168                    receivers);
12169            if (comp == null) {
12170                continue;
12171            }
12172
12173            final int verifierUid = getUidForVerifier(verifierInfo);
12174            if (verifierUid == -1) {
12175                continue;
12176            }
12177
12178            if (DEBUG_VERIFY) {
12179                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12180                        + " with the correct signature");
12181            }
12182            sufficientVerifiers.add(comp);
12183            verificationState.addSufficientVerifier(verifierUid);
12184        }
12185
12186        return sufficientVerifiers;
12187    }
12188
12189    private int getUidForVerifier(VerifierInfo verifierInfo) {
12190        synchronized (mPackages) {
12191            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12192            if (pkg == null) {
12193                return -1;
12194            } else if (pkg.mSignatures.length != 1) {
12195                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12196                        + " has more than one signature; ignoring");
12197                return -1;
12198            }
12199
12200            /*
12201             * If the public key of the package's signature does not match
12202             * our expected public key, then this is a different package and
12203             * we should skip.
12204             */
12205
12206            final byte[] expectedPublicKey;
12207            try {
12208                final Signature verifierSig = pkg.mSignatures[0];
12209                final PublicKey publicKey = verifierSig.getPublicKey();
12210                expectedPublicKey = publicKey.getEncoded();
12211            } catch (CertificateException e) {
12212                return -1;
12213            }
12214
12215            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12216
12217            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12218                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12219                        + " does not have the expected public key; ignoring");
12220                return -1;
12221            }
12222
12223            return pkg.applicationInfo.uid;
12224        }
12225    }
12226
12227    @Override
12228    public void finishPackageInstall(int token, boolean didLaunch) {
12229        enforceSystemOrRoot("Only the system is allowed to finish installs");
12230
12231        if (DEBUG_INSTALL) {
12232            Slog.v(TAG, "BM finishing package install for " + token);
12233        }
12234        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12235
12236        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12237        mHandler.sendMessage(msg);
12238    }
12239
12240    /**
12241     * Get the verification agent timeout.
12242     *
12243     * @return verification timeout in milliseconds
12244     */
12245    private long getVerificationTimeout() {
12246        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12247                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12248                DEFAULT_VERIFICATION_TIMEOUT);
12249    }
12250
12251    /**
12252     * Get the default verification agent response code.
12253     *
12254     * @return default verification response code
12255     */
12256    private int getDefaultVerificationResponse() {
12257        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12258                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12259                DEFAULT_VERIFICATION_RESPONSE);
12260    }
12261
12262    /**
12263     * Check whether or not package verification has been enabled.
12264     *
12265     * @return true if verification should be performed
12266     */
12267    private boolean isVerificationEnabled(int userId, int installFlags) {
12268        if (!DEFAULT_VERIFY_ENABLE) {
12269            return false;
12270        }
12271        // Ephemeral apps don't get the full verification treatment
12272        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12273            if (DEBUG_EPHEMERAL) {
12274                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12275            }
12276            return false;
12277        }
12278
12279        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12280
12281        // Check if installing from ADB
12282        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12283            // Do not run verification in a test harness environment
12284            if (ActivityManager.isRunningInTestHarness()) {
12285                return false;
12286            }
12287            if (ensureVerifyAppsEnabled) {
12288                return true;
12289            }
12290            // Check if the developer does not want package verification for ADB installs
12291            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12292                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12293                return false;
12294            }
12295        }
12296
12297        if (ensureVerifyAppsEnabled) {
12298            return true;
12299        }
12300
12301        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12302                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12303    }
12304
12305    @Override
12306    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12307            throws RemoteException {
12308        mContext.enforceCallingOrSelfPermission(
12309                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12310                "Only intentfilter verification agents can verify applications");
12311
12312        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12313        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12314                Binder.getCallingUid(), verificationCode, failedDomains);
12315        msg.arg1 = id;
12316        msg.obj = response;
12317        mHandler.sendMessage(msg);
12318    }
12319
12320    @Override
12321    public int getIntentVerificationStatus(String packageName, int userId) {
12322        synchronized (mPackages) {
12323            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12324        }
12325    }
12326
12327    @Override
12328    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12329        mContext.enforceCallingOrSelfPermission(
12330                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12331
12332        boolean result = false;
12333        synchronized (mPackages) {
12334            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12335        }
12336        if (result) {
12337            scheduleWritePackageRestrictionsLocked(userId);
12338        }
12339        return result;
12340    }
12341
12342    @Override
12343    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12344            String packageName) {
12345        synchronized (mPackages) {
12346            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12347        }
12348    }
12349
12350    @Override
12351    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12352        if (TextUtils.isEmpty(packageName)) {
12353            return ParceledListSlice.emptyList();
12354        }
12355        synchronized (mPackages) {
12356            PackageParser.Package pkg = mPackages.get(packageName);
12357            if (pkg == null || pkg.activities == null) {
12358                return ParceledListSlice.emptyList();
12359            }
12360            final int count = pkg.activities.size();
12361            ArrayList<IntentFilter> result = new ArrayList<>();
12362            for (int n=0; n<count; n++) {
12363                PackageParser.Activity activity = pkg.activities.get(n);
12364                if (activity.intents != null && activity.intents.size() > 0) {
12365                    result.addAll(activity.intents);
12366                }
12367            }
12368            return new ParceledListSlice<>(result);
12369        }
12370    }
12371
12372    @Override
12373    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12374        mContext.enforceCallingOrSelfPermission(
12375                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12376
12377        synchronized (mPackages) {
12378            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12379            if (packageName != null) {
12380                result |= updateIntentVerificationStatus(packageName,
12381                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12382                        userId);
12383                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12384                        packageName, userId);
12385            }
12386            return result;
12387        }
12388    }
12389
12390    @Override
12391    public String getDefaultBrowserPackageName(int userId) {
12392        synchronized (mPackages) {
12393            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12394        }
12395    }
12396
12397    /**
12398     * Get the "allow unknown sources" setting.
12399     *
12400     * @return the current "allow unknown sources" setting
12401     */
12402    private int getUnknownSourcesSettings() {
12403        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12404                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12405                -1);
12406    }
12407
12408    @Override
12409    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12410        final int uid = Binder.getCallingUid();
12411        // writer
12412        synchronized (mPackages) {
12413            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12414            if (targetPackageSetting == null) {
12415                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12416            }
12417
12418            PackageSetting installerPackageSetting;
12419            if (installerPackageName != null) {
12420                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12421                if (installerPackageSetting == null) {
12422                    throw new IllegalArgumentException("Unknown installer package: "
12423                            + installerPackageName);
12424                }
12425            } else {
12426                installerPackageSetting = null;
12427            }
12428
12429            Signature[] callerSignature;
12430            Object obj = mSettings.getUserIdLPr(uid);
12431            if (obj != null) {
12432                if (obj instanceof SharedUserSetting) {
12433                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12434                } else if (obj instanceof PackageSetting) {
12435                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12436                } else {
12437                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12438                }
12439            } else {
12440                throw new SecurityException("Unknown calling UID: " + uid);
12441            }
12442
12443            // Verify: can't set installerPackageName to a package that is
12444            // not signed with the same cert as the caller.
12445            if (installerPackageSetting != null) {
12446                if (compareSignatures(callerSignature,
12447                        installerPackageSetting.signatures.mSignatures)
12448                        != PackageManager.SIGNATURE_MATCH) {
12449                    throw new SecurityException(
12450                            "Caller does not have same cert as new installer package "
12451                            + installerPackageName);
12452                }
12453            }
12454
12455            // Verify: if target already has an installer package, it must
12456            // be signed with the same cert as the caller.
12457            if (targetPackageSetting.installerPackageName != null) {
12458                PackageSetting setting = mSettings.mPackages.get(
12459                        targetPackageSetting.installerPackageName);
12460                // If the currently set package isn't valid, then it's always
12461                // okay to change it.
12462                if (setting != null) {
12463                    if (compareSignatures(callerSignature,
12464                            setting.signatures.mSignatures)
12465                            != PackageManager.SIGNATURE_MATCH) {
12466                        throw new SecurityException(
12467                                "Caller does not have same cert as old installer package "
12468                                + targetPackageSetting.installerPackageName);
12469                    }
12470                }
12471            }
12472
12473            // Okay!
12474            targetPackageSetting.installerPackageName = installerPackageName;
12475            if (installerPackageName != null) {
12476                mSettings.mInstallerPackages.add(installerPackageName);
12477            }
12478            scheduleWriteSettingsLocked();
12479        }
12480    }
12481
12482    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12483        // Queue up an async operation since the package installation may take a little while.
12484        mHandler.post(new Runnable() {
12485            public void run() {
12486                mHandler.removeCallbacks(this);
12487                 // Result object to be returned
12488                PackageInstalledInfo res = new PackageInstalledInfo();
12489                res.setReturnCode(currentStatus);
12490                res.uid = -1;
12491                res.pkg = null;
12492                res.removedInfo = null;
12493                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12494                    args.doPreInstall(res.returnCode);
12495                    synchronized (mInstallLock) {
12496                        installPackageTracedLI(args, res);
12497                    }
12498                    args.doPostInstall(res.returnCode, res.uid);
12499                }
12500
12501                // A restore should be performed at this point if (a) the install
12502                // succeeded, (b) the operation is not an update, and (c) the new
12503                // package has not opted out of backup participation.
12504                final boolean update = res.removedInfo != null
12505                        && res.removedInfo.removedPackage != null;
12506                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12507                boolean doRestore = !update
12508                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12509
12510                // Set up the post-install work request bookkeeping.  This will be used
12511                // and cleaned up by the post-install event handling regardless of whether
12512                // there's a restore pass performed.  Token values are >= 1.
12513                int token;
12514                if (mNextInstallToken < 0) mNextInstallToken = 1;
12515                token = mNextInstallToken++;
12516
12517                PostInstallData data = new PostInstallData(args, res);
12518                mRunningInstalls.put(token, data);
12519                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12520
12521                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12522                    // Pass responsibility to the Backup Manager.  It will perform a
12523                    // restore if appropriate, then pass responsibility back to the
12524                    // Package Manager to run the post-install observer callbacks
12525                    // and broadcasts.
12526                    IBackupManager bm = IBackupManager.Stub.asInterface(
12527                            ServiceManager.getService(Context.BACKUP_SERVICE));
12528                    if (bm != null) {
12529                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12530                                + " to BM for possible restore");
12531                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12532                        try {
12533                            // TODO: http://b/22388012
12534                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12535                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12536                            } else {
12537                                doRestore = false;
12538                            }
12539                        } catch (RemoteException e) {
12540                            // can't happen; the backup manager is local
12541                        } catch (Exception e) {
12542                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12543                            doRestore = false;
12544                        }
12545                    } else {
12546                        Slog.e(TAG, "Backup Manager not found!");
12547                        doRestore = false;
12548                    }
12549                }
12550
12551                if (!doRestore) {
12552                    // No restore possible, or the Backup Manager was mysteriously not
12553                    // available -- just fire the post-install work request directly.
12554                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12555
12556                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12557
12558                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12559                    mHandler.sendMessage(msg);
12560                }
12561            }
12562        });
12563    }
12564
12565    /**
12566     * Callback from PackageSettings whenever an app is first transitioned out of the
12567     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12568     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12569     * here whether the app is the target of an ongoing install, and only send the
12570     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12571     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12572     * handling.
12573     */
12574    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12575        // Serialize this with the rest of the install-process message chain.  In the
12576        // restore-at-install case, this Runnable will necessarily run before the
12577        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12578        // are coherent.  In the non-restore case, the app has already completed install
12579        // and been launched through some other means, so it is not in a problematic
12580        // state for observers to see the FIRST_LAUNCH signal.
12581        mHandler.post(new Runnable() {
12582            @Override
12583            public void run() {
12584                for (int i = 0; i < mRunningInstalls.size(); i++) {
12585                    final PostInstallData data = mRunningInstalls.valueAt(i);
12586                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12587                        continue;
12588                    }
12589                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12590                        // right package; but is it for the right user?
12591                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12592                            if (userId == data.res.newUsers[uIndex]) {
12593                                if (DEBUG_BACKUP) {
12594                                    Slog.i(TAG, "Package " + pkgName
12595                                            + " being restored so deferring FIRST_LAUNCH");
12596                                }
12597                                return;
12598                            }
12599                        }
12600                    }
12601                }
12602                // didn't find it, so not being restored
12603                if (DEBUG_BACKUP) {
12604                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12605                }
12606                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12607            }
12608        });
12609    }
12610
12611    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12612        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12613                installerPkg, null, userIds);
12614    }
12615
12616    private abstract class HandlerParams {
12617        private static final int MAX_RETRIES = 4;
12618
12619        /**
12620         * Number of times startCopy() has been attempted and had a non-fatal
12621         * error.
12622         */
12623        private int mRetries = 0;
12624
12625        /** User handle for the user requesting the information or installation. */
12626        private final UserHandle mUser;
12627        String traceMethod;
12628        int traceCookie;
12629
12630        HandlerParams(UserHandle user) {
12631            mUser = user;
12632        }
12633
12634        UserHandle getUser() {
12635            return mUser;
12636        }
12637
12638        HandlerParams setTraceMethod(String traceMethod) {
12639            this.traceMethod = traceMethod;
12640            return this;
12641        }
12642
12643        HandlerParams setTraceCookie(int traceCookie) {
12644            this.traceCookie = traceCookie;
12645            return this;
12646        }
12647
12648        final boolean startCopy() {
12649            boolean res;
12650            try {
12651                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12652
12653                if (++mRetries > MAX_RETRIES) {
12654                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12655                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12656                    handleServiceError();
12657                    return false;
12658                } else {
12659                    handleStartCopy();
12660                    res = true;
12661                }
12662            } catch (RemoteException e) {
12663                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12664                mHandler.sendEmptyMessage(MCS_RECONNECT);
12665                res = false;
12666            }
12667            handleReturnCode();
12668            return res;
12669        }
12670
12671        final void serviceError() {
12672            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12673            handleServiceError();
12674            handleReturnCode();
12675        }
12676
12677        abstract void handleStartCopy() throws RemoteException;
12678        abstract void handleServiceError();
12679        abstract void handleReturnCode();
12680    }
12681
12682    class MeasureParams extends HandlerParams {
12683        private final PackageStats mStats;
12684        private boolean mSuccess;
12685
12686        private final IPackageStatsObserver mObserver;
12687
12688        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12689            super(new UserHandle(stats.userHandle));
12690            mObserver = observer;
12691            mStats = stats;
12692        }
12693
12694        @Override
12695        public String toString() {
12696            return "MeasureParams{"
12697                + Integer.toHexString(System.identityHashCode(this))
12698                + " " + mStats.packageName + "}";
12699        }
12700
12701        @Override
12702        void handleStartCopy() throws RemoteException {
12703            synchronized (mInstallLock) {
12704                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12705            }
12706
12707            if (mSuccess) {
12708                boolean mounted = false;
12709                try {
12710                    final String status = Environment.getExternalStorageState();
12711                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12712                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12713                } catch (Exception e) {
12714                }
12715
12716                if (mounted) {
12717                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12718
12719                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12720                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12721
12722                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12723                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12724
12725                    // Always subtract cache size, since it's a subdirectory
12726                    mStats.externalDataSize -= mStats.externalCacheSize;
12727
12728                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12729                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12730
12731                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12732                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12733                }
12734            }
12735        }
12736
12737        @Override
12738        void handleReturnCode() {
12739            if (mObserver != null) {
12740                try {
12741                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12742                } catch (RemoteException e) {
12743                    Slog.i(TAG, "Observer no longer exists.");
12744                }
12745            }
12746        }
12747
12748        @Override
12749        void handleServiceError() {
12750            Slog.e(TAG, "Could not measure application " + mStats.packageName
12751                            + " external storage");
12752        }
12753    }
12754
12755    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12756            throws RemoteException {
12757        long result = 0;
12758        for (File path : paths) {
12759            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12760        }
12761        return result;
12762    }
12763
12764    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12765        for (File path : paths) {
12766            try {
12767                mcs.clearDirectory(path.getAbsolutePath());
12768            } catch (RemoteException e) {
12769            }
12770        }
12771    }
12772
12773    static class OriginInfo {
12774        /**
12775         * Location where install is coming from, before it has been
12776         * copied/renamed into place. This could be a single monolithic APK
12777         * file, or a cluster directory. This location may be untrusted.
12778         */
12779        final File file;
12780        final String cid;
12781
12782        /**
12783         * Flag indicating that {@link #file} or {@link #cid} has already been
12784         * staged, meaning downstream users don't need to defensively copy the
12785         * contents.
12786         */
12787        final boolean staged;
12788
12789        /**
12790         * Flag indicating that {@link #file} or {@link #cid} is an already
12791         * installed app that is being moved.
12792         */
12793        final boolean existing;
12794
12795        final String resolvedPath;
12796        final File resolvedFile;
12797
12798        static OriginInfo fromNothing() {
12799            return new OriginInfo(null, null, false, false);
12800        }
12801
12802        static OriginInfo fromUntrustedFile(File file) {
12803            return new OriginInfo(file, null, false, false);
12804        }
12805
12806        static OriginInfo fromExistingFile(File file) {
12807            return new OriginInfo(file, null, false, true);
12808        }
12809
12810        static OriginInfo fromStagedFile(File file) {
12811            return new OriginInfo(file, null, true, false);
12812        }
12813
12814        static OriginInfo fromStagedContainer(String cid) {
12815            return new OriginInfo(null, cid, true, false);
12816        }
12817
12818        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12819            this.file = file;
12820            this.cid = cid;
12821            this.staged = staged;
12822            this.existing = existing;
12823
12824            if (cid != null) {
12825                resolvedPath = PackageHelper.getSdDir(cid);
12826                resolvedFile = new File(resolvedPath);
12827            } else if (file != null) {
12828                resolvedPath = file.getAbsolutePath();
12829                resolvedFile = file;
12830            } else {
12831                resolvedPath = null;
12832                resolvedFile = null;
12833            }
12834        }
12835    }
12836
12837    static class MoveInfo {
12838        final int moveId;
12839        final String fromUuid;
12840        final String toUuid;
12841        final String packageName;
12842        final String dataAppName;
12843        final int appId;
12844        final String seinfo;
12845        final int targetSdkVersion;
12846
12847        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12848                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12849            this.moveId = moveId;
12850            this.fromUuid = fromUuid;
12851            this.toUuid = toUuid;
12852            this.packageName = packageName;
12853            this.dataAppName = dataAppName;
12854            this.appId = appId;
12855            this.seinfo = seinfo;
12856            this.targetSdkVersion = targetSdkVersion;
12857        }
12858    }
12859
12860    static class VerificationInfo {
12861        /** A constant used to indicate that a uid value is not present. */
12862        public static final int NO_UID = -1;
12863
12864        /** URI referencing where the package was downloaded from. */
12865        final Uri originatingUri;
12866
12867        /** HTTP referrer URI associated with the originatingURI. */
12868        final Uri referrer;
12869
12870        /** UID of the application that the install request originated from. */
12871        final int originatingUid;
12872
12873        /** UID of application requesting the install */
12874        final int installerUid;
12875
12876        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12877            this.originatingUri = originatingUri;
12878            this.referrer = referrer;
12879            this.originatingUid = originatingUid;
12880            this.installerUid = installerUid;
12881        }
12882    }
12883
12884    class InstallParams extends HandlerParams {
12885        final OriginInfo origin;
12886        final MoveInfo move;
12887        final IPackageInstallObserver2 observer;
12888        int installFlags;
12889        final String installerPackageName;
12890        final String volumeUuid;
12891        private InstallArgs mArgs;
12892        private int mRet;
12893        final String packageAbiOverride;
12894        final String[] grantedRuntimePermissions;
12895        final VerificationInfo verificationInfo;
12896        final Certificate[][] certificates;
12897
12898        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12899                int installFlags, String installerPackageName, String volumeUuid,
12900                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12901                String[] grantedPermissions, Certificate[][] certificates) {
12902            super(user);
12903            this.origin = origin;
12904            this.move = move;
12905            this.observer = observer;
12906            this.installFlags = installFlags;
12907            this.installerPackageName = installerPackageName;
12908            this.volumeUuid = volumeUuid;
12909            this.verificationInfo = verificationInfo;
12910            this.packageAbiOverride = packageAbiOverride;
12911            this.grantedRuntimePermissions = grantedPermissions;
12912            this.certificates = certificates;
12913        }
12914
12915        @Override
12916        public String toString() {
12917            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12918                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12919        }
12920
12921        private int installLocationPolicy(PackageInfoLite pkgLite) {
12922            String packageName = pkgLite.packageName;
12923            int installLocation = pkgLite.installLocation;
12924            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12925            // reader
12926            synchronized (mPackages) {
12927                // Currently installed package which the new package is attempting to replace or
12928                // null if no such package is installed.
12929                PackageParser.Package installedPkg = mPackages.get(packageName);
12930                // Package which currently owns the data which the new package will own if installed.
12931                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12932                // will be null whereas dataOwnerPkg will contain information about the package
12933                // which was uninstalled while keeping its data.
12934                PackageParser.Package dataOwnerPkg = installedPkg;
12935                if (dataOwnerPkg  == null) {
12936                    PackageSetting ps = mSettings.mPackages.get(packageName);
12937                    if (ps != null) {
12938                        dataOwnerPkg = ps.pkg;
12939                    }
12940                }
12941
12942                if (dataOwnerPkg != null) {
12943                    // If installed, the package will get access to data left on the device by its
12944                    // predecessor. As a security measure, this is permited only if this is not a
12945                    // version downgrade or if the predecessor package is marked as debuggable and
12946                    // a downgrade is explicitly requested.
12947                    //
12948                    // On debuggable platform builds, downgrades are permitted even for
12949                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12950                    // not offer security guarantees and thus it's OK to disable some security
12951                    // mechanisms to make debugging/testing easier on those builds. However, even on
12952                    // debuggable builds downgrades of packages are permitted only if requested via
12953                    // installFlags. This is because we aim to keep the behavior of debuggable
12954                    // platform builds as close as possible to the behavior of non-debuggable
12955                    // platform builds.
12956                    final boolean downgradeRequested =
12957                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12958                    final boolean packageDebuggable =
12959                                (dataOwnerPkg.applicationInfo.flags
12960                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12961                    final boolean downgradePermitted =
12962                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12963                    if (!downgradePermitted) {
12964                        try {
12965                            checkDowngrade(dataOwnerPkg, pkgLite);
12966                        } catch (PackageManagerException e) {
12967                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12968                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12969                        }
12970                    }
12971                }
12972
12973                if (installedPkg != null) {
12974                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12975                        // Check for updated system application.
12976                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12977                            if (onSd) {
12978                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12979                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12980                            }
12981                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12982                        } else {
12983                            if (onSd) {
12984                                // Install flag overrides everything.
12985                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12986                            }
12987                            // If current upgrade specifies particular preference
12988                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12989                                // Application explicitly specified internal.
12990                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12991                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12992                                // App explictly prefers external. Let policy decide
12993                            } else {
12994                                // Prefer previous location
12995                                if (isExternal(installedPkg)) {
12996                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12997                                }
12998                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12999                            }
13000                        }
13001                    } else {
13002                        // Invalid install. Return error code
13003                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
13004                    }
13005                }
13006            }
13007            // All the special cases have been taken care of.
13008            // Return result based on recommended install location.
13009            if (onSd) {
13010                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13011            }
13012            return pkgLite.recommendedInstallLocation;
13013        }
13014
13015        /*
13016         * Invoke remote method to get package information and install
13017         * location values. Override install location based on default
13018         * policy if needed and then create install arguments based
13019         * on the install location.
13020         */
13021        public void handleStartCopy() throws RemoteException {
13022            int ret = PackageManager.INSTALL_SUCCEEDED;
13023
13024            // If we're already staged, we've firmly committed to an install location
13025            if (origin.staged) {
13026                if (origin.file != null) {
13027                    installFlags |= PackageManager.INSTALL_INTERNAL;
13028                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13029                } else if (origin.cid != null) {
13030                    installFlags |= PackageManager.INSTALL_EXTERNAL;
13031                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
13032                } else {
13033                    throw new IllegalStateException("Invalid stage location");
13034                }
13035            }
13036
13037            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13038            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
13039            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13040            PackageInfoLite pkgLite = null;
13041
13042            if (onInt && onSd) {
13043                // Check if both bits are set.
13044                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
13045                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13046            } else if (onSd && ephemeral) {
13047                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
13048                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13049            } else {
13050                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13051                        packageAbiOverride);
13052
13053                if (DEBUG_EPHEMERAL && ephemeral) {
13054                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
13055                }
13056
13057                /*
13058                 * If we have too little free space, try to free cache
13059                 * before giving up.
13060                 */
13061                if (!origin.staged && pkgLite.recommendedInstallLocation
13062                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13063                    // TODO: focus freeing disk space on the target device
13064                    final StorageManager storage = StorageManager.from(mContext);
13065                    final long lowThreshold = storage.getStorageLowBytes(
13066                            Environment.getDataDirectory());
13067
13068                    final long sizeBytes = mContainerService.calculateInstalledSize(
13069                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13070
13071                    try {
13072                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
13073                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13074                                installFlags, packageAbiOverride);
13075                    } catch (InstallerException e) {
13076                        Slog.w(TAG, "Failed to free cache", e);
13077                    }
13078
13079                    /*
13080                     * The cache free must have deleted the file we
13081                     * downloaded to install.
13082                     *
13083                     * TODO: fix the "freeCache" call to not delete
13084                     *       the file we care about.
13085                     */
13086                    if (pkgLite.recommendedInstallLocation
13087                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13088                        pkgLite.recommendedInstallLocation
13089                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13090                    }
13091                }
13092            }
13093
13094            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13095                int loc = pkgLite.recommendedInstallLocation;
13096                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13097                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13098                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13099                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13100                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13101                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13102                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13103                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13104                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13105                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13106                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13107                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13108                } else {
13109                    // Override with defaults if needed.
13110                    loc = installLocationPolicy(pkgLite);
13111                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13112                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13113                    } else if (!onSd && !onInt) {
13114                        // Override install location with flags
13115                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13116                            // Set the flag to install on external media.
13117                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13118                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13119                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13120                            if (DEBUG_EPHEMERAL) {
13121                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13122                            }
13123                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13124                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13125                                    |PackageManager.INSTALL_INTERNAL);
13126                        } else {
13127                            // Make sure the flag for installing on external
13128                            // media is unset
13129                            installFlags |= PackageManager.INSTALL_INTERNAL;
13130                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13131                        }
13132                    }
13133                }
13134            }
13135
13136            final InstallArgs args = createInstallArgs(this);
13137            mArgs = args;
13138
13139            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13140                // TODO: http://b/22976637
13141                // Apps installed for "all" users use the device owner to verify the app
13142                UserHandle verifierUser = getUser();
13143                if (verifierUser == UserHandle.ALL) {
13144                    verifierUser = UserHandle.SYSTEM;
13145                }
13146
13147                /*
13148                 * Determine if we have any installed package verifiers. If we
13149                 * do, then we'll defer to them to verify the packages.
13150                 */
13151                final int requiredUid = mRequiredVerifierPackage == null ? -1
13152                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13153                                verifierUser.getIdentifier());
13154                if (!origin.existing && requiredUid != -1
13155                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13156                    final Intent verification = new Intent(
13157                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13158                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13159                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13160                            PACKAGE_MIME_TYPE);
13161                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13162
13163                    // Query all live verifiers based on current user state
13164                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13165                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13166
13167                    if (DEBUG_VERIFY) {
13168                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13169                                + verification.toString() + " with " + pkgLite.verifiers.length
13170                                + " optional verifiers");
13171                    }
13172
13173                    final int verificationId = mPendingVerificationToken++;
13174
13175                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13176
13177                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13178                            installerPackageName);
13179
13180                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13181                            installFlags);
13182
13183                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13184                            pkgLite.packageName);
13185
13186                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13187                            pkgLite.versionCode);
13188
13189                    if (verificationInfo != null) {
13190                        if (verificationInfo.originatingUri != null) {
13191                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13192                                    verificationInfo.originatingUri);
13193                        }
13194                        if (verificationInfo.referrer != null) {
13195                            verification.putExtra(Intent.EXTRA_REFERRER,
13196                                    verificationInfo.referrer);
13197                        }
13198                        if (verificationInfo.originatingUid >= 0) {
13199                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13200                                    verificationInfo.originatingUid);
13201                        }
13202                        if (verificationInfo.installerUid >= 0) {
13203                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13204                                    verificationInfo.installerUid);
13205                        }
13206                    }
13207
13208                    final PackageVerificationState verificationState = new PackageVerificationState(
13209                            requiredUid, args);
13210
13211                    mPendingVerification.append(verificationId, verificationState);
13212
13213                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13214                            receivers, verificationState);
13215
13216                    /*
13217                     * If any sufficient verifiers were listed in the package
13218                     * manifest, attempt to ask them.
13219                     */
13220                    if (sufficientVerifiers != null) {
13221                        final int N = sufficientVerifiers.size();
13222                        if (N == 0) {
13223                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13224                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13225                        } else {
13226                            for (int i = 0; i < N; i++) {
13227                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13228
13229                                final Intent sufficientIntent = new Intent(verification);
13230                                sufficientIntent.setComponent(verifierComponent);
13231                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13232                            }
13233                        }
13234                    }
13235
13236                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13237                            mRequiredVerifierPackage, receivers);
13238                    if (ret == PackageManager.INSTALL_SUCCEEDED
13239                            && mRequiredVerifierPackage != null) {
13240                        Trace.asyncTraceBegin(
13241                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13242                        /*
13243                         * Send the intent to the required verification agent,
13244                         * but only start the verification timeout after the
13245                         * target BroadcastReceivers have run.
13246                         */
13247                        verification.setComponent(requiredVerifierComponent);
13248                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13249                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13250                                new BroadcastReceiver() {
13251                                    @Override
13252                                    public void onReceive(Context context, Intent intent) {
13253                                        final Message msg = mHandler
13254                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13255                                        msg.arg1 = verificationId;
13256                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13257                                    }
13258                                }, null, 0, null, null);
13259
13260                        /*
13261                         * We don't want the copy to proceed until verification
13262                         * succeeds, so null out this field.
13263                         */
13264                        mArgs = null;
13265                    }
13266                } else {
13267                    /*
13268                     * No package verification is enabled, so immediately start
13269                     * the remote call to initiate copy using temporary file.
13270                     */
13271                    ret = args.copyApk(mContainerService, true);
13272                }
13273            }
13274
13275            mRet = ret;
13276        }
13277
13278        @Override
13279        void handleReturnCode() {
13280            // If mArgs is null, then MCS couldn't be reached. When it
13281            // reconnects, it will try again to install. At that point, this
13282            // will succeed.
13283            if (mArgs != null) {
13284                processPendingInstall(mArgs, mRet);
13285            }
13286        }
13287
13288        @Override
13289        void handleServiceError() {
13290            mArgs = createInstallArgs(this);
13291            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13292        }
13293
13294        public boolean isForwardLocked() {
13295            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13296        }
13297    }
13298
13299    /**
13300     * Used during creation of InstallArgs
13301     *
13302     * @param installFlags package installation flags
13303     * @return true if should be installed on external storage
13304     */
13305    private static boolean installOnExternalAsec(int installFlags) {
13306        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13307            return false;
13308        }
13309        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13310            return true;
13311        }
13312        return false;
13313    }
13314
13315    /**
13316     * Used during creation of InstallArgs
13317     *
13318     * @param installFlags package installation flags
13319     * @return true if should be installed as forward locked
13320     */
13321    private static boolean installForwardLocked(int installFlags) {
13322        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13323    }
13324
13325    private InstallArgs createInstallArgs(InstallParams params) {
13326        if (params.move != null) {
13327            return new MoveInstallArgs(params);
13328        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13329            return new AsecInstallArgs(params);
13330        } else {
13331            return new FileInstallArgs(params);
13332        }
13333    }
13334
13335    /**
13336     * Create args that describe an existing installed package. Typically used
13337     * when cleaning up old installs, or used as a move source.
13338     */
13339    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13340            String resourcePath, String[] instructionSets) {
13341        final boolean isInAsec;
13342        if (installOnExternalAsec(installFlags)) {
13343            /* Apps on SD card are always in ASEC containers. */
13344            isInAsec = true;
13345        } else if (installForwardLocked(installFlags)
13346                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13347            /*
13348             * Forward-locked apps are only in ASEC containers if they're the
13349             * new style
13350             */
13351            isInAsec = true;
13352        } else {
13353            isInAsec = false;
13354        }
13355
13356        if (isInAsec) {
13357            return new AsecInstallArgs(codePath, instructionSets,
13358                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13359        } else {
13360            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13361        }
13362    }
13363
13364    static abstract class InstallArgs {
13365        /** @see InstallParams#origin */
13366        final OriginInfo origin;
13367        /** @see InstallParams#move */
13368        final MoveInfo move;
13369
13370        final IPackageInstallObserver2 observer;
13371        // Always refers to PackageManager flags only
13372        final int installFlags;
13373        final String installerPackageName;
13374        final String volumeUuid;
13375        final UserHandle user;
13376        final String abiOverride;
13377        final String[] installGrantPermissions;
13378        /** If non-null, drop an async trace when the install completes */
13379        final String traceMethod;
13380        final int traceCookie;
13381        final Certificate[][] certificates;
13382
13383        // The list of instruction sets supported by this app. This is currently
13384        // only used during the rmdex() phase to clean up resources. We can get rid of this
13385        // if we move dex files under the common app path.
13386        /* nullable */ String[] instructionSets;
13387
13388        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13389                int installFlags, String installerPackageName, String volumeUuid,
13390                UserHandle user, String[] instructionSets,
13391                String abiOverride, String[] installGrantPermissions,
13392                String traceMethod, int traceCookie, Certificate[][] certificates) {
13393            this.origin = origin;
13394            this.move = move;
13395            this.installFlags = installFlags;
13396            this.observer = observer;
13397            this.installerPackageName = installerPackageName;
13398            this.volumeUuid = volumeUuid;
13399            this.user = user;
13400            this.instructionSets = instructionSets;
13401            this.abiOverride = abiOverride;
13402            this.installGrantPermissions = installGrantPermissions;
13403            this.traceMethod = traceMethod;
13404            this.traceCookie = traceCookie;
13405            this.certificates = certificates;
13406        }
13407
13408        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13409        abstract int doPreInstall(int status);
13410
13411        /**
13412         * Rename package into final resting place. All paths on the given
13413         * scanned package should be updated to reflect the rename.
13414         */
13415        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13416        abstract int doPostInstall(int status, int uid);
13417
13418        /** @see PackageSettingBase#codePathString */
13419        abstract String getCodePath();
13420        /** @see PackageSettingBase#resourcePathString */
13421        abstract String getResourcePath();
13422
13423        // Need installer lock especially for dex file removal.
13424        abstract void cleanUpResourcesLI();
13425        abstract boolean doPostDeleteLI(boolean delete);
13426
13427        /**
13428         * Called before the source arguments are copied. This is used mostly
13429         * for MoveParams when it needs to read the source file to put it in the
13430         * destination.
13431         */
13432        int doPreCopy() {
13433            return PackageManager.INSTALL_SUCCEEDED;
13434        }
13435
13436        /**
13437         * Called after the source arguments are copied. This is used mostly for
13438         * MoveParams when it needs to read the source file to put it in the
13439         * destination.
13440         */
13441        int doPostCopy(int uid) {
13442            return PackageManager.INSTALL_SUCCEEDED;
13443        }
13444
13445        protected boolean isFwdLocked() {
13446            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13447        }
13448
13449        protected boolean isExternalAsec() {
13450            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13451        }
13452
13453        protected boolean isEphemeral() {
13454            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13455        }
13456
13457        UserHandle getUser() {
13458            return user;
13459        }
13460    }
13461
13462    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13463        if (!allCodePaths.isEmpty()) {
13464            if (instructionSets == null) {
13465                throw new IllegalStateException("instructionSet == null");
13466            }
13467            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13468            for (String codePath : allCodePaths) {
13469                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13470                    try {
13471                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13472                    } catch (InstallerException ignored) {
13473                    }
13474                }
13475            }
13476        }
13477    }
13478
13479    /**
13480     * Logic to handle installation of non-ASEC applications, including copying
13481     * and renaming logic.
13482     */
13483    class FileInstallArgs extends InstallArgs {
13484        private File codeFile;
13485        private File resourceFile;
13486
13487        // Example topology:
13488        // /data/app/com.example/base.apk
13489        // /data/app/com.example/split_foo.apk
13490        // /data/app/com.example/lib/arm/libfoo.so
13491        // /data/app/com.example/lib/arm64/libfoo.so
13492        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13493
13494        /** New install */
13495        FileInstallArgs(InstallParams params) {
13496            super(params.origin, params.move, params.observer, params.installFlags,
13497                    params.installerPackageName, params.volumeUuid,
13498                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13499                    params.grantedRuntimePermissions,
13500                    params.traceMethod, params.traceCookie, params.certificates);
13501            if (isFwdLocked()) {
13502                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13503            }
13504        }
13505
13506        /** Existing install */
13507        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13508            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13509                    null, null, null, 0, null /*certificates*/);
13510            this.codeFile = (codePath != null) ? new File(codePath) : null;
13511            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13512        }
13513
13514        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13515            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13516            try {
13517                return doCopyApk(imcs, temp);
13518            } finally {
13519                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13520            }
13521        }
13522
13523        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13524            if (origin.staged) {
13525                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13526                codeFile = origin.file;
13527                resourceFile = origin.file;
13528                return PackageManager.INSTALL_SUCCEEDED;
13529            }
13530
13531            try {
13532                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13533                final File tempDir =
13534                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13535                codeFile = tempDir;
13536                resourceFile = tempDir;
13537            } catch (IOException e) {
13538                Slog.w(TAG, "Failed to create copy file: " + e);
13539                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13540            }
13541
13542            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13543                @Override
13544                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13545                    if (!FileUtils.isValidExtFilename(name)) {
13546                        throw new IllegalArgumentException("Invalid filename: " + name);
13547                    }
13548                    try {
13549                        final File file = new File(codeFile, name);
13550                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13551                                O_RDWR | O_CREAT, 0644);
13552                        Os.chmod(file.getAbsolutePath(), 0644);
13553                        return new ParcelFileDescriptor(fd);
13554                    } catch (ErrnoException e) {
13555                        throw new RemoteException("Failed to open: " + e.getMessage());
13556                    }
13557                }
13558            };
13559
13560            int ret = PackageManager.INSTALL_SUCCEEDED;
13561            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13562            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13563                Slog.e(TAG, "Failed to copy package");
13564                return ret;
13565            }
13566
13567            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13568            NativeLibraryHelper.Handle handle = null;
13569            try {
13570                handle = NativeLibraryHelper.Handle.create(codeFile);
13571                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13572                        abiOverride);
13573            } catch (IOException e) {
13574                Slog.e(TAG, "Copying native libraries failed", e);
13575                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13576            } finally {
13577                IoUtils.closeQuietly(handle);
13578            }
13579
13580            return ret;
13581        }
13582
13583        int doPreInstall(int status) {
13584            if (status != PackageManager.INSTALL_SUCCEEDED) {
13585                cleanUp();
13586            }
13587            return status;
13588        }
13589
13590        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13591            if (status != PackageManager.INSTALL_SUCCEEDED) {
13592                cleanUp();
13593                return false;
13594            }
13595
13596            final File targetDir = codeFile.getParentFile();
13597            final File beforeCodeFile = codeFile;
13598            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13599
13600            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13601            try {
13602                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13603            } catch (ErrnoException e) {
13604                Slog.w(TAG, "Failed to rename", e);
13605                return false;
13606            }
13607
13608            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13609                Slog.w(TAG, "Failed to restorecon");
13610                return false;
13611            }
13612
13613            // Reflect the rename internally
13614            codeFile = afterCodeFile;
13615            resourceFile = afterCodeFile;
13616
13617            // Reflect the rename in scanned details
13618            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13619            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13620                    afterCodeFile, pkg.baseCodePath));
13621            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13622                    afterCodeFile, pkg.splitCodePaths));
13623
13624            // Reflect the rename in app info
13625            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13626            pkg.setApplicationInfoCodePath(pkg.codePath);
13627            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13628            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13629            pkg.setApplicationInfoResourcePath(pkg.codePath);
13630            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13631            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13632
13633            return true;
13634        }
13635
13636        int doPostInstall(int status, int uid) {
13637            if (status != PackageManager.INSTALL_SUCCEEDED) {
13638                cleanUp();
13639            }
13640            return status;
13641        }
13642
13643        @Override
13644        String getCodePath() {
13645            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13646        }
13647
13648        @Override
13649        String getResourcePath() {
13650            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13651        }
13652
13653        private boolean cleanUp() {
13654            if (codeFile == null || !codeFile.exists()) {
13655                return false;
13656            }
13657
13658            removeCodePathLI(codeFile);
13659
13660            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13661                resourceFile.delete();
13662            }
13663
13664            return true;
13665        }
13666
13667        void cleanUpResourcesLI() {
13668            // Try enumerating all code paths before deleting
13669            List<String> allCodePaths = Collections.EMPTY_LIST;
13670            if (codeFile != null && codeFile.exists()) {
13671                try {
13672                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13673                    allCodePaths = pkg.getAllCodePaths();
13674                } catch (PackageParserException e) {
13675                    // Ignored; we tried our best
13676                }
13677            }
13678
13679            cleanUp();
13680            removeDexFiles(allCodePaths, instructionSets);
13681        }
13682
13683        boolean doPostDeleteLI(boolean delete) {
13684            // XXX err, shouldn't we respect the delete flag?
13685            cleanUpResourcesLI();
13686            return true;
13687        }
13688    }
13689
13690    private boolean isAsecExternal(String cid) {
13691        final String asecPath = PackageHelper.getSdFilesystem(cid);
13692        return !asecPath.startsWith(mAsecInternalPath);
13693    }
13694
13695    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13696            PackageManagerException {
13697        if (copyRet < 0) {
13698            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13699                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13700                throw new PackageManagerException(copyRet, message);
13701            }
13702        }
13703    }
13704
13705    /**
13706     * Extract the MountService "container ID" from the full code path of an
13707     * .apk.
13708     */
13709    static String cidFromCodePath(String fullCodePath) {
13710        int eidx = fullCodePath.lastIndexOf("/");
13711        String subStr1 = fullCodePath.substring(0, eidx);
13712        int sidx = subStr1.lastIndexOf("/");
13713        return subStr1.substring(sidx+1, eidx);
13714    }
13715
13716    /**
13717     * Logic to handle installation of ASEC applications, including copying and
13718     * renaming logic.
13719     */
13720    class AsecInstallArgs extends InstallArgs {
13721        static final String RES_FILE_NAME = "pkg.apk";
13722        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13723
13724        String cid;
13725        String packagePath;
13726        String resourcePath;
13727
13728        /** New install */
13729        AsecInstallArgs(InstallParams params) {
13730            super(params.origin, params.move, params.observer, params.installFlags,
13731                    params.installerPackageName, params.volumeUuid,
13732                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13733                    params.grantedRuntimePermissions,
13734                    params.traceMethod, params.traceCookie, params.certificates);
13735        }
13736
13737        /** Existing install */
13738        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13739                        boolean isExternal, boolean isForwardLocked) {
13740            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13741              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13742                    instructionSets, null, null, null, 0, null /*certificates*/);
13743            // Hackily pretend we're still looking at a full code path
13744            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13745                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13746            }
13747
13748            // Extract cid from fullCodePath
13749            int eidx = fullCodePath.lastIndexOf("/");
13750            String subStr1 = fullCodePath.substring(0, eidx);
13751            int sidx = subStr1.lastIndexOf("/");
13752            cid = subStr1.substring(sidx+1, eidx);
13753            setMountPath(subStr1);
13754        }
13755
13756        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13757            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13758              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13759                    instructionSets, null, null, null, 0, null /*certificates*/);
13760            this.cid = cid;
13761            setMountPath(PackageHelper.getSdDir(cid));
13762        }
13763
13764        void createCopyFile() {
13765            cid = mInstallerService.allocateExternalStageCidLegacy();
13766        }
13767
13768        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13769            if (origin.staged && origin.cid != null) {
13770                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13771                cid = origin.cid;
13772                setMountPath(PackageHelper.getSdDir(cid));
13773                return PackageManager.INSTALL_SUCCEEDED;
13774            }
13775
13776            if (temp) {
13777                createCopyFile();
13778            } else {
13779                /*
13780                 * Pre-emptively destroy the container since it's destroyed if
13781                 * copying fails due to it existing anyway.
13782                 */
13783                PackageHelper.destroySdDir(cid);
13784            }
13785
13786            final String newMountPath = imcs.copyPackageToContainer(
13787                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13788                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13789
13790            if (newMountPath != null) {
13791                setMountPath(newMountPath);
13792                return PackageManager.INSTALL_SUCCEEDED;
13793            } else {
13794                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13795            }
13796        }
13797
13798        @Override
13799        String getCodePath() {
13800            return packagePath;
13801        }
13802
13803        @Override
13804        String getResourcePath() {
13805            return resourcePath;
13806        }
13807
13808        int doPreInstall(int status) {
13809            if (status != PackageManager.INSTALL_SUCCEEDED) {
13810                // Destroy container
13811                PackageHelper.destroySdDir(cid);
13812            } else {
13813                boolean mounted = PackageHelper.isContainerMounted(cid);
13814                if (!mounted) {
13815                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13816                            Process.SYSTEM_UID);
13817                    if (newMountPath != null) {
13818                        setMountPath(newMountPath);
13819                    } else {
13820                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13821                    }
13822                }
13823            }
13824            return status;
13825        }
13826
13827        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13828            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13829            String newMountPath = null;
13830            if (PackageHelper.isContainerMounted(cid)) {
13831                // Unmount the container
13832                if (!PackageHelper.unMountSdDir(cid)) {
13833                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13834                    return false;
13835                }
13836            }
13837            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13838                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13839                        " which might be stale. Will try to clean up.");
13840                // Clean up the stale container and proceed to recreate.
13841                if (!PackageHelper.destroySdDir(newCacheId)) {
13842                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13843                    return false;
13844                }
13845                // Successfully cleaned up stale container. Try to rename again.
13846                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13847                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13848                            + " inspite of cleaning it up.");
13849                    return false;
13850                }
13851            }
13852            if (!PackageHelper.isContainerMounted(newCacheId)) {
13853                Slog.w(TAG, "Mounting container " + newCacheId);
13854                newMountPath = PackageHelper.mountSdDir(newCacheId,
13855                        getEncryptKey(), Process.SYSTEM_UID);
13856            } else {
13857                newMountPath = PackageHelper.getSdDir(newCacheId);
13858            }
13859            if (newMountPath == null) {
13860                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13861                return false;
13862            }
13863            Log.i(TAG, "Succesfully renamed " + cid +
13864                    " to " + newCacheId +
13865                    " at new path: " + newMountPath);
13866            cid = newCacheId;
13867
13868            final File beforeCodeFile = new File(packagePath);
13869            setMountPath(newMountPath);
13870            final File afterCodeFile = new File(packagePath);
13871
13872            // Reflect the rename in scanned details
13873            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13874            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13875                    afterCodeFile, pkg.baseCodePath));
13876            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13877                    afterCodeFile, pkg.splitCodePaths));
13878
13879            // Reflect the rename in app info
13880            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13881            pkg.setApplicationInfoCodePath(pkg.codePath);
13882            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13883            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13884            pkg.setApplicationInfoResourcePath(pkg.codePath);
13885            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13886            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13887
13888            return true;
13889        }
13890
13891        private void setMountPath(String mountPath) {
13892            final File mountFile = new File(mountPath);
13893
13894            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13895            if (monolithicFile.exists()) {
13896                packagePath = monolithicFile.getAbsolutePath();
13897                if (isFwdLocked()) {
13898                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13899                } else {
13900                    resourcePath = packagePath;
13901                }
13902            } else {
13903                packagePath = mountFile.getAbsolutePath();
13904                resourcePath = packagePath;
13905            }
13906        }
13907
13908        int doPostInstall(int status, int uid) {
13909            if (status != PackageManager.INSTALL_SUCCEEDED) {
13910                cleanUp();
13911            } else {
13912                final int groupOwner;
13913                final String protectedFile;
13914                if (isFwdLocked()) {
13915                    groupOwner = UserHandle.getSharedAppGid(uid);
13916                    protectedFile = RES_FILE_NAME;
13917                } else {
13918                    groupOwner = -1;
13919                    protectedFile = null;
13920                }
13921
13922                if (uid < Process.FIRST_APPLICATION_UID
13923                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13924                    Slog.e(TAG, "Failed to finalize " + cid);
13925                    PackageHelper.destroySdDir(cid);
13926                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13927                }
13928
13929                boolean mounted = PackageHelper.isContainerMounted(cid);
13930                if (!mounted) {
13931                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13932                }
13933            }
13934            return status;
13935        }
13936
13937        private void cleanUp() {
13938            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13939
13940            // Destroy secure container
13941            PackageHelper.destroySdDir(cid);
13942        }
13943
13944        private List<String> getAllCodePaths() {
13945            final File codeFile = new File(getCodePath());
13946            if (codeFile != null && codeFile.exists()) {
13947                try {
13948                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13949                    return pkg.getAllCodePaths();
13950                } catch (PackageParserException e) {
13951                    // Ignored; we tried our best
13952                }
13953            }
13954            return Collections.EMPTY_LIST;
13955        }
13956
13957        void cleanUpResourcesLI() {
13958            // Enumerate all code paths before deleting
13959            cleanUpResourcesLI(getAllCodePaths());
13960        }
13961
13962        private void cleanUpResourcesLI(List<String> allCodePaths) {
13963            cleanUp();
13964            removeDexFiles(allCodePaths, instructionSets);
13965        }
13966
13967        String getPackageName() {
13968            return getAsecPackageName(cid);
13969        }
13970
13971        boolean doPostDeleteLI(boolean delete) {
13972            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13973            final List<String> allCodePaths = getAllCodePaths();
13974            boolean mounted = PackageHelper.isContainerMounted(cid);
13975            if (mounted) {
13976                // Unmount first
13977                if (PackageHelper.unMountSdDir(cid)) {
13978                    mounted = false;
13979                }
13980            }
13981            if (!mounted && delete) {
13982                cleanUpResourcesLI(allCodePaths);
13983            }
13984            return !mounted;
13985        }
13986
13987        @Override
13988        int doPreCopy() {
13989            if (isFwdLocked()) {
13990                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13991                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13992                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13993                }
13994            }
13995
13996            return PackageManager.INSTALL_SUCCEEDED;
13997        }
13998
13999        @Override
14000        int doPostCopy(int uid) {
14001            if (isFwdLocked()) {
14002                if (uid < Process.FIRST_APPLICATION_UID
14003                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
14004                                RES_FILE_NAME)) {
14005                    Slog.e(TAG, "Failed to finalize " + cid);
14006                    PackageHelper.destroySdDir(cid);
14007                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14008                }
14009            }
14010
14011            return PackageManager.INSTALL_SUCCEEDED;
14012        }
14013    }
14014
14015    /**
14016     * Logic to handle movement of existing installed applications.
14017     */
14018    class MoveInstallArgs extends InstallArgs {
14019        private File codeFile;
14020        private File resourceFile;
14021
14022        /** New install */
14023        MoveInstallArgs(InstallParams params) {
14024            super(params.origin, params.move, params.observer, params.installFlags,
14025                    params.installerPackageName, params.volumeUuid,
14026                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14027                    params.grantedRuntimePermissions,
14028                    params.traceMethod, params.traceCookie, params.certificates);
14029        }
14030
14031        int copyApk(IMediaContainerService imcs, boolean temp) {
14032            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
14033                    + move.fromUuid + " to " + move.toUuid);
14034            synchronized (mInstaller) {
14035                try {
14036                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
14037                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
14038                } catch (InstallerException e) {
14039                    Slog.w(TAG, "Failed to move app", e);
14040                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14041                }
14042            }
14043
14044            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
14045            resourceFile = codeFile;
14046            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14047
14048            return PackageManager.INSTALL_SUCCEEDED;
14049        }
14050
14051        int doPreInstall(int status) {
14052            if (status != PackageManager.INSTALL_SUCCEEDED) {
14053                cleanUp(move.toUuid);
14054            }
14055            return status;
14056        }
14057
14058        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14059            if (status != PackageManager.INSTALL_SUCCEEDED) {
14060                cleanUp(move.toUuid);
14061                return false;
14062            }
14063
14064            // Reflect the move in app info
14065            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14066            pkg.setApplicationInfoCodePath(pkg.codePath);
14067            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14068            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14069            pkg.setApplicationInfoResourcePath(pkg.codePath);
14070            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14071            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14072
14073            return true;
14074        }
14075
14076        int doPostInstall(int status, int uid) {
14077            if (status == PackageManager.INSTALL_SUCCEEDED) {
14078                cleanUp(move.fromUuid);
14079            } else {
14080                cleanUp(move.toUuid);
14081            }
14082            return status;
14083        }
14084
14085        @Override
14086        String getCodePath() {
14087            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14088        }
14089
14090        @Override
14091        String getResourcePath() {
14092            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14093        }
14094
14095        private boolean cleanUp(String volumeUuid) {
14096            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14097                    move.dataAppName);
14098            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14099            final int[] userIds = sUserManager.getUserIds();
14100            synchronized (mInstallLock) {
14101                // Clean up both app data and code
14102                // All package moves are frozen until finished
14103                for (int userId : userIds) {
14104                    try {
14105                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14106                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14107                    } catch (InstallerException e) {
14108                        Slog.w(TAG, String.valueOf(e));
14109                    }
14110                }
14111                removeCodePathLI(codeFile);
14112            }
14113            return true;
14114        }
14115
14116        void cleanUpResourcesLI() {
14117            throw new UnsupportedOperationException();
14118        }
14119
14120        boolean doPostDeleteLI(boolean delete) {
14121            throw new UnsupportedOperationException();
14122        }
14123    }
14124
14125    static String getAsecPackageName(String packageCid) {
14126        int idx = packageCid.lastIndexOf("-");
14127        if (idx == -1) {
14128            return packageCid;
14129        }
14130        return packageCid.substring(0, idx);
14131    }
14132
14133    // Utility method used to create code paths based on package name and available index.
14134    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14135        String idxStr = "";
14136        int idx = 1;
14137        // Fall back to default value of idx=1 if prefix is not
14138        // part of oldCodePath
14139        if (oldCodePath != null) {
14140            String subStr = oldCodePath;
14141            // Drop the suffix right away
14142            if (suffix != null && subStr.endsWith(suffix)) {
14143                subStr = subStr.substring(0, subStr.length() - suffix.length());
14144            }
14145            // If oldCodePath already contains prefix find out the
14146            // ending index to either increment or decrement.
14147            int sidx = subStr.lastIndexOf(prefix);
14148            if (sidx != -1) {
14149                subStr = subStr.substring(sidx + prefix.length());
14150                if (subStr != null) {
14151                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14152                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14153                    }
14154                    try {
14155                        idx = Integer.parseInt(subStr);
14156                        if (idx <= 1) {
14157                            idx++;
14158                        } else {
14159                            idx--;
14160                        }
14161                    } catch(NumberFormatException e) {
14162                    }
14163                }
14164            }
14165        }
14166        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14167        return prefix + idxStr;
14168    }
14169
14170    private File getNextCodePath(File targetDir, String packageName) {
14171        int suffix = 1;
14172        File result;
14173        do {
14174            result = new File(targetDir, packageName + "-" + suffix);
14175            suffix++;
14176        } while (result.exists());
14177        return result;
14178    }
14179
14180    // Utility method that returns the relative package path with respect
14181    // to the installation directory. Like say for /data/data/com.test-1.apk
14182    // string com.test-1 is returned.
14183    static String deriveCodePathName(String codePath) {
14184        if (codePath == null) {
14185            return null;
14186        }
14187        final File codeFile = new File(codePath);
14188        final String name = codeFile.getName();
14189        if (codeFile.isDirectory()) {
14190            return name;
14191        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14192            final int lastDot = name.lastIndexOf('.');
14193            return name.substring(0, lastDot);
14194        } else {
14195            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14196            return null;
14197        }
14198    }
14199
14200    static class PackageInstalledInfo {
14201        String name;
14202        int uid;
14203        // The set of users that originally had this package installed.
14204        int[] origUsers;
14205        // The set of users that now have this package installed.
14206        int[] newUsers;
14207        PackageParser.Package pkg;
14208        int returnCode;
14209        String returnMsg;
14210        PackageRemovedInfo removedInfo;
14211        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14212
14213        public void setError(int code, String msg) {
14214            setReturnCode(code);
14215            setReturnMessage(msg);
14216            Slog.w(TAG, msg);
14217        }
14218
14219        public void setError(String msg, PackageParserException e) {
14220            setReturnCode(e.error);
14221            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14222            Slog.w(TAG, msg, e);
14223        }
14224
14225        public void setError(String msg, PackageManagerException e) {
14226            returnCode = e.error;
14227            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14228            Slog.w(TAG, msg, e);
14229        }
14230
14231        public void setReturnCode(int returnCode) {
14232            this.returnCode = returnCode;
14233            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14234            for (int i = 0; i < childCount; i++) {
14235                addedChildPackages.valueAt(i).returnCode = returnCode;
14236            }
14237        }
14238
14239        private void setReturnMessage(String returnMsg) {
14240            this.returnMsg = returnMsg;
14241            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14242            for (int i = 0; i < childCount; i++) {
14243                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14244            }
14245        }
14246
14247        // In some error cases we want to convey more info back to the observer
14248        String origPackage;
14249        String origPermission;
14250    }
14251
14252    /*
14253     * Install a non-existing package.
14254     */
14255    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14256            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14257            PackageInstalledInfo res) {
14258        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14259
14260        // Remember this for later, in case we need to rollback this install
14261        String pkgName = pkg.packageName;
14262
14263        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14264
14265        synchronized(mPackages) {
14266            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14267                // A package with the same name is already installed, though
14268                // it has been renamed to an older name.  The package we
14269                // are trying to install should be installed as an update to
14270                // the existing one, but that has not been requested, so bail.
14271                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14272                        + " without first uninstalling package running as "
14273                        + mSettings.mRenamedPackages.get(pkgName));
14274                return;
14275            }
14276            if (mPackages.containsKey(pkgName)) {
14277                // Don't allow installation over an existing package with the same name.
14278                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14279                        + " without first uninstalling.");
14280                return;
14281            }
14282        }
14283
14284        try {
14285            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14286                    System.currentTimeMillis(), user);
14287
14288            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14289
14290            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14291                prepareAppDataAfterInstallLIF(newPackage);
14292
14293            } else {
14294                // Remove package from internal structures, but keep around any
14295                // data that might have already existed
14296                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14297                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14298            }
14299        } catch (PackageManagerException e) {
14300            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14301        }
14302
14303        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14304    }
14305
14306    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14307        // Can't rotate keys during boot or if sharedUser.
14308        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14309                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14310            return false;
14311        }
14312        // app is using upgradeKeySets; make sure all are valid
14313        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14314        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14315        for (int i = 0; i < upgradeKeySets.length; i++) {
14316            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14317                Slog.wtf(TAG, "Package "
14318                         + (oldPs.name != null ? oldPs.name : "<null>")
14319                         + " contains upgrade-key-set reference to unknown key-set: "
14320                         + upgradeKeySets[i]
14321                         + " reverting to signatures check.");
14322                return false;
14323            }
14324        }
14325        return true;
14326    }
14327
14328    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14329        // Upgrade keysets are being used.  Determine if new package has a superset of the
14330        // required keys.
14331        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14332        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14333        for (int i = 0; i < upgradeKeySets.length; i++) {
14334            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14335            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14336                return true;
14337            }
14338        }
14339        return false;
14340    }
14341
14342    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14343        try (DigestInputStream digestStream =
14344                new DigestInputStream(new FileInputStream(file), digest)) {
14345            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14346        }
14347    }
14348
14349    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14350            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14351        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14352
14353        final PackageParser.Package oldPackage;
14354        final String pkgName = pkg.packageName;
14355        final int[] allUsers;
14356        final int[] installedUsers;
14357
14358        synchronized(mPackages) {
14359            oldPackage = mPackages.get(pkgName);
14360            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14361
14362            // don't allow upgrade to target a release SDK from a pre-release SDK
14363            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14364                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14365            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14366                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14367            if (oldTargetsPreRelease
14368                    && !newTargetsPreRelease
14369                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14370                Slog.w(TAG, "Can't install package targeting released sdk");
14371                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14372                return;
14373            }
14374
14375            // don't allow an upgrade from full to ephemeral
14376            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14377            if (isEphemeral && !oldIsEphemeral) {
14378                // can't downgrade from full to ephemeral
14379                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14380                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14381                return;
14382            }
14383
14384            // verify signatures are valid
14385            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14386            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14387                if (!checkUpgradeKeySetLP(ps, pkg)) {
14388                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14389                            "New package not signed by keys specified by upgrade-keysets: "
14390                                    + pkgName);
14391                    return;
14392                }
14393            } else {
14394                // default to original signature matching
14395                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14396                        != PackageManager.SIGNATURE_MATCH) {
14397                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14398                            "New package has a different signature: " + pkgName);
14399                    return;
14400                }
14401            }
14402
14403            // don't allow a system upgrade unless the upgrade hash matches
14404            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14405                byte[] digestBytes = null;
14406                try {
14407                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14408                    updateDigest(digest, new File(pkg.baseCodePath));
14409                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14410                        for (String path : pkg.splitCodePaths) {
14411                            updateDigest(digest, new File(path));
14412                        }
14413                    }
14414                    digestBytes = digest.digest();
14415                } catch (NoSuchAlgorithmException | IOException e) {
14416                    res.setError(INSTALL_FAILED_INVALID_APK,
14417                            "Could not compute hash: " + pkgName);
14418                    return;
14419                }
14420                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14421                    res.setError(INSTALL_FAILED_INVALID_APK,
14422                            "New package fails restrict-update check: " + pkgName);
14423                    return;
14424                }
14425                // retain upgrade restriction
14426                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14427            }
14428
14429            // Check for shared user id changes
14430            String invalidPackageName =
14431                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14432            if (invalidPackageName != null) {
14433                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14434                        "Package " + invalidPackageName + " tried to change user "
14435                                + oldPackage.mSharedUserId);
14436                return;
14437            }
14438
14439            // In case of rollback, remember per-user/profile install state
14440            allUsers = sUserManager.getUserIds();
14441            installedUsers = ps.queryInstalledUsers(allUsers, true);
14442        }
14443
14444        // Update what is removed
14445        res.removedInfo = new PackageRemovedInfo();
14446        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14447        res.removedInfo.removedPackage = oldPackage.packageName;
14448        res.removedInfo.isUpdate = true;
14449        res.removedInfo.origUsers = installedUsers;
14450        final int childCount = (oldPackage.childPackages != null)
14451                ? oldPackage.childPackages.size() : 0;
14452        for (int i = 0; i < childCount; i++) {
14453            boolean childPackageUpdated = false;
14454            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14455            if (res.addedChildPackages != null) {
14456                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14457                if (childRes != null) {
14458                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14459                    childRes.removedInfo.removedPackage = childPkg.packageName;
14460                    childRes.removedInfo.isUpdate = true;
14461                    childPackageUpdated = true;
14462                }
14463            }
14464            if (!childPackageUpdated) {
14465                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14466                childRemovedRes.removedPackage = childPkg.packageName;
14467                childRemovedRes.isUpdate = false;
14468                childRemovedRes.dataRemoved = true;
14469                synchronized (mPackages) {
14470                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14471                    if (childPs != null) {
14472                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14473                    }
14474                }
14475                if (res.removedInfo.removedChildPackages == null) {
14476                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14477                }
14478                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14479            }
14480        }
14481
14482        boolean sysPkg = (isSystemApp(oldPackage));
14483        if (sysPkg) {
14484            // Set the system/privileged flags as needed
14485            final boolean privileged =
14486                    (oldPackage.applicationInfo.privateFlags
14487                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14488            final int systemPolicyFlags = policyFlags
14489                    | PackageParser.PARSE_IS_SYSTEM
14490                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14491
14492            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14493                    user, allUsers, installerPackageName, res);
14494        } else {
14495            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14496                    user, allUsers, installerPackageName, res);
14497        }
14498    }
14499
14500    public List<String> getPreviousCodePaths(String packageName) {
14501        final PackageSetting ps = mSettings.mPackages.get(packageName);
14502        final List<String> result = new ArrayList<String>();
14503        if (ps != null && ps.oldCodePaths != null) {
14504            result.addAll(ps.oldCodePaths);
14505        }
14506        return result;
14507    }
14508
14509    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14510            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14511            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14512        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14513                + deletedPackage);
14514
14515        String pkgName = deletedPackage.packageName;
14516        boolean deletedPkg = true;
14517        boolean addedPkg = false;
14518        boolean updatedSettings = false;
14519        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14520        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14521                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14522
14523        final long origUpdateTime = (pkg.mExtras != null)
14524                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14525
14526        // First delete the existing package while retaining the data directory
14527        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14528                res.removedInfo, true, pkg)) {
14529            // If the existing package wasn't successfully deleted
14530            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14531            deletedPkg = false;
14532        } else {
14533            // Successfully deleted the old package; proceed with replace.
14534
14535            // If deleted package lived in a container, give users a chance to
14536            // relinquish resources before killing.
14537            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14538                if (DEBUG_INSTALL) {
14539                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14540                }
14541                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14542                final ArrayList<String> pkgList = new ArrayList<String>(1);
14543                pkgList.add(deletedPackage.applicationInfo.packageName);
14544                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14545            }
14546
14547            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14548                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14549            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14550
14551            try {
14552                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14553                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14554                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14555
14556                // Update the in-memory copy of the previous code paths.
14557                PackageSetting ps = mSettings.mPackages.get(pkgName);
14558                if (!killApp) {
14559                    if (ps.oldCodePaths == null) {
14560                        ps.oldCodePaths = new ArraySet<>();
14561                    }
14562                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14563                    if (deletedPackage.splitCodePaths != null) {
14564                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14565                    }
14566                } else {
14567                    ps.oldCodePaths = null;
14568                }
14569                if (ps.childPackageNames != null) {
14570                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14571                        final String childPkgName = ps.childPackageNames.get(i);
14572                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14573                        childPs.oldCodePaths = ps.oldCodePaths;
14574                    }
14575                }
14576                prepareAppDataAfterInstallLIF(newPackage);
14577                addedPkg = true;
14578            } catch (PackageManagerException e) {
14579                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14580            }
14581        }
14582
14583        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14584            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14585
14586            // Revert all internal state mutations and added folders for the failed install
14587            if (addedPkg) {
14588                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14589                        res.removedInfo, true, null);
14590            }
14591
14592            // Restore the old package
14593            if (deletedPkg) {
14594                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14595                File restoreFile = new File(deletedPackage.codePath);
14596                // Parse old package
14597                boolean oldExternal = isExternal(deletedPackage);
14598                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14599                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14600                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14601                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14602                try {
14603                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14604                            null);
14605                } catch (PackageManagerException e) {
14606                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14607                            + e.getMessage());
14608                    return;
14609                }
14610
14611                synchronized (mPackages) {
14612                    // Ensure the installer package name up to date
14613                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14614
14615                    // Update permissions for restored package
14616                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14617
14618                    mSettings.writeLPr();
14619                }
14620
14621                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14622            }
14623        } else {
14624            synchronized (mPackages) {
14625                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14626                if (ps != null) {
14627                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14628                    if (res.removedInfo.removedChildPackages != null) {
14629                        final int childCount = res.removedInfo.removedChildPackages.size();
14630                        // Iterate in reverse as we may modify the collection
14631                        for (int i = childCount - 1; i >= 0; i--) {
14632                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14633                            if (res.addedChildPackages.containsKey(childPackageName)) {
14634                                res.removedInfo.removedChildPackages.removeAt(i);
14635                            } else {
14636                                PackageRemovedInfo childInfo = res.removedInfo
14637                                        .removedChildPackages.valueAt(i);
14638                                childInfo.removedForAllUsers = mPackages.get(
14639                                        childInfo.removedPackage) == null;
14640                            }
14641                        }
14642                    }
14643                }
14644            }
14645        }
14646    }
14647
14648    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14649            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14650            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14651        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14652                + ", old=" + deletedPackage);
14653
14654        final boolean disabledSystem;
14655
14656        // Remove existing system package
14657        removePackageLI(deletedPackage, true);
14658
14659        synchronized (mPackages) {
14660            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14661        }
14662        if (!disabledSystem) {
14663            // We didn't need to disable the .apk as a current system package,
14664            // which means we are replacing another update that is already
14665            // installed.  We need to make sure to delete the older one's .apk.
14666            res.removedInfo.args = createInstallArgsForExisting(0,
14667                    deletedPackage.applicationInfo.getCodePath(),
14668                    deletedPackage.applicationInfo.getResourcePath(),
14669                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14670        } else {
14671            res.removedInfo.args = null;
14672        }
14673
14674        // Successfully disabled the old package. Now proceed with re-installation
14675        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14676                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14677        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14678
14679        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14680        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14681                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14682
14683        PackageParser.Package newPackage = null;
14684        try {
14685            // Add the package to the internal data structures
14686            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14687
14688            // Set the update and install times
14689            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14690            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14691                    System.currentTimeMillis());
14692
14693            // Update the package dynamic state if succeeded
14694            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14695                // Now that the install succeeded make sure we remove data
14696                // directories for any child package the update removed.
14697                final int deletedChildCount = (deletedPackage.childPackages != null)
14698                        ? deletedPackage.childPackages.size() : 0;
14699                final int newChildCount = (newPackage.childPackages != null)
14700                        ? newPackage.childPackages.size() : 0;
14701                for (int i = 0; i < deletedChildCount; i++) {
14702                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14703                    boolean childPackageDeleted = true;
14704                    for (int j = 0; j < newChildCount; j++) {
14705                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14706                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14707                            childPackageDeleted = false;
14708                            break;
14709                        }
14710                    }
14711                    if (childPackageDeleted) {
14712                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14713                                deletedChildPkg.packageName);
14714                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14715                            PackageRemovedInfo removedChildRes = res.removedInfo
14716                                    .removedChildPackages.get(deletedChildPkg.packageName);
14717                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14718                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14719                        }
14720                    }
14721                }
14722
14723                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14724                prepareAppDataAfterInstallLIF(newPackage);
14725            }
14726        } catch (PackageManagerException e) {
14727            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14728            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14729        }
14730
14731        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14732            // Re installation failed. Restore old information
14733            // Remove new pkg information
14734            if (newPackage != null) {
14735                removeInstalledPackageLI(newPackage, true);
14736            }
14737            // Add back the old system package
14738            try {
14739                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14740            } catch (PackageManagerException e) {
14741                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14742            }
14743
14744            synchronized (mPackages) {
14745                if (disabledSystem) {
14746                    enableSystemPackageLPw(deletedPackage);
14747                }
14748
14749                // Ensure the installer package name up to date
14750                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14751
14752                // Update permissions for restored package
14753                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14754
14755                mSettings.writeLPr();
14756            }
14757
14758            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14759                    + " after failed upgrade");
14760        }
14761    }
14762
14763    /**
14764     * Checks whether the parent or any of the child packages have a change shared
14765     * user. For a package to be a valid update the shred users of the parent and
14766     * the children should match. We may later support changing child shared users.
14767     * @param oldPkg The updated package.
14768     * @param newPkg The update package.
14769     * @return The shared user that change between the versions.
14770     */
14771    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14772            PackageParser.Package newPkg) {
14773        // Check parent shared user
14774        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14775            return newPkg.packageName;
14776        }
14777        // Check child shared users
14778        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14779        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14780        for (int i = 0; i < newChildCount; i++) {
14781            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14782            // If this child was present, did it have the same shared user?
14783            for (int j = 0; j < oldChildCount; j++) {
14784                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14785                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14786                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14787                    return newChildPkg.packageName;
14788                }
14789            }
14790        }
14791        return null;
14792    }
14793
14794    private void removeNativeBinariesLI(PackageSetting ps) {
14795        // Remove the lib path for the parent package
14796        if (ps != null) {
14797            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14798            // Remove the lib path for the child packages
14799            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14800            for (int i = 0; i < childCount; i++) {
14801                PackageSetting childPs = null;
14802                synchronized (mPackages) {
14803                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14804                }
14805                if (childPs != null) {
14806                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14807                            .legacyNativeLibraryPathString);
14808                }
14809            }
14810        }
14811    }
14812
14813    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14814        // Enable the parent package
14815        mSettings.enableSystemPackageLPw(pkg.packageName);
14816        // Enable the child packages
14817        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14818        for (int i = 0; i < childCount; i++) {
14819            PackageParser.Package childPkg = pkg.childPackages.get(i);
14820            mSettings.enableSystemPackageLPw(childPkg.packageName);
14821        }
14822    }
14823
14824    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14825            PackageParser.Package newPkg) {
14826        // Disable the parent package (parent always replaced)
14827        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14828        // Disable the child packages
14829        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14830        for (int i = 0; i < childCount; i++) {
14831            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14832            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14833            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14834        }
14835        return disabled;
14836    }
14837
14838    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14839            String installerPackageName) {
14840        // Enable the parent package
14841        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14842        // Enable the child packages
14843        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14844        for (int i = 0; i < childCount; i++) {
14845            PackageParser.Package childPkg = pkg.childPackages.get(i);
14846            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14847        }
14848    }
14849
14850    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14851        // Collect all used permissions in the UID
14852        ArraySet<String> usedPermissions = new ArraySet<>();
14853        final int packageCount = su.packages.size();
14854        for (int i = 0; i < packageCount; i++) {
14855            PackageSetting ps = su.packages.valueAt(i);
14856            if (ps.pkg == null) {
14857                continue;
14858            }
14859            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14860            for (int j = 0; j < requestedPermCount; j++) {
14861                String permission = ps.pkg.requestedPermissions.get(j);
14862                BasePermission bp = mSettings.mPermissions.get(permission);
14863                if (bp != null) {
14864                    usedPermissions.add(permission);
14865                }
14866            }
14867        }
14868
14869        PermissionsState permissionsState = su.getPermissionsState();
14870        // Prune install permissions
14871        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14872        final int installPermCount = installPermStates.size();
14873        for (int i = installPermCount - 1; i >= 0;  i--) {
14874            PermissionState permissionState = installPermStates.get(i);
14875            if (!usedPermissions.contains(permissionState.getName())) {
14876                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14877                if (bp != null) {
14878                    permissionsState.revokeInstallPermission(bp);
14879                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14880                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14881                }
14882            }
14883        }
14884
14885        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14886
14887        // Prune runtime permissions
14888        for (int userId : allUserIds) {
14889            List<PermissionState> runtimePermStates = permissionsState
14890                    .getRuntimePermissionStates(userId);
14891            final int runtimePermCount = runtimePermStates.size();
14892            for (int i = runtimePermCount - 1; i >= 0; i--) {
14893                PermissionState permissionState = runtimePermStates.get(i);
14894                if (!usedPermissions.contains(permissionState.getName())) {
14895                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14896                    if (bp != null) {
14897                        permissionsState.revokeRuntimePermission(bp, userId);
14898                        permissionsState.updatePermissionFlags(bp, userId,
14899                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14900                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14901                                runtimePermissionChangedUserIds, userId);
14902                    }
14903                }
14904            }
14905        }
14906
14907        return runtimePermissionChangedUserIds;
14908    }
14909
14910    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14911            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14912        // Update the parent package setting
14913        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14914                res, user);
14915        // Update the child packages setting
14916        final int childCount = (newPackage.childPackages != null)
14917                ? newPackage.childPackages.size() : 0;
14918        for (int i = 0; i < childCount; i++) {
14919            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14920            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14921            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14922                    childRes.origUsers, childRes, user);
14923        }
14924    }
14925
14926    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14927            String installerPackageName, int[] allUsers, int[] installedForUsers,
14928            PackageInstalledInfo res, UserHandle user) {
14929        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14930
14931        String pkgName = newPackage.packageName;
14932        synchronized (mPackages) {
14933            //write settings. the installStatus will be incomplete at this stage.
14934            //note that the new package setting would have already been
14935            //added to mPackages. It hasn't been persisted yet.
14936            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14937            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14938            mSettings.writeLPr();
14939            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14940        }
14941
14942        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14943        synchronized (mPackages) {
14944            updatePermissionsLPw(newPackage.packageName, newPackage,
14945                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14946                            ? UPDATE_PERMISSIONS_ALL : 0));
14947            // For system-bundled packages, we assume that installing an upgraded version
14948            // of the package implies that the user actually wants to run that new code,
14949            // so we enable the package.
14950            PackageSetting ps = mSettings.mPackages.get(pkgName);
14951            final int userId = user.getIdentifier();
14952            if (ps != null) {
14953                if (isSystemApp(newPackage)) {
14954                    if (DEBUG_INSTALL) {
14955                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14956                    }
14957                    // Enable system package for requested users
14958                    if (res.origUsers != null) {
14959                        for (int origUserId : res.origUsers) {
14960                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14961                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14962                                        origUserId, installerPackageName);
14963                            }
14964                        }
14965                    }
14966                    // Also convey the prior install/uninstall state
14967                    if (allUsers != null && installedForUsers != null) {
14968                        for (int currentUserId : allUsers) {
14969                            final boolean installed = ArrayUtils.contains(
14970                                    installedForUsers, currentUserId);
14971                            if (DEBUG_INSTALL) {
14972                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14973                            }
14974                            ps.setInstalled(installed, currentUserId);
14975                        }
14976                        // these install state changes will be persisted in the
14977                        // upcoming call to mSettings.writeLPr().
14978                    }
14979                }
14980                // It's implied that when a user requests installation, they want the app to be
14981                // installed and enabled.
14982                if (userId != UserHandle.USER_ALL) {
14983                    ps.setInstalled(true, userId);
14984                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14985                }
14986            }
14987            res.name = pkgName;
14988            res.uid = newPackage.applicationInfo.uid;
14989            res.pkg = newPackage;
14990            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14991            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14992            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14993            //to update install status
14994            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14995            mSettings.writeLPr();
14996            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14997        }
14998
14999        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15000    }
15001
15002    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
15003        try {
15004            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
15005            installPackageLI(args, res);
15006        } finally {
15007            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15008        }
15009    }
15010
15011    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
15012        final int installFlags = args.installFlags;
15013        final String installerPackageName = args.installerPackageName;
15014        final String volumeUuid = args.volumeUuid;
15015        final File tmpPackageFile = new File(args.getCodePath());
15016        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
15017        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
15018                || (args.volumeUuid != null));
15019        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
15020        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
15021        boolean replace = false;
15022        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
15023        if (args.move != null) {
15024            // moving a complete application; perform an initial scan on the new install location
15025            scanFlags |= SCAN_INITIAL;
15026        }
15027        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
15028            scanFlags |= SCAN_DONT_KILL_APP;
15029        }
15030
15031        // Result object to be returned
15032        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15033
15034        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
15035
15036        // Sanity check
15037        if (ephemeral && (forwardLocked || onExternal)) {
15038            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
15039                    + " external=" + onExternal);
15040            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15041            return;
15042        }
15043
15044        // Retrieve PackageSettings and parse package
15045        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15046                | PackageParser.PARSE_ENFORCE_CODE
15047                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15048                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15049                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15050                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15051        PackageParser pp = new PackageParser();
15052        pp.setSeparateProcesses(mSeparateProcesses);
15053        pp.setDisplayMetrics(mMetrics);
15054
15055        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15056        final PackageParser.Package pkg;
15057        try {
15058            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15059        } catch (PackageParserException e) {
15060            res.setError("Failed parse during installPackageLI", e);
15061            return;
15062        } finally {
15063            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15064        }
15065
15066        // If we are installing a clustered package add results for the children
15067        if (pkg.childPackages != null) {
15068            synchronized (mPackages) {
15069                final int childCount = pkg.childPackages.size();
15070                for (int i = 0; i < childCount; i++) {
15071                    PackageParser.Package childPkg = pkg.childPackages.get(i);
15072                    PackageInstalledInfo childRes = new PackageInstalledInfo();
15073                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15074                    childRes.pkg = childPkg;
15075                    childRes.name = childPkg.packageName;
15076                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15077                    if (childPs != null) {
15078                        childRes.origUsers = childPs.queryInstalledUsers(
15079                                sUserManager.getUserIds(), true);
15080                    }
15081                    if ((mPackages.containsKey(childPkg.packageName))) {
15082                        childRes.removedInfo = new PackageRemovedInfo();
15083                        childRes.removedInfo.removedPackage = childPkg.packageName;
15084                    }
15085                    if (res.addedChildPackages == null) {
15086                        res.addedChildPackages = new ArrayMap<>();
15087                    }
15088                    res.addedChildPackages.put(childPkg.packageName, childRes);
15089                }
15090            }
15091        }
15092
15093        // If package doesn't declare API override, mark that we have an install
15094        // time CPU ABI override.
15095        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15096            pkg.cpuAbiOverride = args.abiOverride;
15097        }
15098
15099        String pkgName = res.name = pkg.packageName;
15100        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15101            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15102                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15103                return;
15104            }
15105        }
15106
15107        try {
15108            // either use what we've been given or parse directly from the APK
15109            if (args.certificates != null) {
15110                try {
15111                    PackageParser.populateCertificates(pkg, args.certificates);
15112                } catch (PackageParserException e) {
15113                    // there was something wrong with the certificates we were given;
15114                    // try to pull them from the APK
15115                    PackageParser.collectCertificates(pkg, parseFlags);
15116                }
15117            } else {
15118                PackageParser.collectCertificates(pkg, parseFlags);
15119            }
15120        } catch (PackageParserException e) {
15121            res.setError("Failed collect during installPackageLI", e);
15122            return;
15123        }
15124
15125        // Get rid of all references to package scan path via parser.
15126        pp = null;
15127        String oldCodePath = null;
15128        boolean systemApp = false;
15129        synchronized (mPackages) {
15130            // Check if installing already existing package
15131            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15132                String oldName = mSettings.mRenamedPackages.get(pkgName);
15133                if (pkg.mOriginalPackages != null
15134                        && pkg.mOriginalPackages.contains(oldName)
15135                        && mPackages.containsKey(oldName)) {
15136                    // This package is derived from an original package,
15137                    // and this device has been updating from that original
15138                    // name.  We must continue using the original name, so
15139                    // rename the new package here.
15140                    pkg.setPackageName(oldName);
15141                    pkgName = pkg.packageName;
15142                    replace = true;
15143                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15144                            + oldName + " pkgName=" + pkgName);
15145                } else if (mPackages.containsKey(pkgName)) {
15146                    // This package, under its official name, already exists
15147                    // on the device; we should replace it.
15148                    replace = true;
15149                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15150                }
15151
15152                // Child packages are installed through the parent package
15153                if (pkg.parentPackage != null) {
15154                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15155                            "Package " + pkg.packageName + " is child of package "
15156                                    + pkg.parentPackage.parentPackage + ". Child packages "
15157                                    + "can be updated only through the parent package.");
15158                    return;
15159                }
15160
15161                if (replace) {
15162                    // Prevent apps opting out from runtime permissions
15163                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15164                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15165                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15166                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15167                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15168                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15169                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15170                                        + " doesn't support runtime permissions but the old"
15171                                        + " target SDK " + oldTargetSdk + " does.");
15172                        return;
15173                    }
15174
15175                    // Prevent installing of child packages
15176                    if (oldPackage.parentPackage != null) {
15177                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15178                                "Package " + pkg.packageName + " is child of package "
15179                                        + oldPackage.parentPackage + ". Child packages "
15180                                        + "can be updated only through the parent package.");
15181                        return;
15182                    }
15183                }
15184            }
15185
15186            PackageSetting ps = mSettings.mPackages.get(pkgName);
15187            if (ps != null) {
15188                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15189
15190                // Quick sanity check that we're signed correctly if updating;
15191                // we'll check this again later when scanning, but we want to
15192                // bail early here before tripping over redefined permissions.
15193                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15194                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15195                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15196                                + pkg.packageName + " upgrade keys do not match the "
15197                                + "previously installed version");
15198                        return;
15199                    }
15200                } else {
15201                    try {
15202                        verifySignaturesLP(ps, pkg);
15203                    } catch (PackageManagerException e) {
15204                        res.setError(e.error, e.getMessage());
15205                        return;
15206                    }
15207                }
15208
15209                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15210                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15211                    systemApp = (ps.pkg.applicationInfo.flags &
15212                            ApplicationInfo.FLAG_SYSTEM) != 0;
15213                }
15214                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15215            }
15216
15217            // Check whether the newly-scanned package wants to define an already-defined perm
15218            int N = pkg.permissions.size();
15219            for (int i = N-1; i >= 0; i--) {
15220                PackageParser.Permission perm = pkg.permissions.get(i);
15221                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15222                if (bp != null) {
15223                    // If the defining package is signed with our cert, it's okay.  This
15224                    // also includes the "updating the same package" case, of course.
15225                    // "updating same package" could also involve key-rotation.
15226                    final boolean sigsOk;
15227                    if (bp.sourcePackage.equals(pkg.packageName)
15228                            && (bp.packageSetting instanceof PackageSetting)
15229                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15230                                    scanFlags))) {
15231                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15232                    } else {
15233                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15234                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15235                    }
15236                    if (!sigsOk) {
15237                        // If the owning package is the system itself, we log but allow
15238                        // install to proceed; we fail the install on all other permission
15239                        // redefinitions.
15240                        if (!bp.sourcePackage.equals("android")) {
15241                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15242                                    + pkg.packageName + " attempting to redeclare permission "
15243                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15244                            res.origPermission = perm.info.name;
15245                            res.origPackage = bp.sourcePackage;
15246                            return;
15247                        } else {
15248                            Slog.w(TAG, "Package " + pkg.packageName
15249                                    + " attempting to redeclare system permission "
15250                                    + perm.info.name + "; ignoring new declaration");
15251                            pkg.permissions.remove(i);
15252                        }
15253                    }
15254                }
15255            }
15256        }
15257
15258        if (systemApp) {
15259            if (onExternal) {
15260                // Abort update; system app can't be replaced with app on sdcard
15261                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15262                        "Cannot install updates to system apps on sdcard");
15263                return;
15264            } else if (ephemeral) {
15265                // Abort update; system app can't be replaced with an ephemeral app
15266                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15267                        "Cannot update a system app with an ephemeral app");
15268                return;
15269            }
15270        }
15271
15272        if (args.move != null) {
15273            // We did an in-place move, so dex is ready to roll
15274            scanFlags |= SCAN_NO_DEX;
15275            scanFlags |= SCAN_MOVE;
15276
15277            synchronized (mPackages) {
15278                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15279                if (ps == null) {
15280                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15281                            "Missing settings for moved package " + pkgName);
15282                }
15283
15284                // We moved the entire application as-is, so bring over the
15285                // previously derived ABI information.
15286                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15287                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15288            }
15289
15290        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15291            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15292            scanFlags |= SCAN_NO_DEX;
15293
15294            try {
15295                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15296                    args.abiOverride : pkg.cpuAbiOverride);
15297                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15298                        true /* extract libs */);
15299            } catch (PackageManagerException pme) {
15300                Slog.e(TAG, "Error deriving application ABI", pme);
15301                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15302                return;
15303            }
15304
15305            // Shared libraries for the package need to be updated.
15306            synchronized (mPackages) {
15307                try {
15308                    updateSharedLibrariesLPw(pkg, null);
15309                } catch (PackageManagerException e) {
15310                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15311                }
15312            }
15313            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15314            // Do not run PackageDexOptimizer through the local performDexOpt
15315            // method because `pkg` may not be in `mPackages` yet.
15316            //
15317            // Also, don't fail application installs if the dexopt step fails.
15318            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15319                    null /* instructionSets */, false /* checkProfiles */,
15320                    getCompilerFilterForReason(REASON_INSTALL),
15321                    getOrCreateCompilerPackageStats(pkg));
15322            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15323
15324            // Notify BackgroundDexOptService that the package has been changed.
15325            // If this is an update of a package which used to fail to compile,
15326            // BDOS will remove it from its blacklist.
15327            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15328        }
15329
15330        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15331            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15332            return;
15333        }
15334
15335        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15336
15337        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15338                "installPackageLI")) {
15339            if (replace) {
15340                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15341                        installerPackageName, res);
15342            } else {
15343                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15344                        args.user, installerPackageName, volumeUuid, res);
15345            }
15346        }
15347        synchronized (mPackages) {
15348            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15349            if (ps != null) {
15350                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15351            }
15352
15353            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15354            for (int i = 0; i < childCount; i++) {
15355                PackageParser.Package childPkg = pkg.childPackages.get(i);
15356                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15357                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15358                if (childPs != null) {
15359                    childRes.newUsers = childPs.queryInstalledUsers(
15360                            sUserManager.getUserIds(), true);
15361                }
15362            }
15363        }
15364    }
15365
15366    private void startIntentFilterVerifications(int userId, boolean replacing,
15367            PackageParser.Package pkg) {
15368        if (mIntentFilterVerifierComponent == null) {
15369            Slog.w(TAG, "No IntentFilter verification will not be done as "
15370                    + "there is no IntentFilterVerifier available!");
15371            return;
15372        }
15373
15374        final int verifierUid = getPackageUid(
15375                mIntentFilterVerifierComponent.getPackageName(),
15376                MATCH_DEBUG_TRIAGED_MISSING,
15377                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15378
15379        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15380        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15381        mHandler.sendMessage(msg);
15382
15383        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15384        for (int i = 0; i < childCount; i++) {
15385            PackageParser.Package childPkg = pkg.childPackages.get(i);
15386            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15387            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15388            mHandler.sendMessage(msg);
15389        }
15390    }
15391
15392    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15393            PackageParser.Package pkg) {
15394        int size = pkg.activities.size();
15395        if (size == 0) {
15396            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15397                    "No activity, so no need to verify any IntentFilter!");
15398            return;
15399        }
15400
15401        final boolean hasDomainURLs = hasDomainURLs(pkg);
15402        if (!hasDomainURLs) {
15403            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15404                    "No domain URLs, so no need to verify any IntentFilter!");
15405            return;
15406        }
15407
15408        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15409                + " if any IntentFilter from the " + size
15410                + " Activities needs verification ...");
15411
15412        int count = 0;
15413        final String packageName = pkg.packageName;
15414
15415        synchronized (mPackages) {
15416            // If this is a new install and we see that we've already run verification for this
15417            // package, we have nothing to do: it means the state was restored from backup.
15418            if (!replacing) {
15419                IntentFilterVerificationInfo ivi =
15420                        mSettings.getIntentFilterVerificationLPr(packageName);
15421                if (ivi != null) {
15422                    if (DEBUG_DOMAIN_VERIFICATION) {
15423                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15424                                + ivi.getStatusString());
15425                    }
15426                    return;
15427                }
15428            }
15429
15430            // If any filters need to be verified, then all need to be.
15431            boolean needToVerify = false;
15432            for (PackageParser.Activity a : pkg.activities) {
15433                for (ActivityIntentInfo filter : a.intents) {
15434                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15435                        if (DEBUG_DOMAIN_VERIFICATION) {
15436                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15437                        }
15438                        needToVerify = true;
15439                        break;
15440                    }
15441                }
15442            }
15443
15444            if (needToVerify) {
15445                final int verificationId = mIntentFilterVerificationToken++;
15446                for (PackageParser.Activity a : pkg.activities) {
15447                    for (ActivityIntentInfo filter : a.intents) {
15448                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15449                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15450                                    "Verification needed for IntentFilter:" + filter.toString());
15451                            mIntentFilterVerifier.addOneIntentFilterVerification(
15452                                    verifierUid, userId, verificationId, filter, packageName);
15453                            count++;
15454                        }
15455                    }
15456                }
15457            }
15458        }
15459
15460        if (count > 0) {
15461            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15462                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15463                    +  " for userId:" + userId);
15464            mIntentFilterVerifier.startVerifications(userId);
15465        } else {
15466            if (DEBUG_DOMAIN_VERIFICATION) {
15467                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15468            }
15469        }
15470    }
15471
15472    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15473        final ComponentName cn  = filter.activity.getComponentName();
15474        final String packageName = cn.getPackageName();
15475
15476        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15477                packageName);
15478        if (ivi == null) {
15479            return true;
15480        }
15481        int status = ivi.getStatus();
15482        switch (status) {
15483            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15484            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15485                return true;
15486
15487            default:
15488                // Nothing to do
15489                return false;
15490        }
15491    }
15492
15493    private static boolean isMultiArch(ApplicationInfo info) {
15494        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15495    }
15496
15497    private static boolean isExternal(PackageParser.Package pkg) {
15498        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15499    }
15500
15501    private static boolean isExternal(PackageSetting ps) {
15502        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15503    }
15504
15505    private static boolean isEphemeral(PackageParser.Package pkg) {
15506        return pkg.applicationInfo.isEphemeralApp();
15507    }
15508
15509    private static boolean isEphemeral(PackageSetting ps) {
15510        return ps.pkg != null && isEphemeral(ps.pkg);
15511    }
15512
15513    private static boolean isSystemApp(PackageParser.Package pkg) {
15514        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15515    }
15516
15517    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15518        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15519    }
15520
15521    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15522        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15523    }
15524
15525    private static boolean isSystemApp(PackageSetting ps) {
15526        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15527    }
15528
15529    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15530        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15531    }
15532
15533    private int packageFlagsToInstallFlags(PackageSetting ps) {
15534        int installFlags = 0;
15535        if (isEphemeral(ps)) {
15536            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15537        }
15538        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15539            // This existing package was an external ASEC install when we have
15540            // the external flag without a UUID
15541            installFlags |= PackageManager.INSTALL_EXTERNAL;
15542        }
15543        if (ps.isForwardLocked()) {
15544            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15545        }
15546        return installFlags;
15547    }
15548
15549    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15550        if (isExternal(pkg)) {
15551            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15552                return StorageManager.UUID_PRIMARY_PHYSICAL;
15553            } else {
15554                return pkg.volumeUuid;
15555            }
15556        } else {
15557            return StorageManager.UUID_PRIVATE_INTERNAL;
15558        }
15559    }
15560
15561    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15562        if (isExternal(pkg)) {
15563            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15564                return mSettings.getExternalVersion();
15565            } else {
15566                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15567            }
15568        } else {
15569            return mSettings.getInternalVersion();
15570        }
15571    }
15572
15573    private void deleteTempPackageFiles() {
15574        final FilenameFilter filter = new FilenameFilter() {
15575            public boolean accept(File dir, String name) {
15576                return name.startsWith("vmdl") && name.endsWith(".tmp");
15577            }
15578        };
15579        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15580            file.delete();
15581        }
15582    }
15583
15584    @Override
15585    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15586            int flags) {
15587        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15588                flags);
15589    }
15590
15591    @Override
15592    public void deletePackage(final String packageName,
15593            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15594        mContext.enforceCallingOrSelfPermission(
15595                android.Manifest.permission.DELETE_PACKAGES, null);
15596        Preconditions.checkNotNull(packageName);
15597        Preconditions.checkNotNull(observer);
15598        final int uid = Binder.getCallingUid();
15599        if (!isOrphaned(packageName)
15600                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15601            try {
15602                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15603                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15604                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15605                observer.onUserActionRequired(intent);
15606            } catch (RemoteException re) {
15607            }
15608            return;
15609        }
15610        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15611        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15612        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15613            mContext.enforceCallingOrSelfPermission(
15614                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15615                    "deletePackage for user " + userId);
15616        }
15617
15618        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15619            try {
15620                observer.onPackageDeleted(packageName,
15621                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15622            } catch (RemoteException re) {
15623            }
15624            return;
15625        }
15626
15627        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15628            try {
15629                observer.onPackageDeleted(packageName,
15630                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15631            } catch (RemoteException re) {
15632            }
15633            return;
15634        }
15635
15636        if (DEBUG_REMOVE) {
15637            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15638                    + " deleteAllUsers: " + deleteAllUsers );
15639        }
15640        // Queue up an async operation since the package deletion may take a little while.
15641        mHandler.post(new Runnable() {
15642            public void run() {
15643                mHandler.removeCallbacks(this);
15644                int returnCode;
15645                if (!deleteAllUsers) {
15646                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15647                } else {
15648                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15649                    // If nobody is blocking uninstall, proceed with delete for all users
15650                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15651                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15652                    } else {
15653                        // Otherwise uninstall individually for users with blockUninstalls=false
15654                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15655                        for (int userId : users) {
15656                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15657                                returnCode = deletePackageX(packageName, userId, userFlags);
15658                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15659                                    Slog.w(TAG, "Package delete failed for user " + userId
15660                                            + ", returnCode " + returnCode);
15661                                }
15662                            }
15663                        }
15664                        // The app has only been marked uninstalled for certain users.
15665                        // We still need to report that delete was blocked
15666                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15667                    }
15668                }
15669                try {
15670                    observer.onPackageDeleted(packageName, returnCode, null);
15671                } catch (RemoteException e) {
15672                    Log.i(TAG, "Observer no longer exists.");
15673                } //end catch
15674            } //end run
15675        });
15676    }
15677
15678    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15679        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15680              || callingUid == Process.SYSTEM_UID) {
15681            return true;
15682        }
15683        final int callingUserId = UserHandle.getUserId(callingUid);
15684        // If the caller installed the pkgName, then allow it to silently uninstall.
15685        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15686            return true;
15687        }
15688
15689        // Allow package verifier to silently uninstall.
15690        if (mRequiredVerifierPackage != null &&
15691                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15692            return true;
15693        }
15694
15695        // Allow package uninstaller to silently uninstall.
15696        if (mRequiredUninstallerPackage != null &&
15697                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15698            return true;
15699        }
15700
15701        // Allow storage manager to silently uninstall.
15702        if (mStorageManagerPackage != null &&
15703                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
15704            return true;
15705        }
15706        return false;
15707    }
15708
15709    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15710        int[] result = EMPTY_INT_ARRAY;
15711        for (int userId : userIds) {
15712            if (getBlockUninstallForUser(packageName, userId)) {
15713                result = ArrayUtils.appendInt(result, userId);
15714            }
15715        }
15716        return result;
15717    }
15718
15719    @Override
15720    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15721        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15722    }
15723
15724    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15725        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15726                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15727        try {
15728            if (dpm != null) {
15729                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15730                        /* callingUserOnly =*/ false);
15731                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15732                        : deviceOwnerComponentName.getPackageName();
15733                // Does the package contains the device owner?
15734                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15735                // this check is probably not needed, since DO should be registered as a device
15736                // admin on some user too. (Original bug for this: b/17657954)
15737                if (packageName.equals(deviceOwnerPackageName)) {
15738                    return true;
15739                }
15740                // Does it contain a device admin for any user?
15741                int[] users;
15742                if (userId == UserHandle.USER_ALL) {
15743                    users = sUserManager.getUserIds();
15744                } else {
15745                    users = new int[]{userId};
15746                }
15747                for (int i = 0; i < users.length; ++i) {
15748                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15749                        return true;
15750                    }
15751                }
15752            }
15753        } catch (RemoteException e) {
15754        }
15755        return false;
15756    }
15757
15758    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15759        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15760    }
15761
15762    /**
15763     *  This method is an internal method that could be get invoked either
15764     *  to delete an installed package or to clean up a failed installation.
15765     *  After deleting an installed package, a broadcast is sent to notify any
15766     *  listeners that the package has been removed. For cleaning up a failed
15767     *  installation, the broadcast is not necessary since the package's
15768     *  installation wouldn't have sent the initial broadcast either
15769     *  The key steps in deleting a package are
15770     *  deleting the package information in internal structures like mPackages,
15771     *  deleting the packages base directories through installd
15772     *  updating mSettings to reflect current status
15773     *  persisting settings for later use
15774     *  sending a broadcast if necessary
15775     */
15776    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15777        final PackageRemovedInfo info = new PackageRemovedInfo();
15778        final boolean res;
15779
15780        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15781                ? UserHandle.USER_ALL : userId;
15782
15783        if (isPackageDeviceAdmin(packageName, removeUser)) {
15784            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15785            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15786        }
15787
15788        PackageSetting uninstalledPs = null;
15789
15790        // for the uninstall-updates case and restricted profiles, remember the per-
15791        // user handle installed state
15792        int[] allUsers;
15793        synchronized (mPackages) {
15794            uninstalledPs = mSettings.mPackages.get(packageName);
15795            if (uninstalledPs == null) {
15796                Slog.w(TAG, "Not removing non-existent package " + packageName);
15797                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15798            }
15799            allUsers = sUserManager.getUserIds();
15800            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15801        }
15802
15803        final int freezeUser;
15804        if (isUpdatedSystemApp(uninstalledPs)
15805                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15806            // We're downgrading a system app, which will apply to all users, so
15807            // freeze them all during the downgrade
15808            freezeUser = UserHandle.USER_ALL;
15809        } else {
15810            freezeUser = removeUser;
15811        }
15812
15813        synchronized (mInstallLock) {
15814            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15815            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15816                    deleteFlags, "deletePackageX")) {
15817                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15818                        deleteFlags | REMOVE_CHATTY, info, true, null);
15819            }
15820            synchronized (mPackages) {
15821                if (res) {
15822                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15823                }
15824            }
15825        }
15826
15827        if (res) {
15828            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15829            info.sendPackageRemovedBroadcasts(killApp);
15830            info.sendSystemPackageUpdatedBroadcasts();
15831            info.sendSystemPackageAppearedBroadcasts();
15832        }
15833        // Force a gc here.
15834        Runtime.getRuntime().gc();
15835        // Delete the resources here after sending the broadcast to let
15836        // other processes clean up before deleting resources.
15837        if (info.args != null) {
15838            synchronized (mInstallLock) {
15839                info.args.doPostDeleteLI(true);
15840            }
15841        }
15842
15843        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15844    }
15845
15846    class PackageRemovedInfo {
15847        String removedPackage;
15848        int uid = -1;
15849        int removedAppId = -1;
15850        int[] origUsers;
15851        int[] removedUsers = null;
15852        boolean isRemovedPackageSystemUpdate = false;
15853        boolean isUpdate;
15854        boolean dataRemoved;
15855        boolean removedForAllUsers;
15856        // Clean up resources deleted packages.
15857        InstallArgs args = null;
15858        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15859        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15860
15861        void sendPackageRemovedBroadcasts(boolean killApp) {
15862            sendPackageRemovedBroadcastInternal(killApp);
15863            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15864            for (int i = 0; i < childCount; i++) {
15865                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15866                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15867            }
15868        }
15869
15870        void sendSystemPackageUpdatedBroadcasts() {
15871            if (isRemovedPackageSystemUpdate) {
15872                sendSystemPackageUpdatedBroadcastsInternal();
15873                final int childCount = (removedChildPackages != null)
15874                        ? removedChildPackages.size() : 0;
15875                for (int i = 0; i < childCount; i++) {
15876                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15877                    if (childInfo.isRemovedPackageSystemUpdate) {
15878                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15879                    }
15880                }
15881            }
15882        }
15883
15884        void sendSystemPackageAppearedBroadcasts() {
15885            final int packageCount = (appearedChildPackages != null)
15886                    ? appearedChildPackages.size() : 0;
15887            for (int i = 0; i < packageCount; i++) {
15888                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15889                for (int userId : installedInfo.newUsers) {
15890                    sendPackageAddedForUser(installedInfo.name, true,
15891                            UserHandle.getAppId(installedInfo.uid), userId);
15892                }
15893            }
15894        }
15895
15896        private void sendSystemPackageUpdatedBroadcastsInternal() {
15897            Bundle extras = new Bundle(2);
15898            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15899            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15900            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15901                    extras, 0, null, null, null);
15902            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15903                    extras, 0, null, null, null);
15904            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15905                    null, 0, removedPackage, null, null);
15906        }
15907
15908        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15909            Bundle extras = new Bundle(2);
15910            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15911            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15912            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15913            if (isUpdate || isRemovedPackageSystemUpdate) {
15914                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15915            }
15916            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15917            if (removedPackage != null) {
15918                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15919                        extras, 0, null, null, removedUsers);
15920                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15921                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15922                            removedPackage, extras, 0, null, null, removedUsers);
15923                }
15924            }
15925            if (removedAppId >= 0) {
15926                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15927                        removedUsers);
15928            }
15929        }
15930    }
15931
15932    /*
15933     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15934     * flag is not set, the data directory is removed as well.
15935     * make sure this flag is set for partially installed apps. If not its meaningless to
15936     * delete a partially installed application.
15937     */
15938    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15939            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15940        String packageName = ps.name;
15941        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15942        // Retrieve object to delete permissions for shared user later on
15943        final PackageParser.Package deletedPkg;
15944        final PackageSetting deletedPs;
15945        // reader
15946        synchronized (mPackages) {
15947            deletedPkg = mPackages.get(packageName);
15948            deletedPs = mSettings.mPackages.get(packageName);
15949            if (outInfo != null) {
15950                outInfo.removedPackage = packageName;
15951                outInfo.removedUsers = deletedPs != null
15952                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15953                        : null;
15954            }
15955        }
15956
15957        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15958
15959        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15960            final PackageParser.Package resolvedPkg;
15961            if (deletedPkg != null) {
15962                resolvedPkg = deletedPkg;
15963            } else {
15964                // We don't have a parsed package when it lives on an ejected
15965                // adopted storage device, so fake something together
15966                resolvedPkg = new PackageParser.Package(ps.name);
15967                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15968            }
15969            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15970                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15971            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15972            if (outInfo != null) {
15973                outInfo.dataRemoved = true;
15974            }
15975            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15976        }
15977
15978        // writer
15979        synchronized (mPackages) {
15980            if (deletedPs != null) {
15981                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15982                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15983                    clearDefaultBrowserIfNeeded(packageName);
15984                    if (outInfo != null) {
15985                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15986                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15987                    }
15988                    updatePermissionsLPw(deletedPs.name, null, 0);
15989                    if (deletedPs.sharedUser != null) {
15990                        // Remove permissions associated with package. Since runtime
15991                        // permissions are per user we have to kill the removed package
15992                        // or packages running under the shared user of the removed
15993                        // package if revoking the permissions requested only by the removed
15994                        // package is successful and this causes a change in gids.
15995                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15996                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15997                                    userId);
15998                            if (userIdToKill == UserHandle.USER_ALL
15999                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
16000                                // If gids changed for this user, kill all affected packages.
16001                                mHandler.post(new Runnable() {
16002                                    @Override
16003                                    public void run() {
16004                                        // This has to happen with no lock held.
16005                                        killApplication(deletedPs.name, deletedPs.appId,
16006                                                KILL_APP_REASON_GIDS_CHANGED);
16007                                    }
16008                                });
16009                                break;
16010                            }
16011                        }
16012                    }
16013                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
16014                }
16015                // make sure to preserve per-user disabled state if this removal was just
16016                // a downgrade of a system app to the factory package
16017                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
16018                    if (DEBUG_REMOVE) {
16019                        Slog.d(TAG, "Propagating install state across downgrade");
16020                    }
16021                    for (int userId : allUserHandles) {
16022                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16023                        if (DEBUG_REMOVE) {
16024                            Slog.d(TAG, "    user " + userId + " => " + installed);
16025                        }
16026                        ps.setInstalled(installed, userId);
16027                    }
16028                }
16029            }
16030            // can downgrade to reader
16031            if (writeSettings) {
16032                // Save settings now
16033                mSettings.writeLPr();
16034            }
16035        }
16036        if (outInfo != null) {
16037            // A user ID was deleted here. Go through all users and remove it
16038            // from KeyStore.
16039            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
16040        }
16041    }
16042
16043    static boolean locationIsPrivileged(File path) {
16044        try {
16045            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16046                    .getCanonicalPath();
16047            return path.getCanonicalPath().startsWith(privilegedAppDir);
16048        } catch (IOException e) {
16049            Slog.e(TAG, "Unable to access code path " + path);
16050        }
16051        return false;
16052    }
16053
16054    /*
16055     * Tries to delete system package.
16056     */
16057    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16058            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16059            boolean writeSettings) {
16060        if (deletedPs.parentPackageName != null) {
16061            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16062            return false;
16063        }
16064
16065        final boolean applyUserRestrictions
16066                = (allUserHandles != null) && (outInfo.origUsers != null);
16067        final PackageSetting disabledPs;
16068        // Confirm if the system package has been updated
16069        // An updated system app can be deleted. This will also have to restore
16070        // the system pkg from system partition
16071        // reader
16072        synchronized (mPackages) {
16073            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16074        }
16075
16076        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16077                + " disabledPs=" + disabledPs);
16078
16079        if (disabledPs == null) {
16080            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16081            return false;
16082        } else if (DEBUG_REMOVE) {
16083            Slog.d(TAG, "Deleting system pkg from data partition");
16084        }
16085
16086        if (DEBUG_REMOVE) {
16087            if (applyUserRestrictions) {
16088                Slog.d(TAG, "Remembering install states:");
16089                for (int userId : allUserHandles) {
16090                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16091                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
16092                }
16093            }
16094        }
16095
16096        // Delete the updated package
16097        outInfo.isRemovedPackageSystemUpdate = true;
16098        if (outInfo.removedChildPackages != null) {
16099            final int childCount = (deletedPs.childPackageNames != null)
16100                    ? deletedPs.childPackageNames.size() : 0;
16101            for (int i = 0; i < childCount; i++) {
16102                String childPackageName = deletedPs.childPackageNames.get(i);
16103                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16104                        .contains(childPackageName)) {
16105                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16106                            childPackageName);
16107                    if (childInfo != null) {
16108                        childInfo.isRemovedPackageSystemUpdate = true;
16109                    }
16110                }
16111            }
16112        }
16113
16114        if (disabledPs.versionCode < deletedPs.versionCode) {
16115            // Delete data for downgrades
16116            flags &= ~PackageManager.DELETE_KEEP_DATA;
16117        } else {
16118            // Preserve data by setting flag
16119            flags |= PackageManager.DELETE_KEEP_DATA;
16120        }
16121
16122        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16123                outInfo, writeSettings, disabledPs.pkg);
16124        if (!ret) {
16125            return false;
16126        }
16127
16128        // writer
16129        synchronized (mPackages) {
16130            // Reinstate the old system package
16131            enableSystemPackageLPw(disabledPs.pkg);
16132            // Remove any native libraries from the upgraded package.
16133            removeNativeBinariesLI(deletedPs);
16134        }
16135
16136        // Install the system package
16137        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16138        int parseFlags = mDefParseFlags
16139                | PackageParser.PARSE_MUST_BE_APK
16140                | PackageParser.PARSE_IS_SYSTEM
16141                | PackageParser.PARSE_IS_SYSTEM_DIR;
16142        if (locationIsPrivileged(disabledPs.codePath)) {
16143            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16144        }
16145
16146        final PackageParser.Package newPkg;
16147        try {
16148            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16149        } catch (PackageManagerException e) {
16150            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16151                    + e.getMessage());
16152            return false;
16153        }
16154        try {
16155            // update shared libraries for the newly re-installed system package
16156            updateSharedLibrariesLPw(newPkg, null);
16157        } catch (PackageManagerException e) {
16158            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16159        }
16160
16161        prepareAppDataAfterInstallLIF(newPkg);
16162
16163        // writer
16164        synchronized (mPackages) {
16165            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16166
16167            // Propagate the permissions state as we do not want to drop on the floor
16168            // runtime permissions. The update permissions method below will take
16169            // care of removing obsolete permissions and grant install permissions.
16170            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16171            updatePermissionsLPw(newPkg.packageName, newPkg,
16172                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16173
16174            if (applyUserRestrictions) {
16175                if (DEBUG_REMOVE) {
16176                    Slog.d(TAG, "Propagating install state across reinstall");
16177                }
16178                for (int userId : allUserHandles) {
16179                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16180                    if (DEBUG_REMOVE) {
16181                        Slog.d(TAG, "    user " + userId + " => " + installed);
16182                    }
16183                    ps.setInstalled(installed, userId);
16184
16185                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16186                }
16187                // Regardless of writeSettings we need to ensure that this restriction
16188                // state propagation is persisted
16189                mSettings.writeAllUsersPackageRestrictionsLPr();
16190            }
16191            // can downgrade to reader here
16192            if (writeSettings) {
16193                mSettings.writeLPr();
16194            }
16195        }
16196        return true;
16197    }
16198
16199    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16200            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16201            PackageRemovedInfo outInfo, boolean writeSettings,
16202            PackageParser.Package replacingPackage) {
16203        synchronized (mPackages) {
16204            if (outInfo != null) {
16205                outInfo.uid = ps.appId;
16206            }
16207
16208            if (outInfo != null && outInfo.removedChildPackages != null) {
16209                final int childCount = (ps.childPackageNames != null)
16210                        ? ps.childPackageNames.size() : 0;
16211                for (int i = 0; i < childCount; i++) {
16212                    String childPackageName = ps.childPackageNames.get(i);
16213                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16214                    if (childPs == null) {
16215                        return false;
16216                    }
16217                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16218                            childPackageName);
16219                    if (childInfo != null) {
16220                        childInfo.uid = childPs.appId;
16221                    }
16222                }
16223            }
16224        }
16225
16226        // Delete package data from internal structures and also remove data if flag is set
16227        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16228
16229        // Delete the child packages data
16230        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16231        for (int i = 0; i < childCount; i++) {
16232            PackageSetting childPs;
16233            synchronized (mPackages) {
16234                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16235            }
16236            if (childPs != null) {
16237                PackageRemovedInfo childOutInfo = (outInfo != null
16238                        && outInfo.removedChildPackages != null)
16239                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16240                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16241                        && (replacingPackage != null
16242                        && !replacingPackage.hasChildPackage(childPs.name))
16243                        ? flags & ~DELETE_KEEP_DATA : flags;
16244                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16245                        deleteFlags, writeSettings);
16246            }
16247        }
16248
16249        // Delete application code and resources only for parent packages
16250        if (ps.parentPackageName == null) {
16251            if (deleteCodeAndResources && (outInfo != null)) {
16252                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16253                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16254                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16255            }
16256        }
16257
16258        return true;
16259    }
16260
16261    @Override
16262    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16263            int userId) {
16264        mContext.enforceCallingOrSelfPermission(
16265                android.Manifest.permission.DELETE_PACKAGES, null);
16266        synchronized (mPackages) {
16267            PackageSetting ps = mSettings.mPackages.get(packageName);
16268            if (ps == null) {
16269                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16270                return false;
16271            }
16272            if (!ps.getInstalled(userId)) {
16273                // Can't block uninstall for an app that is not installed or enabled.
16274                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16275                return false;
16276            }
16277            ps.setBlockUninstall(blockUninstall, userId);
16278            mSettings.writePackageRestrictionsLPr(userId);
16279        }
16280        return true;
16281    }
16282
16283    @Override
16284    public boolean getBlockUninstallForUser(String packageName, int userId) {
16285        synchronized (mPackages) {
16286            PackageSetting ps = mSettings.mPackages.get(packageName);
16287            if (ps == null) {
16288                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16289                return false;
16290            }
16291            return ps.getBlockUninstall(userId);
16292        }
16293    }
16294
16295    @Override
16296    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16297        int callingUid = Binder.getCallingUid();
16298        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16299            throw new SecurityException(
16300                    "setRequiredForSystemUser can only be run by the system or root");
16301        }
16302        synchronized (mPackages) {
16303            PackageSetting ps = mSettings.mPackages.get(packageName);
16304            if (ps == null) {
16305                Log.w(TAG, "Package doesn't exist: " + packageName);
16306                return false;
16307            }
16308            if (systemUserApp) {
16309                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16310            } else {
16311                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16312            }
16313            mSettings.writeLPr();
16314        }
16315        return true;
16316    }
16317
16318    /*
16319     * This method handles package deletion in general
16320     */
16321    private boolean deletePackageLIF(String packageName, UserHandle user,
16322            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16323            PackageRemovedInfo outInfo, boolean writeSettings,
16324            PackageParser.Package replacingPackage) {
16325        if (packageName == null) {
16326            Slog.w(TAG, "Attempt to delete null packageName.");
16327            return false;
16328        }
16329
16330        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16331
16332        PackageSetting ps;
16333
16334        synchronized (mPackages) {
16335            ps = mSettings.mPackages.get(packageName);
16336            if (ps == null) {
16337                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16338                return false;
16339            }
16340
16341            if (ps.parentPackageName != null && (!isSystemApp(ps)
16342                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16343                if (DEBUG_REMOVE) {
16344                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16345                            + ((user == null) ? UserHandle.USER_ALL : user));
16346                }
16347                final int removedUserId = (user != null) ? user.getIdentifier()
16348                        : UserHandle.USER_ALL;
16349                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16350                    return false;
16351                }
16352                markPackageUninstalledForUserLPw(ps, user);
16353                scheduleWritePackageRestrictionsLocked(user);
16354                return true;
16355            }
16356        }
16357
16358        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16359                && user.getIdentifier() != UserHandle.USER_ALL)) {
16360            // The caller is asking that the package only be deleted for a single
16361            // user.  To do this, we just mark its uninstalled state and delete
16362            // its data. If this is a system app, we only allow this to happen if
16363            // they have set the special DELETE_SYSTEM_APP which requests different
16364            // semantics than normal for uninstalling system apps.
16365            markPackageUninstalledForUserLPw(ps, user);
16366
16367            if (!isSystemApp(ps)) {
16368                // Do not uninstall the APK if an app should be cached
16369                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16370                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16371                    // Other user still have this package installed, so all
16372                    // we need to do is clear this user's data and save that
16373                    // it is uninstalled.
16374                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16375                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16376                        return false;
16377                    }
16378                    scheduleWritePackageRestrictionsLocked(user);
16379                    return true;
16380                } else {
16381                    // We need to set it back to 'installed' so the uninstall
16382                    // broadcasts will be sent correctly.
16383                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16384                    ps.setInstalled(true, user.getIdentifier());
16385                }
16386            } else {
16387                // This is a system app, so we assume that the
16388                // other users still have this package installed, so all
16389                // we need to do is clear this user's data and save that
16390                // it is uninstalled.
16391                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16392                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16393                    return false;
16394                }
16395                scheduleWritePackageRestrictionsLocked(user);
16396                return true;
16397            }
16398        }
16399
16400        // If we are deleting a composite package for all users, keep track
16401        // of result for each child.
16402        if (ps.childPackageNames != null && outInfo != null) {
16403            synchronized (mPackages) {
16404                final int childCount = ps.childPackageNames.size();
16405                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16406                for (int i = 0; i < childCount; i++) {
16407                    String childPackageName = ps.childPackageNames.get(i);
16408                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16409                    childInfo.removedPackage = childPackageName;
16410                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16411                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16412                    if (childPs != null) {
16413                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16414                    }
16415                }
16416            }
16417        }
16418
16419        boolean ret = false;
16420        if (isSystemApp(ps)) {
16421            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16422            // When an updated system application is deleted we delete the existing resources
16423            // as well and fall back to existing code in system partition
16424            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16425        } else {
16426            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16427            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16428                    outInfo, writeSettings, replacingPackage);
16429        }
16430
16431        // Take a note whether we deleted the package for all users
16432        if (outInfo != null) {
16433            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16434            if (outInfo.removedChildPackages != null) {
16435                synchronized (mPackages) {
16436                    final int childCount = outInfo.removedChildPackages.size();
16437                    for (int i = 0; i < childCount; i++) {
16438                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16439                        if (childInfo != null) {
16440                            childInfo.removedForAllUsers = mPackages.get(
16441                                    childInfo.removedPackage) == null;
16442                        }
16443                    }
16444                }
16445            }
16446            // If we uninstalled an update to a system app there may be some
16447            // child packages that appeared as they are declared in the system
16448            // app but were not declared in the update.
16449            if (isSystemApp(ps)) {
16450                synchronized (mPackages) {
16451                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16452                    final int childCount = (updatedPs.childPackageNames != null)
16453                            ? updatedPs.childPackageNames.size() : 0;
16454                    for (int i = 0; i < childCount; i++) {
16455                        String childPackageName = updatedPs.childPackageNames.get(i);
16456                        if (outInfo.removedChildPackages == null
16457                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16458                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16459                            if (childPs == null) {
16460                                continue;
16461                            }
16462                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16463                            installRes.name = childPackageName;
16464                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16465                            installRes.pkg = mPackages.get(childPackageName);
16466                            installRes.uid = childPs.pkg.applicationInfo.uid;
16467                            if (outInfo.appearedChildPackages == null) {
16468                                outInfo.appearedChildPackages = new ArrayMap<>();
16469                            }
16470                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16471                        }
16472                    }
16473                }
16474            }
16475        }
16476
16477        return ret;
16478    }
16479
16480    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16481        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16482                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16483        for (int nextUserId : userIds) {
16484            if (DEBUG_REMOVE) {
16485                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16486            }
16487            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16488                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16489                    false /*hidden*/, false /*suspended*/, null, null, null,
16490                    false /*blockUninstall*/,
16491                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16492        }
16493    }
16494
16495    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16496            PackageRemovedInfo outInfo) {
16497        final PackageParser.Package pkg;
16498        synchronized (mPackages) {
16499            pkg = mPackages.get(ps.name);
16500        }
16501
16502        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16503                : new int[] {userId};
16504        for (int nextUserId : userIds) {
16505            if (DEBUG_REMOVE) {
16506                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16507                        + nextUserId);
16508            }
16509
16510            destroyAppDataLIF(pkg, userId,
16511                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16512            destroyAppProfilesLIF(pkg, userId);
16513            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16514            schedulePackageCleaning(ps.name, nextUserId, false);
16515            synchronized (mPackages) {
16516                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16517                    scheduleWritePackageRestrictionsLocked(nextUserId);
16518                }
16519                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16520            }
16521        }
16522
16523        if (outInfo != null) {
16524            outInfo.removedPackage = ps.name;
16525            outInfo.removedAppId = ps.appId;
16526            outInfo.removedUsers = userIds;
16527        }
16528
16529        return true;
16530    }
16531
16532    private final class ClearStorageConnection implements ServiceConnection {
16533        IMediaContainerService mContainerService;
16534
16535        @Override
16536        public void onServiceConnected(ComponentName name, IBinder service) {
16537            synchronized (this) {
16538                mContainerService = IMediaContainerService.Stub.asInterface(service);
16539                notifyAll();
16540            }
16541        }
16542
16543        @Override
16544        public void onServiceDisconnected(ComponentName name) {
16545        }
16546    }
16547
16548    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16549        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16550
16551        final boolean mounted;
16552        if (Environment.isExternalStorageEmulated()) {
16553            mounted = true;
16554        } else {
16555            final String status = Environment.getExternalStorageState();
16556
16557            mounted = status.equals(Environment.MEDIA_MOUNTED)
16558                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16559        }
16560
16561        if (!mounted) {
16562            return;
16563        }
16564
16565        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16566        int[] users;
16567        if (userId == UserHandle.USER_ALL) {
16568            users = sUserManager.getUserIds();
16569        } else {
16570            users = new int[] { userId };
16571        }
16572        final ClearStorageConnection conn = new ClearStorageConnection();
16573        if (mContext.bindServiceAsUser(
16574                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16575            try {
16576                for (int curUser : users) {
16577                    long timeout = SystemClock.uptimeMillis() + 5000;
16578                    synchronized (conn) {
16579                        long now;
16580                        while (conn.mContainerService == null &&
16581                                (now = SystemClock.uptimeMillis()) < timeout) {
16582                            try {
16583                                conn.wait(timeout - now);
16584                            } catch (InterruptedException e) {
16585                            }
16586                        }
16587                    }
16588                    if (conn.mContainerService == null) {
16589                        return;
16590                    }
16591
16592                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16593                    clearDirectory(conn.mContainerService,
16594                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16595                    if (allData) {
16596                        clearDirectory(conn.mContainerService,
16597                                userEnv.buildExternalStorageAppDataDirs(packageName));
16598                        clearDirectory(conn.mContainerService,
16599                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16600                    }
16601                }
16602            } finally {
16603                mContext.unbindService(conn);
16604            }
16605        }
16606    }
16607
16608    @Override
16609    public void clearApplicationProfileData(String packageName) {
16610        enforceSystemOrRoot("Only the system can clear all profile data");
16611
16612        final PackageParser.Package pkg;
16613        synchronized (mPackages) {
16614            pkg = mPackages.get(packageName);
16615        }
16616
16617        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16618            synchronized (mInstallLock) {
16619                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16620                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16621                        true /* removeBaseMarker */);
16622            }
16623        }
16624    }
16625
16626    @Override
16627    public void clearApplicationUserData(final String packageName,
16628            final IPackageDataObserver observer, final int userId) {
16629        mContext.enforceCallingOrSelfPermission(
16630                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16631
16632        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16633                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16634
16635        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16636            throw new SecurityException("Cannot clear data for a protected package: "
16637                    + packageName);
16638        }
16639        // Queue up an async operation since the package deletion may take a little while.
16640        mHandler.post(new Runnable() {
16641            public void run() {
16642                mHandler.removeCallbacks(this);
16643                final boolean succeeded;
16644                try (PackageFreezer freezer = freezePackage(packageName,
16645                        "clearApplicationUserData")) {
16646                    synchronized (mInstallLock) {
16647                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16648                    }
16649                    clearExternalStorageDataSync(packageName, userId, true);
16650                }
16651                if (succeeded) {
16652                    // invoke DeviceStorageMonitor's update method to clear any notifications
16653                    DeviceStorageMonitorInternal dsm = LocalServices
16654                            .getService(DeviceStorageMonitorInternal.class);
16655                    if (dsm != null) {
16656                        dsm.checkMemory();
16657                    }
16658                }
16659                if(observer != null) {
16660                    try {
16661                        observer.onRemoveCompleted(packageName, succeeded);
16662                    } catch (RemoteException e) {
16663                        Log.i(TAG, "Observer no longer exists.");
16664                    }
16665                } //end if observer
16666            } //end run
16667        });
16668    }
16669
16670    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16671        if (packageName == null) {
16672            Slog.w(TAG, "Attempt to delete null packageName.");
16673            return false;
16674        }
16675
16676        // Try finding details about the requested package
16677        PackageParser.Package pkg;
16678        synchronized (mPackages) {
16679            pkg = mPackages.get(packageName);
16680            if (pkg == null) {
16681                final PackageSetting ps = mSettings.mPackages.get(packageName);
16682                if (ps != null) {
16683                    pkg = ps.pkg;
16684                }
16685            }
16686
16687            if (pkg == null) {
16688                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16689                return false;
16690            }
16691
16692            PackageSetting ps = (PackageSetting) pkg.mExtras;
16693            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16694        }
16695
16696        clearAppDataLIF(pkg, userId,
16697                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16698
16699        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16700        removeKeystoreDataIfNeeded(userId, appId);
16701
16702        UserManagerInternal umInternal = getUserManagerInternal();
16703        final int flags;
16704        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16705            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16706        } else if (umInternal.isUserRunning(userId)) {
16707            flags = StorageManager.FLAG_STORAGE_DE;
16708        } else {
16709            flags = 0;
16710        }
16711        prepareAppDataContentsLIF(pkg, userId, flags);
16712
16713        return true;
16714    }
16715
16716    /**
16717     * Reverts user permission state changes (permissions and flags) in
16718     * all packages for a given user.
16719     *
16720     * @param userId The device user for which to do a reset.
16721     */
16722    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16723        final int packageCount = mPackages.size();
16724        for (int i = 0; i < packageCount; i++) {
16725            PackageParser.Package pkg = mPackages.valueAt(i);
16726            PackageSetting ps = (PackageSetting) pkg.mExtras;
16727            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16728        }
16729    }
16730
16731    private void resetNetworkPolicies(int userId) {
16732        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16733    }
16734
16735    /**
16736     * Reverts user permission state changes (permissions and flags).
16737     *
16738     * @param ps The package for which to reset.
16739     * @param userId The device user for which to do a reset.
16740     */
16741    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16742            final PackageSetting ps, final int userId) {
16743        if (ps.pkg == null) {
16744            return;
16745        }
16746
16747        // These are flags that can change base on user actions.
16748        final int userSettableMask = FLAG_PERMISSION_USER_SET
16749                | FLAG_PERMISSION_USER_FIXED
16750                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16751                | FLAG_PERMISSION_REVIEW_REQUIRED;
16752
16753        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16754                | FLAG_PERMISSION_POLICY_FIXED;
16755
16756        boolean writeInstallPermissions = false;
16757        boolean writeRuntimePermissions = false;
16758
16759        final int permissionCount = ps.pkg.requestedPermissions.size();
16760        for (int i = 0; i < permissionCount; i++) {
16761            String permission = ps.pkg.requestedPermissions.get(i);
16762
16763            BasePermission bp = mSettings.mPermissions.get(permission);
16764            if (bp == null) {
16765                continue;
16766            }
16767
16768            // If shared user we just reset the state to which only this app contributed.
16769            if (ps.sharedUser != null) {
16770                boolean used = false;
16771                final int packageCount = ps.sharedUser.packages.size();
16772                for (int j = 0; j < packageCount; j++) {
16773                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16774                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16775                            && pkg.pkg.requestedPermissions.contains(permission)) {
16776                        used = true;
16777                        break;
16778                    }
16779                }
16780                if (used) {
16781                    continue;
16782                }
16783            }
16784
16785            PermissionsState permissionsState = ps.getPermissionsState();
16786
16787            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16788
16789            // Always clear the user settable flags.
16790            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16791                    bp.name) != null;
16792            // If permission review is enabled and this is a legacy app, mark the
16793            // permission as requiring a review as this is the initial state.
16794            int flags = 0;
16795            if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
16796                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16797                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16798            }
16799            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16800                if (hasInstallState) {
16801                    writeInstallPermissions = true;
16802                } else {
16803                    writeRuntimePermissions = true;
16804                }
16805            }
16806
16807            // Below is only runtime permission handling.
16808            if (!bp.isRuntime()) {
16809                continue;
16810            }
16811
16812            // Never clobber system or policy.
16813            if ((oldFlags & policyOrSystemFlags) != 0) {
16814                continue;
16815            }
16816
16817            // If this permission was granted by default, make sure it is.
16818            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16819                if (permissionsState.grantRuntimePermission(bp, userId)
16820                        != PERMISSION_OPERATION_FAILURE) {
16821                    writeRuntimePermissions = true;
16822                }
16823            // If permission review is enabled the permissions for a legacy apps
16824            // are represented as constantly granted runtime ones, so don't revoke.
16825            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16826                // Otherwise, reset the permission.
16827                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16828                switch (revokeResult) {
16829                    case PERMISSION_OPERATION_SUCCESS:
16830                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16831                        writeRuntimePermissions = true;
16832                        final int appId = ps.appId;
16833                        mHandler.post(new Runnable() {
16834                            @Override
16835                            public void run() {
16836                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16837                            }
16838                        });
16839                    } break;
16840                }
16841            }
16842        }
16843
16844        // Synchronously write as we are taking permissions away.
16845        if (writeRuntimePermissions) {
16846            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16847        }
16848
16849        // Synchronously write as we are taking permissions away.
16850        if (writeInstallPermissions) {
16851            mSettings.writeLPr();
16852        }
16853    }
16854
16855    /**
16856     * Remove entries from the keystore daemon. Will only remove it if the
16857     * {@code appId} is valid.
16858     */
16859    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16860        if (appId < 0) {
16861            return;
16862        }
16863
16864        final KeyStore keyStore = KeyStore.getInstance();
16865        if (keyStore != null) {
16866            if (userId == UserHandle.USER_ALL) {
16867                for (final int individual : sUserManager.getUserIds()) {
16868                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16869                }
16870            } else {
16871                keyStore.clearUid(UserHandle.getUid(userId, appId));
16872            }
16873        } else {
16874            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16875        }
16876    }
16877
16878    @Override
16879    public void deleteApplicationCacheFiles(final String packageName,
16880            final IPackageDataObserver observer) {
16881        final int userId = UserHandle.getCallingUserId();
16882        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16883    }
16884
16885    @Override
16886    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16887            final IPackageDataObserver observer) {
16888        mContext.enforceCallingOrSelfPermission(
16889                android.Manifest.permission.DELETE_CACHE_FILES, null);
16890        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16891                /* requireFullPermission= */ true, /* checkShell= */ false,
16892                "delete application cache files");
16893
16894        final PackageParser.Package pkg;
16895        synchronized (mPackages) {
16896            pkg = mPackages.get(packageName);
16897        }
16898
16899        // Queue up an async operation since the package deletion may take a little while.
16900        mHandler.post(new Runnable() {
16901            public void run() {
16902                synchronized (mInstallLock) {
16903                    final int flags = StorageManager.FLAG_STORAGE_DE
16904                            | StorageManager.FLAG_STORAGE_CE;
16905                    // We're only clearing cache files, so we don't care if the
16906                    // app is unfrozen and still able to run
16907                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16908                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16909                }
16910                clearExternalStorageDataSync(packageName, userId, false);
16911                if (observer != null) {
16912                    try {
16913                        observer.onRemoveCompleted(packageName, true);
16914                    } catch (RemoteException e) {
16915                        Log.i(TAG, "Observer no longer exists.");
16916                    }
16917                }
16918            }
16919        });
16920    }
16921
16922    @Override
16923    public void getPackageSizeInfo(final String packageName, int userHandle,
16924            final IPackageStatsObserver observer) {
16925        mContext.enforceCallingOrSelfPermission(
16926                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16927        if (packageName == null) {
16928            throw new IllegalArgumentException("Attempt to get size of null packageName");
16929        }
16930
16931        PackageStats stats = new PackageStats(packageName, userHandle);
16932
16933        /*
16934         * Queue up an async operation since the package measurement may take a
16935         * little while.
16936         */
16937        Message msg = mHandler.obtainMessage(INIT_COPY);
16938        msg.obj = new MeasureParams(stats, observer);
16939        mHandler.sendMessage(msg);
16940    }
16941
16942    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16943        final PackageSetting ps;
16944        synchronized (mPackages) {
16945            ps = mSettings.mPackages.get(packageName);
16946            if (ps == null) {
16947                Slog.w(TAG, "Failed to find settings for " + packageName);
16948                return false;
16949            }
16950        }
16951
16952        final String[] packageNames = { packageName };
16953        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
16954        final String[] codePaths = { ps.codePathString };
16955
16956        try {
16957            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
16958                    ps.appId, ceDataInodes, codePaths, stats);
16959
16960            // For now, ignore code size of packages on system partition
16961            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16962                stats.codeSize = 0;
16963            }
16964
16965            // External clients expect these to be tracked separately
16966            stats.dataSize -= stats.cacheSize;
16967
16968        } catch (InstallerException e) {
16969            Slog.w(TAG, String.valueOf(e));
16970            return false;
16971        }
16972
16973        return true;
16974    }
16975
16976    private int getUidTargetSdkVersionLockedLPr(int uid) {
16977        Object obj = mSettings.getUserIdLPr(uid);
16978        if (obj instanceof SharedUserSetting) {
16979            final SharedUserSetting sus = (SharedUserSetting) obj;
16980            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16981            final Iterator<PackageSetting> it = sus.packages.iterator();
16982            while (it.hasNext()) {
16983                final PackageSetting ps = it.next();
16984                if (ps.pkg != null) {
16985                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16986                    if (v < vers) vers = v;
16987                }
16988            }
16989            return vers;
16990        } else if (obj instanceof PackageSetting) {
16991            final PackageSetting ps = (PackageSetting) obj;
16992            if (ps.pkg != null) {
16993                return ps.pkg.applicationInfo.targetSdkVersion;
16994            }
16995        }
16996        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16997    }
16998
16999    @Override
17000    public void addPreferredActivity(IntentFilter filter, int match,
17001            ComponentName[] set, ComponentName activity, int userId) {
17002        addPreferredActivityInternal(filter, match, set, activity, true, userId,
17003                "Adding preferred");
17004    }
17005
17006    private void addPreferredActivityInternal(IntentFilter filter, int match,
17007            ComponentName[] set, ComponentName activity, boolean always, int userId,
17008            String opname) {
17009        // writer
17010        int callingUid = Binder.getCallingUid();
17011        enforceCrossUserPermission(callingUid, userId,
17012                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
17013        if (filter.countActions() == 0) {
17014            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17015            return;
17016        }
17017        synchronized (mPackages) {
17018            if (mContext.checkCallingOrSelfPermission(
17019                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17020                    != PackageManager.PERMISSION_GRANTED) {
17021                if (getUidTargetSdkVersionLockedLPr(callingUid)
17022                        < Build.VERSION_CODES.FROYO) {
17023                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
17024                            + callingUid);
17025                    return;
17026                }
17027                mContext.enforceCallingOrSelfPermission(
17028                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17029            }
17030
17031            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
17032            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
17033                    + userId + ":");
17034            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17035            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
17036            scheduleWritePackageRestrictionsLocked(userId);
17037            postPreferredActivityChangedBroadcast(userId);
17038        }
17039    }
17040
17041    private void postPreferredActivityChangedBroadcast(int userId) {
17042        mHandler.post(() -> {
17043            final IActivityManager am = ActivityManagerNative.getDefault();
17044            if (am == null) {
17045                return;
17046            }
17047
17048            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
17049            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17050            try {
17051                am.broadcastIntent(null, intent, null, null,
17052                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
17053                        null, false, false, userId);
17054            } catch (RemoteException e) {
17055            }
17056        });
17057    }
17058
17059    @Override
17060    public void replacePreferredActivity(IntentFilter filter, int match,
17061            ComponentName[] set, ComponentName activity, int userId) {
17062        if (filter.countActions() != 1) {
17063            throw new IllegalArgumentException(
17064                    "replacePreferredActivity expects filter to have only 1 action.");
17065        }
17066        if (filter.countDataAuthorities() != 0
17067                || filter.countDataPaths() != 0
17068                || filter.countDataSchemes() > 1
17069                || filter.countDataTypes() != 0) {
17070            throw new IllegalArgumentException(
17071                    "replacePreferredActivity expects filter to have no data authorities, " +
17072                    "paths, or types; and at most one scheme.");
17073        }
17074
17075        final int callingUid = Binder.getCallingUid();
17076        enforceCrossUserPermission(callingUid, userId,
17077                true /* requireFullPermission */, false /* checkShell */,
17078                "replace preferred activity");
17079        synchronized (mPackages) {
17080            if (mContext.checkCallingOrSelfPermission(
17081                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17082                    != PackageManager.PERMISSION_GRANTED) {
17083                if (getUidTargetSdkVersionLockedLPr(callingUid)
17084                        < Build.VERSION_CODES.FROYO) {
17085                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17086                            + Binder.getCallingUid());
17087                    return;
17088                }
17089                mContext.enforceCallingOrSelfPermission(
17090                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17091            }
17092
17093            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17094            if (pir != null) {
17095                // Get all of the existing entries that exactly match this filter.
17096                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17097                if (existing != null && existing.size() == 1) {
17098                    PreferredActivity cur = existing.get(0);
17099                    if (DEBUG_PREFERRED) {
17100                        Slog.i(TAG, "Checking replace of preferred:");
17101                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17102                        if (!cur.mPref.mAlways) {
17103                            Slog.i(TAG, "  -- CUR; not mAlways!");
17104                        } else {
17105                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
17106                            Slog.i(TAG, "  -- CUR: mSet="
17107                                    + Arrays.toString(cur.mPref.mSetComponents));
17108                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
17109                            Slog.i(TAG, "  -- NEW: mMatch="
17110                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
17111                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
17112                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
17113                        }
17114                    }
17115                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17116                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17117                            && cur.mPref.sameSet(set)) {
17118                        // Setting the preferred activity to what it happens to be already
17119                        if (DEBUG_PREFERRED) {
17120                            Slog.i(TAG, "Replacing with same preferred activity "
17121                                    + cur.mPref.mShortComponent + " for user "
17122                                    + userId + ":");
17123                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17124                        }
17125                        return;
17126                    }
17127                }
17128
17129                if (existing != null) {
17130                    if (DEBUG_PREFERRED) {
17131                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17132                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17133                    }
17134                    for (int i = 0; i < existing.size(); i++) {
17135                        PreferredActivity pa = existing.get(i);
17136                        if (DEBUG_PREFERRED) {
17137                            Slog.i(TAG, "Removing existing preferred activity "
17138                                    + pa.mPref.mComponent + ":");
17139                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17140                        }
17141                        pir.removeFilter(pa);
17142                    }
17143                }
17144            }
17145            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17146                    "Replacing preferred");
17147        }
17148    }
17149
17150    @Override
17151    public void clearPackagePreferredActivities(String packageName) {
17152        final int uid = Binder.getCallingUid();
17153        // writer
17154        synchronized (mPackages) {
17155            PackageParser.Package pkg = mPackages.get(packageName);
17156            if (pkg == null || pkg.applicationInfo.uid != uid) {
17157                if (mContext.checkCallingOrSelfPermission(
17158                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17159                        != PackageManager.PERMISSION_GRANTED) {
17160                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17161                            < Build.VERSION_CODES.FROYO) {
17162                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17163                                + Binder.getCallingUid());
17164                        return;
17165                    }
17166                    mContext.enforceCallingOrSelfPermission(
17167                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17168                }
17169            }
17170
17171            int user = UserHandle.getCallingUserId();
17172            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17173                scheduleWritePackageRestrictionsLocked(user);
17174            }
17175        }
17176    }
17177
17178    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17179    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17180        ArrayList<PreferredActivity> removed = null;
17181        boolean changed = false;
17182        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17183            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17184            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17185            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17186                continue;
17187            }
17188            Iterator<PreferredActivity> it = pir.filterIterator();
17189            while (it.hasNext()) {
17190                PreferredActivity pa = it.next();
17191                // Mark entry for removal only if it matches the package name
17192                // and the entry is of type "always".
17193                if (packageName == null ||
17194                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17195                                && pa.mPref.mAlways)) {
17196                    if (removed == null) {
17197                        removed = new ArrayList<PreferredActivity>();
17198                    }
17199                    removed.add(pa);
17200                }
17201            }
17202            if (removed != null) {
17203                for (int j=0; j<removed.size(); j++) {
17204                    PreferredActivity pa = removed.get(j);
17205                    pir.removeFilter(pa);
17206                }
17207                changed = true;
17208            }
17209        }
17210        if (changed) {
17211            postPreferredActivityChangedBroadcast(userId);
17212        }
17213        return changed;
17214    }
17215
17216    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17217    private void clearIntentFilterVerificationsLPw(int userId) {
17218        final int packageCount = mPackages.size();
17219        for (int i = 0; i < packageCount; i++) {
17220            PackageParser.Package pkg = mPackages.valueAt(i);
17221            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17222        }
17223    }
17224
17225    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17226    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17227        if (userId == UserHandle.USER_ALL) {
17228            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17229                    sUserManager.getUserIds())) {
17230                for (int oneUserId : sUserManager.getUserIds()) {
17231                    scheduleWritePackageRestrictionsLocked(oneUserId);
17232                }
17233            }
17234        } else {
17235            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17236                scheduleWritePackageRestrictionsLocked(userId);
17237            }
17238        }
17239    }
17240
17241    void clearDefaultBrowserIfNeeded(String packageName) {
17242        for (int oneUserId : sUserManager.getUserIds()) {
17243            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17244            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17245            if (packageName.equals(defaultBrowserPackageName)) {
17246                setDefaultBrowserPackageName(null, oneUserId);
17247            }
17248        }
17249    }
17250
17251    @Override
17252    public void resetApplicationPreferences(int userId) {
17253        mContext.enforceCallingOrSelfPermission(
17254                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17255        final long identity = Binder.clearCallingIdentity();
17256        // writer
17257        try {
17258            synchronized (mPackages) {
17259                clearPackagePreferredActivitiesLPw(null, userId);
17260                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17261                // TODO: We have to reset the default SMS and Phone. This requires
17262                // significant refactoring to keep all default apps in the package
17263                // manager (cleaner but more work) or have the services provide
17264                // callbacks to the package manager to request a default app reset.
17265                applyFactoryDefaultBrowserLPw(userId);
17266                clearIntentFilterVerificationsLPw(userId);
17267                primeDomainVerificationsLPw(userId);
17268                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17269                scheduleWritePackageRestrictionsLocked(userId);
17270            }
17271            resetNetworkPolicies(userId);
17272        } finally {
17273            Binder.restoreCallingIdentity(identity);
17274        }
17275    }
17276
17277    @Override
17278    public int getPreferredActivities(List<IntentFilter> outFilters,
17279            List<ComponentName> outActivities, String packageName) {
17280
17281        int num = 0;
17282        final int userId = UserHandle.getCallingUserId();
17283        // reader
17284        synchronized (mPackages) {
17285            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17286            if (pir != null) {
17287                final Iterator<PreferredActivity> it = pir.filterIterator();
17288                while (it.hasNext()) {
17289                    final PreferredActivity pa = it.next();
17290                    if (packageName == null
17291                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17292                                    && pa.mPref.mAlways)) {
17293                        if (outFilters != null) {
17294                            outFilters.add(new IntentFilter(pa));
17295                        }
17296                        if (outActivities != null) {
17297                            outActivities.add(pa.mPref.mComponent);
17298                        }
17299                    }
17300                }
17301            }
17302        }
17303
17304        return num;
17305    }
17306
17307    @Override
17308    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17309            int userId) {
17310        int callingUid = Binder.getCallingUid();
17311        if (callingUid != Process.SYSTEM_UID) {
17312            throw new SecurityException(
17313                    "addPersistentPreferredActivity can only be run by the system");
17314        }
17315        if (filter.countActions() == 0) {
17316            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17317            return;
17318        }
17319        synchronized (mPackages) {
17320            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17321                    ":");
17322            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17323            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17324                    new PersistentPreferredActivity(filter, activity));
17325            scheduleWritePackageRestrictionsLocked(userId);
17326            postPreferredActivityChangedBroadcast(userId);
17327        }
17328    }
17329
17330    @Override
17331    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17332        int callingUid = Binder.getCallingUid();
17333        if (callingUid != Process.SYSTEM_UID) {
17334            throw new SecurityException(
17335                    "clearPackagePersistentPreferredActivities can only be run by the system");
17336        }
17337        ArrayList<PersistentPreferredActivity> removed = null;
17338        boolean changed = false;
17339        synchronized (mPackages) {
17340            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17341                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17342                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17343                        .valueAt(i);
17344                if (userId != thisUserId) {
17345                    continue;
17346                }
17347                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17348                while (it.hasNext()) {
17349                    PersistentPreferredActivity ppa = it.next();
17350                    // Mark entry for removal only if it matches the package name.
17351                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17352                        if (removed == null) {
17353                            removed = new ArrayList<PersistentPreferredActivity>();
17354                        }
17355                        removed.add(ppa);
17356                    }
17357                }
17358                if (removed != null) {
17359                    for (int j=0; j<removed.size(); j++) {
17360                        PersistentPreferredActivity ppa = removed.get(j);
17361                        ppir.removeFilter(ppa);
17362                    }
17363                    changed = true;
17364                }
17365            }
17366
17367            if (changed) {
17368                scheduleWritePackageRestrictionsLocked(userId);
17369                postPreferredActivityChangedBroadcast(userId);
17370            }
17371        }
17372    }
17373
17374    /**
17375     * Common machinery for picking apart a restored XML blob and passing
17376     * it to a caller-supplied functor to be applied to the running system.
17377     */
17378    private void restoreFromXml(XmlPullParser parser, int userId,
17379            String expectedStartTag, BlobXmlRestorer functor)
17380            throws IOException, XmlPullParserException {
17381        int type;
17382        while ((type = parser.next()) != XmlPullParser.START_TAG
17383                && type != XmlPullParser.END_DOCUMENT) {
17384        }
17385        if (type != XmlPullParser.START_TAG) {
17386            // oops didn't find a start tag?!
17387            if (DEBUG_BACKUP) {
17388                Slog.e(TAG, "Didn't find start tag during restore");
17389            }
17390            return;
17391        }
17392Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17393        // this is supposed to be TAG_PREFERRED_BACKUP
17394        if (!expectedStartTag.equals(parser.getName())) {
17395            if (DEBUG_BACKUP) {
17396                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17397            }
17398            return;
17399        }
17400
17401        // skip interfering stuff, then we're aligned with the backing implementation
17402        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17403Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17404        functor.apply(parser, userId);
17405    }
17406
17407    private interface BlobXmlRestorer {
17408        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17409    }
17410
17411    /**
17412     * Non-Binder method, support for the backup/restore mechanism: write the
17413     * full set of preferred activities in its canonical XML format.  Returns the
17414     * XML output as a byte array, or null if there is none.
17415     */
17416    @Override
17417    public byte[] getPreferredActivityBackup(int userId) {
17418        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17419            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17420        }
17421
17422        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17423        try {
17424            final XmlSerializer serializer = new FastXmlSerializer();
17425            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17426            serializer.startDocument(null, true);
17427            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17428
17429            synchronized (mPackages) {
17430                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17431            }
17432
17433            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17434            serializer.endDocument();
17435            serializer.flush();
17436        } catch (Exception e) {
17437            if (DEBUG_BACKUP) {
17438                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17439            }
17440            return null;
17441        }
17442
17443        return dataStream.toByteArray();
17444    }
17445
17446    @Override
17447    public void restorePreferredActivities(byte[] backup, int userId) {
17448        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17449            throw new SecurityException("Only the system may call restorePreferredActivities()");
17450        }
17451
17452        try {
17453            final XmlPullParser parser = Xml.newPullParser();
17454            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17455            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17456                    new BlobXmlRestorer() {
17457                        @Override
17458                        public void apply(XmlPullParser parser, int userId)
17459                                throws XmlPullParserException, IOException {
17460                            synchronized (mPackages) {
17461                                mSettings.readPreferredActivitiesLPw(parser, userId);
17462                            }
17463                        }
17464                    } );
17465        } catch (Exception e) {
17466            if (DEBUG_BACKUP) {
17467                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17468            }
17469        }
17470    }
17471
17472    /**
17473     * Non-Binder method, support for the backup/restore mechanism: write the
17474     * default browser (etc) settings in its canonical XML format.  Returns the default
17475     * browser XML representation as a byte array, or null if there is none.
17476     */
17477    @Override
17478    public byte[] getDefaultAppsBackup(int userId) {
17479        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17480            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17481        }
17482
17483        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17484        try {
17485            final XmlSerializer serializer = new FastXmlSerializer();
17486            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17487            serializer.startDocument(null, true);
17488            serializer.startTag(null, TAG_DEFAULT_APPS);
17489
17490            synchronized (mPackages) {
17491                mSettings.writeDefaultAppsLPr(serializer, userId);
17492            }
17493
17494            serializer.endTag(null, TAG_DEFAULT_APPS);
17495            serializer.endDocument();
17496            serializer.flush();
17497        } catch (Exception e) {
17498            if (DEBUG_BACKUP) {
17499                Slog.e(TAG, "Unable to write default apps for backup", e);
17500            }
17501            return null;
17502        }
17503
17504        return dataStream.toByteArray();
17505    }
17506
17507    @Override
17508    public void restoreDefaultApps(byte[] backup, int userId) {
17509        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17510            throw new SecurityException("Only the system may call restoreDefaultApps()");
17511        }
17512
17513        try {
17514            final XmlPullParser parser = Xml.newPullParser();
17515            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17516            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17517                    new BlobXmlRestorer() {
17518                        @Override
17519                        public void apply(XmlPullParser parser, int userId)
17520                                throws XmlPullParserException, IOException {
17521                            synchronized (mPackages) {
17522                                mSettings.readDefaultAppsLPw(parser, userId);
17523                            }
17524                        }
17525                    } );
17526        } catch (Exception e) {
17527            if (DEBUG_BACKUP) {
17528                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17529            }
17530        }
17531    }
17532
17533    @Override
17534    public byte[] getIntentFilterVerificationBackup(int userId) {
17535        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17536            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17537        }
17538
17539        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17540        try {
17541            final XmlSerializer serializer = new FastXmlSerializer();
17542            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17543            serializer.startDocument(null, true);
17544            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17545
17546            synchronized (mPackages) {
17547                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17548            }
17549
17550            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17551            serializer.endDocument();
17552            serializer.flush();
17553        } catch (Exception e) {
17554            if (DEBUG_BACKUP) {
17555                Slog.e(TAG, "Unable to write default apps for backup", e);
17556            }
17557            return null;
17558        }
17559
17560        return dataStream.toByteArray();
17561    }
17562
17563    @Override
17564    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17565        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17566            throw new SecurityException("Only the system may call restorePreferredActivities()");
17567        }
17568
17569        try {
17570            final XmlPullParser parser = Xml.newPullParser();
17571            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17572            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17573                    new BlobXmlRestorer() {
17574                        @Override
17575                        public void apply(XmlPullParser parser, int userId)
17576                                throws XmlPullParserException, IOException {
17577                            synchronized (mPackages) {
17578                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17579                                mSettings.writeLPr();
17580                            }
17581                        }
17582                    } );
17583        } catch (Exception e) {
17584            if (DEBUG_BACKUP) {
17585                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17586            }
17587        }
17588    }
17589
17590    @Override
17591    public byte[] getPermissionGrantBackup(int userId) {
17592        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17593            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17594        }
17595
17596        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17597        try {
17598            final XmlSerializer serializer = new FastXmlSerializer();
17599            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17600            serializer.startDocument(null, true);
17601            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17602
17603            synchronized (mPackages) {
17604                serializeRuntimePermissionGrantsLPr(serializer, userId);
17605            }
17606
17607            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17608            serializer.endDocument();
17609            serializer.flush();
17610        } catch (Exception e) {
17611            if (DEBUG_BACKUP) {
17612                Slog.e(TAG, "Unable to write default apps for backup", e);
17613            }
17614            return null;
17615        }
17616
17617        return dataStream.toByteArray();
17618    }
17619
17620    @Override
17621    public void restorePermissionGrants(byte[] backup, int userId) {
17622        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17623            throw new SecurityException("Only the system may call restorePermissionGrants()");
17624        }
17625
17626        try {
17627            final XmlPullParser parser = Xml.newPullParser();
17628            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17629            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17630                    new BlobXmlRestorer() {
17631                        @Override
17632                        public void apply(XmlPullParser parser, int userId)
17633                                throws XmlPullParserException, IOException {
17634                            synchronized (mPackages) {
17635                                processRestoredPermissionGrantsLPr(parser, userId);
17636                            }
17637                        }
17638                    } );
17639        } catch (Exception e) {
17640            if (DEBUG_BACKUP) {
17641                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17642            }
17643        }
17644    }
17645
17646    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17647            throws IOException {
17648        serializer.startTag(null, TAG_ALL_GRANTS);
17649
17650        final int N = mSettings.mPackages.size();
17651        for (int i = 0; i < N; i++) {
17652            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17653            boolean pkgGrantsKnown = false;
17654
17655            PermissionsState packagePerms = ps.getPermissionsState();
17656
17657            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17658                final int grantFlags = state.getFlags();
17659                // only look at grants that are not system/policy fixed
17660                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17661                    final boolean isGranted = state.isGranted();
17662                    // And only back up the user-twiddled state bits
17663                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17664                        final String packageName = mSettings.mPackages.keyAt(i);
17665                        if (!pkgGrantsKnown) {
17666                            serializer.startTag(null, TAG_GRANT);
17667                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17668                            pkgGrantsKnown = true;
17669                        }
17670
17671                        final boolean userSet =
17672                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17673                        final boolean userFixed =
17674                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17675                        final boolean revoke =
17676                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17677
17678                        serializer.startTag(null, TAG_PERMISSION);
17679                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17680                        if (isGranted) {
17681                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17682                        }
17683                        if (userSet) {
17684                            serializer.attribute(null, ATTR_USER_SET, "true");
17685                        }
17686                        if (userFixed) {
17687                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17688                        }
17689                        if (revoke) {
17690                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17691                        }
17692                        serializer.endTag(null, TAG_PERMISSION);
17693                    }
17694                }
17695            }
17696
17697            if (pkgGrantsKnown) {
17698                serializer.endTag(null, TAG_GRANT);
17699            }
17700        }
17701
17702        serializer.endTag(null, TAG_ALL_GRANTS);
17703    }
17704
17705    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17706            throws XmlPullParserException, IOException {
17707        String pkgName = null;
17708        int outerDepth = parser.getDepth();
17709        int type;
17710        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17711                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17712            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17713                continue;
17714            }
17715
17716            final String tagName = parser.getName();
17717            if (tagName.equals(TAG_GRANT)) {
17718                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17719                if (DEBUG_BACKUP) {
17720                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17721                }
17722            } else if (tagName.equals(TAG_PERMISSION)) {
17723
17724                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17725                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17726
17727                int newFlagSet = 0;
17728                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17729                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17730                }
17731                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17732                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17733                }
17734                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17735                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17736                }
17737                if (DEBUG_BACKUP) {
17738                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17739                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17740                }
17741                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17742                if (ps != null) {
17743                    // Already installed so we apply the grant immediately
17744                    if (DEBUG_BACKUP) {
17745                        Slog.v(TAG, "        + already installed; applying");
17746                    }
17747                    PermissionsState perms = ps.getPermissionsState();
17748                    BasePermission bp = mSettings.mPermissions.get(permName);
17749                    if (bp != null) {
17750                        if (isGranted) {
17751                            perms.grantRuntimePermission(bp, userId);
17752                        }
17753                        if (newFlagSet != 0) {
17754                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17755                        }
17756                    }
17757                } else {
17758                    // Need to wait for post-restore install to apply the grant
17759                    if (DEBUG_BACKUP) {
17760                        Slog.v(TAG, "        - not yet installed; saving for later");
17761                    }
17762                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17763                            isGranted, newFlagSet, userId);
17764                }
17765            } else {
17766                PackageManagerService.reportSettingsProblem(Log.WARN,
17767                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17768                XmlUtils.skipCurrentTag(parser);
17769            }
17770        }
17771
17772        scheduleWriteSettingsLocked();
17773        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17774    }
17775
17776    @Override
17777    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17778            int sourceUserId, int targetUserId, int flags) {
17779        mContext.enforceCallingOrSelfPermission(
17780                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17781        int callingUid = Binder.getCallingUid();
17782        enforceOwnerRights(ownerPackage, callingUid);
17783        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17784        if (intentFilter.countActions() == 0) {
17785            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17786            return;
17787        }
17788        synchronized (mPackages) {
17789            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17790                    ownerPackage, targetUserId, flags);
17791            CrossProfileIntentResolver resolver =
17792                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17793            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17794            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17795            if (existing != null) {
17796                int size = existing.size();
17797                for (int i = 0; i < size; i++) {
17798                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17799                        return;
17800                    }
17801                }
17802            }
17803            resolver.addFilter(newFilter);
17804            scheduleWritePackageRestrictionsLocked(sourceUserId);
17805        }
17806    }
17807
17808    @Override
17809    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17810        mContext.enforceCallingOrSelfPermission(
17811                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17812        int callingUid = Binder.getCallingUid();
17813        enforceOwnerRights(ownerPackage, callingUid);
17814        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17815        synchronized (mPackages) {
17816            CrossProfileIntentResolver resolver =
17817                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17818            ArraySet<CrossProfileIntentFilter> set =
17819                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17820            for (CrossProfileIntentFilter filter : set) {
17821                if (filter.getOwnerPackage().equals(ownerPackage)) {
17822                    resolver.removeFilter(filter);
17823                }
17824            }
17825            scheduleWritePackageRestrictionsLocked(sourceUserId);
17826        }
17827    }
17828
17829    // Enforcing that callingUid is owning pkg on userId
17830    private void enforceOwnerRights(String pkg, int callingUid) {
17831        // The system owns everything.
17832        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17833            return;
17834        }
17835        int callingUserId = UserHandle.getUserId(callingUid);
17836        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17837        if (pi == null) {
17838            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17839                    + callingUserId);
17840        }
17841        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17842            throw new SecurityException("Calling uid " + callingUid
17843                    + " does not own package " + pkg);
17844        }
17845    }
17846
17847    @Override
17848    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17849        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17850    }
17851
17852    private Intent getHomeIntent() {
17853        Intent intent = new Intent(Intent.ACTION_MAIN);
17854        intent.addCategory(Intent.CATEGORY_HOME);
17855        intent.addCategory(Intent.CATEGORY_DEFAULT);
17856        return intent;
17857    }
17858
17859    private IntentFilter getHomeFilter() {
17860        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17861        filter.addCategory(Intent.CATEGORY_HOME);
17862        filter.addCategory(Intent.CATEGORY_DEFAULT);
17863        return filter;
17864    }
17865
17866    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17867            int userId) {
17868        Intent intent  = getHomeIntent();
17869        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17870                PackageManager.GET_META_DATA, userId);
17871        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17872                true, false, false, userId);
17873
17874        allHomeCandidates.clear();
17875        if (list != null) {
17876            for (ResolveInfo ri : list) {
17877                allHomeCandidates.add(ri);
17878            }
17879        }
17880        return (preferred == null || preferred.activityInfo == null)
17881                ? null
17882                : new ComponentName(preferred.activityInfo.packageName,
17883                        preferred.activityInfo.name);
17884    }
17885
17886    @Override
17887    public void setHomeActivity(ComponentName comp, int userId) {
17888        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17889        getHomeActivitiesAsUser(homeActivities, userId);
17890
17891        boolean found = false;
17892
17893        final int size = homeActivities.size();
17894        final ComponentName[] set = new ComponentName[size];
17895        for (int i = 0; i < size; i++) {
17896            final ResolveInfo candidate = homeActivities.get(i);
17897            final ActivityInfo info = candidate.activityInfo;
17898            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17899            set[i] = activityName;
17900            if (!found && activityName.equals(comp)) {
17901                found = true;
17902            }
17903        }
17904        if (!found) {
17905            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17906                    + userId);
17907        }
17908        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17909                set, comp, userId);
17910    }
17911
17912    private @Nullable String getSetupWizardPackageName() {
17913        final Intent intent = new Intent(Intent.ACTION_MAIN);
17914        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17915
17916        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17917                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17918                        | MATCH_DISABLED_COMPONENTS,
17919                UserHandle.myUserId());
17920        if (matches.size() == 1) {
17921            return matches.get(0).getComponentInfo().packageName;
17922        } else {
17923            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17924                    + ": matches=" + matches);
17925            return null;
17926        }
17927    }
17928
17929    private @Nullable String getStorageManagerPackageName() {
17930        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
17931
17932        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17933                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17934                        | MATCH_DISABLED_COMPONENTS,
17935                UserHandle.myUserId());
17936        if (matches.size() == 1) {
17937            return matches.get(0).getComponentInfo().packageName;
17938        } else {
17939            Slog.e(TAG, "There should probably be exactly one storage manager; found "
17940                    + matches.size() + ": matches=" + matches);
17941            return null;
17942        }
17943    }
17944
17945    @Override
17946    public void setApplicationEnabledSetting(String appPackageName,
17947            int newState, int flags, int userId, String callingPackage) {
17948        if (!sUserManager.exists(userId)) return;
17949        if (callingPackage == null) {
17950            callingPackage = Integer.toString(Binder.getCallingUid());
17951        }
17952        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17953    }
17954
17955    @Override
17956    public void setComponentEnabledSetting(ComponentName componentName,
17957            int newState, int flags, int userId) {
17958        if (!sUserManager.exists(userId)) return;
17959        setEnabledSetting(componentName.getPackageName(),
17960                componentName.getClassName(), newState, flags, userId, null);
17961    }
17962
17963    private void setEnabledSetting(final String packageName, String className, int newState,
17964            final int flags, int userId, String callingPackage) {
17965        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17966              || newState == COMPONENT_ENABLED_STATE_ENABLED
17967              || newState == COMPONENT_ENABLED_STATE_DISABLED
17968              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17969              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17970            throw new IllegalArgumentException("Invalid new component state: "
17971                    + newState);
17972        }
17973        PackageSetting pkgSetting;
17974        final int uid = Binder.getCallingUid();
17975        final int permission;
17976        if (uid == Process.SYSTEM_UID) {
17977            permission = PackageManager.PERMISSION_GRANTED;
17978        } else {
17979            permission = mContext.checkCallingOrSelfPermission(
17980                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17981        }
17982        enforceCrossUserPermission(uid, userId,
17983                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17984        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17985        boolean sendNow = false;
17986        boolean isApp = (className == null);
17987        String componentName = isApp ? packageName : className;
17988        int packageUid = -1;
17989        ArrayList<String> components;
17990
17991        // writer
17992        synchronized (mPackages) {
17993            pkgSetting = mSettings.mPackages.get(packageName);
17994            if (pkgSetting == null) {
17995                if (className == null) {
17996                    throw new IllegalArgumentException("Unknown package: " + packageName);
17997                }
17998                throw new IllegalArgumentException(
17999                        "Unknown component: " + packageName + "/" + className);
18000            }
18001        }
18002
18003        // Limit who can change which apps
18004        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
18005            // Don't allow apps that don't have permission to modify other apps
18006            if (!allowedByPermission) {
18007                throw new SecurityException(
18008                        "Permission Denial: attempt to change component state from pid="
18009                        + Binder.getCallingPid()
18010                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
18011            }
18012            // Don't allow changing protected packages.
18013            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
18014                throw new SecurityException("Cannot disable a protected package: " + packageName);
18015            }
18016        }
18017
18018        synchronized (mPackages) {
18019            if (uid == Process.SHELL_UID) {
18020                // Shell can only change whole packages between ENABLED and DISABLED_USER states
18021                int oldState = pkgSetting.getEnabled(userId);
18022                if (className == null
18023                    &&
18024                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
18025                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
18026                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
18027                    &&
18028                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18029                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
18030                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
18031                    // ok
18032                } else {
18033                    throw new SecurityException(
18034                            "Shell cannot change component state for " + packageName + "/"
18035                            + className + " to " + newState);
18036                }
18037            }
18038            if (className == null) {
18039                // We're dealing with an application/package level state change
18040                if (pkgSetting.getEnabled(userId) == newState) {
18041                    // Nothing to do
18042                    return;
18043                }
18044                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
18045                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
18046                    // Don't care about who enables an app.
18047                    callingPackage = null;
18048                }
18049                pkgSetting.setEnabled(newState, userId, callingPackage);
18050                // pkgSetting.pkg.mSetEnabled = newState;
18051            } else {
18052                // We're dealing with a component level state change
18053                // First, verify that this is a valid class name.
18054                PackageParser.Package pkg = pkgSetting.pkg;
18055                if (pkg == null || !pkg.hasComponentClassName(className)) {
18056                    if (pkg != null &&
18057                            pkg.applicationInfo.targetSdkVersion >=
18058                                    Build.VERSION_CODES.JELLY_BEAN) {
18059                        throw new IllegalArgumentException("Component class " + className
18060                                + " does not exist in " + packageName);
18061                    } else {
18062                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18063                                + className + " does not exist in " + packageName);
18064                    }
18065                }
18066                switch (newState) {
18067                case COMPONENT_ENABLED_STATE_ENABLED:
18068                    if (!pkgSetting.enableComponentLPw(className, userId)) {
18069                        return;
18070                    }
18071                    break;
18072                case COMPONENT_ENABLED_STATE_DISABLED:
18073                    if (!pkgSetting.disableComponentLPw(className, userId)) {
18074                        return;
18075                    }
18076                    break;
18077                case COMPONENT_ENABLED_STATE_DEFAULT:
18078                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
18079                        return;
18080                    }
18081                    break;
18082                default:
18083                    Slog.e(TAG, "Invalid new component state: " + newState);
18084                    return;
18085                }
18086            }
18087            scheduleWritePackageRestrictionsLocked(userId);
18088            components = mPendingBroadcasts.get(userId, packageName);
18089            final boolean newPackage = components == null;
18090            if (newPackage) {
18091                components = new ArrayList<String>();
18092            }
18093            if (!components.contains(componentName)) {
18094                components.add(componentName);
18095            }
18096            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18097                sendNow = true;
18098                // Purge entry from pending broadcast list if another one exists already
18099                // since we are sending one right away.
18100                mPendingBroadcasts.remove(userId, packageName);
18101            } else {
18102                if (newPackage) {
18103                    mPendingBroadcasts.put(userId, packageName, components);
18104                }
18105                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18106                    // Schedule a message
18107                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18108                }
18109            }
18110        }
18111
18112        long callingId = Binder.clearCallingIdentity();
18113        try {
18114            if (sendNow) {
18115                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18116                sendPackageChangedBroadcast(packageName,
18117                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18118            }
18119        } finally {
18120            Binder.restoreCallingIdentity(callingId);
18121        }
18122    }
18123
18124    @Override
18125    public void flushPackageRestrictionsAsUser(int userId) {
18126        if (!sUserManager.exists(userId)) {
18127            return;
18128        }
18129        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18130                false /* checkShell */, "flushPackageRestrictions");
18131        synchronized (mPackages) {
18132            mSettings.writePackageRestrictionsLPr(userId);
18133            mDirtyUsers.remove(userId);
18134            if (mDirtyUsers.isEmpty()) {
18135                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18136            }
18137        }
18138    }
18139
18140    private void sendPackageChangedBroadcast(String packageName,
18141            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18142        if (DEBUG_INSTALL)
18143            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18144                    + componentNames);
18145        Bundle extras = new Bundle(4);
18146        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18147        String nameList[] = new String[componentNames.size()];
18148        componentNames.toArray(nameList);
18149        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18150        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18151        extras.putInt(Intent.EXTRA_UID, packageUid);
18152        // If this is not reporting a change of the overall package, then only send it
18153        // to registered receivers.  We don't want to launch a swath of apps for every
18154        // little component state change.
18155        final int flags = !componentNames.contains(packageName)
18156                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18157        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18158                new int[] {UserHandle.getUserId(packageUid)});
18159    }
18160
18161    @Override
18162    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18163        if (!sUserManager.exists(userId)) return;
18164        final int uid = Binder.getCallingUid();
18165        final int permission = mContext.checkCallingOrSelfPermission(
18166                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18167        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18168        enforceCrossUserPermission(uid, userId,
18169                true /* requireFullPermission */, true /* checkShell */, "stop package");
18170        // writer
18171        synchronized (mPackages) {
18172            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18173                    allowedByPermission, uid, userId)) {
18174                scheduleWritePackageRestrictionsLocked(userId);
18175            }
18176        }
18177    }
18178
18179    @Override
18180    public String getInstallerPackageName(String packageName) {
18181        // reader
18182        synchronized (mPackages) {
18183            return mSettings.getInstallerPackageNameLPr(packageName);
18184        }
18185    }
18186
18187    public boolean isOrphaned(String packageName) {
18188        // reader
18189        synchronized (mPackages) {
18190            return mSettings.isOrphaned(packageName);
18191        }
18192    }
18193
18194    @Override
18195    public int getApplicationEnabledSetting(String packageName, int userId) {
18196        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18197        int uid = Binder.getCallingUid();
18198        enforceCrossUserPermission(uid, userId,
18199                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18200        // reader
18201        synchronized (mPackages) {
18202            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18203        }
18204    }
18205
18206    @Override
18207    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18208        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18209        int uid = Binder.getCallingUid();
18210        enforceCrossUserPermission(uid, userId,
18211                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18212        // reader
18213        synchronized (mPackages) {
18214            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18215        }
18216    }
18217
18218    @Override
18219    public void enterSafeMode() {
18220        enforceSystemOrRoot("Only the system can request entering safe mode");
18221
18222        if (!mSystemReady) {
18223            mSafeMode = true;
18224        }
18225    }
18226
18227    @Override
18228    public void systemReady() {
18229        mSystemReady = true;
18230
18231        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18232        // disabled after already being started.
18233        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18234                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18235
18236        // Read the compatibilty setting when the system is ready.
18237        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18238                mContext.getContentResolver(),
18239                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18240        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18241        if (DEBUG_SETTINGS) {
18242            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18243        }
18244
18245        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18246
18247        synchronized (mPackages) {
18248            // Verify that all of the preferred activity components actually
18249            // exist.  It is possible for applications to be updated and at
18250            // that point remove a previously declared activity component that
18251            // had been set as a preferred activity.  We try to clean this up
18252            // the next time we encounter that preferred activity, but it is
18253            // possible for the user flow to never be able to return to that
18254            // situation so here we do a sanity check to make sure we haven't
18255            // left any junk around.
18256            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18257            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18258                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18259                removed.clear();
18260                for (PreferredActivity pa : pir.filterSet()) {
18261                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18262                        removed.add(pa);
18263                    }
18264                }
18265                if (removed.size() > 0) {
18266                    for (int r=0; r<removed.size(); r++) {
18267                        PreferredActivity pa = removed.get(r);
18268                        Slog.w(TAG, "Removing dangling preferred activity: "
18269                                + pa.mPref.mComponent);
18270                        pir.removeFilter(pa);
18271                    }
18272                    mSettings.writePackageRestrictionsLPr(
18273                            mSettings.mPreferredActivities.keyAt(i));
18274                }
18275            }
18276
18277            for (int userId : UserManagerService.getInstance().getUserIds()) {
18278                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18279                    grantPermissionsUserIds = ArrayUtils.appendInt(
18280                            grantPermissionsUserIds, userId);
18281                }
18282            }
18283        }
18284        sUserManager.systemReady();
18285
18286        // If we upgraded grant all default permissions before kicking off.
18287        for (int userId : grantPermissionsUserIds) {
18288            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18289        }
18290
18291        // If we did not grant default permissions, we preload from this the
18292        // default permission exceptions lazily to ensure we don't hit the
18293        // disk on a new user creation.
18294        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18295            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18296        }
18297
18298        // Kick off any messages waiting for system ready
18299        if (mPostSystemReadyMessages != null) {
18300            for (Message msg : mPostSystemReadyMessages) {
18301                msg.sendToTarget();
18302            }
18303            mPostSystemReadyMessages = null;
18304        }
18305
18306        // Watch for external volumes that come and go over time
18307        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18308        storage.registerListener(mStorageListener);
18309
18310        mInstallerService.systemReady();
18311        mPackageDexOptimizer.systemReady();
18312
18313        MountServiceInternal mountServiceInternal = LocalServices.getService(
18314                MountServiceInternal.class);
18315        mountServiceInternal.addExternalStoragePolicy(
18316                new MountServiceInternal.ExternalStorageMountPolicy() {
18317            @Override
18318            public int getMountMode(int uid, String packageName) {
18319                if (Process.isIsolated(uid)) {
18320                    return Zygote.MOUNT_EXTERNAL_NONE;
18321                }
18322                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18323                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18324                }
18325                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18326                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18327                }
18328                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18329                    return Zygote.MOUNT_EXTERNAL_READ;
18330                }
18331                return Zygote.MOUNT_EXTERNAL_WRITE;
18332            }
18333
18334            @Override
18335            public boolean hasExternalStorage(int uid, String packageName) {
18336                return true;
18337            }
18338        });
18339
18340        // Now that we're mostly running, clean up stale users and apps
18341        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18342        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18343    }
18344
18345    @Override
18346    public boolean isSafeMode() {
18347        return mSafeMode;
18348    }
18349
18350    @Override
18351    public boolean hasSystemUidErrors() {
18352        return mHasSystemUidErrors;
18353    }
18354
18355    static String arrayToString(int[] array) {
18356        StringBuffer buf = new StringBuffer(128);
18357        buf.append('[');
18358        if (array != null) {
18359            for (int i=0; i<array.length; i++) {
18360                if (i > 0) buf.append(", ");
18361                buf.append(array[i]);
18362            }
18363        }
18364        buf.append(']');
18365        return buf.toString();
18366    }
18367
18368    static class DumpState {
18369        public static final int DUMP_LIBS = 1 << 0;
18370        public static final int DUMP_FEATURES = 1 << 1;
18371        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18372        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18373        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18374        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18375        public static final int DUMP_PERMISSIONS = 1 << 6;
18376        public static final int DUMP_PACKAGES = 1 << 7;
18377        public static final int DUMP_SHARED_USERS = 1 << 8;
18378        public static final int DUMP_MESSAGES = 1 << 9;
18379        public static final int DUMP_PROVIDERS = 1 << 10;
18380        public static final int DUMP_VERIFIERS = 1 << 11;
18381        public static final int DUMP_PREFERRED = 1 << 12;
18382        public static final int DUMP_PREFERRED_XML = 1 << 13;
18383        public static final int DUMP_KEYSETS = 1 << 14;
18384        public static final int DUMP_VERSION = 1 << 15;
18385        public static final int DUMP_INSTALLS = 1 << 16;
18386        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18387        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18388        public static final int DUMP_FROZEN = 1 << 19;
18389        public static final int DUMP_DEXOPT = 1 << 20;
18390        public static final int DUMP_COMPILER_STATS = 1 << 21;
18391
18392        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18393
18394        private int mTypes;
18395
18396        private int mOptions;
18397
18398        private boolean mTitlePrinted;
18399
18400        private SharedUserSetting mSharedUser;
18401
18402        public boolean isDumping(int type) {
18403            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18404                return true;
18405            }
18406
18407            return (mTypes & type) != 0;
18408        }
18409
18410        public void setDump(int type) {
18411            mTypes |= type;
18412        }
18413
18414        public boolean isOptionEnabled(int option) {
18415            return (mOptions & option) != 0;
18416        }
18417
18418        public void setOptionEnabled(int option) {
18419            mOptions |= option;
18420        }
18421
18422        public boolean onTitlePrinted() {
18423            final boolean printed = mTitlePrinted;
18424            mTitlePrinted = true;
18425            return printed;
18426        }
18427
18428        public boolean getTitlePrinted() {
18429            return mTitlePrinted;
18430        }
18431
18432        public void setTitlePrinted(boolean enabled) {
18433            mTitlePrinted = enabled;
18434        }
18435
18436        public SharedUserSetting getSharedUser() {
18437            return mSharedUser;
18438        }
18439
18440        public void setSharedUser(SharedUserSetting user) {
18441            mSharedUser = user;
18442        }
18443    }
18444
18445    @Override
18446    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18447            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18448        (new PackageManagerShellCommand(this)).exec(
18449                this, in, out, err, args, resultReceiver);
18450    }
18451
18452    @Override
18453    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18454        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18455                != PackageManager.PERMISSION_GRANTED) {
18456            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18457                    + Binder.getCallingPid()
18458                    + ", uid=" + Binder.getCallingUid()
18459                    + " without permission "
18460                    + android.Manifest.permission.DUMP);
18461            return;
18462        }
18463
18464        DumpState dumpState = new DumpState();
18465        boolean fullPreferred = false;
18466        boolean checkin = false;
18467
18468        String packageName = null;
18469        ArraySet<String> permissionNames = null;
18470
18471        int opti = 0;
18472        while (opti < args.length) {
18473            String opt = args[opti];
18474            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18475                break;
18476            }
18477            opti++;
18478
18479            if ("-a".equals(opt)) {
18480                // Right now we only know how to print all.
18481            } else if ("-h".equals(opt)) {
18482                pw.println("Package manager dump options:");
18483                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18484                pw.println("    --checkin: dump for a checkin");
18485                pw.println("    -f: print details of intent filters");
18486                pw.println("    -h: print this help");
18487                pw.println("  cmd may be one of:");
18488                pw.println("    l[ibraries]: list known shared libraries");
18489                pw.println("    f[eatures]: list device features");
18490                pw.println("    k[eysets]: print known keysets");
18491                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18492                pw.println("    perm[issions]: dump permissions");
18493                pw.println("    permission [name ...]: dump declaration and use of given permission");
18494                pw.println("    pref[erred]: print preferred package settings");
18495                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18496                pw.println("    prov[iders]: dump content providers");
18497                pw.println("    p[ackages]: dump installed packages");
18498                pw.println("    s[hared-users]: dump shared user IDs");
18499                pw.println("    m[essages]: print collected runtime messages");
18500                pw.println("    v[erifiers]: print package verifier info");
18501                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18502                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18503                pw.println("    version: print database version info");
18504                pw.println("    write: write current settings now");
18505                pw.println("    installs: details about install sessions");
18506                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18507                pw.println("    dexopt: dump dexopt state");
18508                pw.println("    compiler-stats: dump compiler statistics");
18509                pw.println("    <package.name>: info about given package");
18510                return;
18511            } else if ("--checkin".equals(opt)) {
18512                checkin = true;
18513            } else if ("-f".equals(opt)) {
18514                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18515            } else {
18516                pw.println("Unknown argument: " + opt + "; use -h for help");
18517            }
18518        }
18519
18520        // Is the caller requesting to dump a particular piece of data?
18521        if (opti < args.length) {
18522            String cmd = args[opti];
18523            opti++;
18524            // Is this a package name?
18525            if ("android".equals(cmd) || cmd.contains(".")) {
18526                packageName = cmd;
18527                // When dumping a single package, we always dump all of its
18528                // filter information since the amount of data will be reasonable.
18529                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18530            } else if ("check-permission".equals(cmd)) {
18531                if (opti >= args.length) {
18532                    pw.println("Error: check-permission missing permission argument");
18533                    return;
18534                }
18535                String perm = args[opti];
18536                opti++;
18537                if (opti >= args.length) {
18538                    pw.println("Error: check-permission missing package argument");
18539                    return;
18540                }
18541                String pkg = args[opti];
18542                opti++;
18543                int user = UserHandle.getUserId(Binder.getCallingUid());
18544                if (opti < args.length) {
18545                    try {
18546                        user = Integer.parseInt(args[opti]);
18547                    } catch (NumberFormatException e) {
18548                        pw.println("Error: check-permission user argument is not a number: "
18549                                + args[opti]);
18550                        return;
18551                    }
18552                }
18553                pw.println(checkPermission(perm, pkg, user));
18554                return;
18555            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18556                dumpState.setDump(DumpState.DUMP_LIBS);
18557            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18558                dumpState.setDump(DumpState.DUMP_FEATURES);
18559            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18560                if (opti >= args.length) {
18561                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18562                            | DumpState.DUMP_SERVICE_RESOLVERS
18563                            | DumpState.DUMP_RECEIVER_RESOLVERS
18564                            | DumpState.DUMP_CONTENT_RESOLVERS);
18565                } else {
18566                    while (opti < args.length) {
18567                        String name = args[opti];
18568                        if ("a".equals(name) || "activity".equals(name)) {
18569                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18570                        } else if ("s".equals(name) || "service".equals(name)) {
18571                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18572                        } else if ("r".equals(name) || "receiver".equals(name)) {
18573                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18574                        } else if ("c".equals(name) || "content".equals(name)) {
18575                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18576                        } else {
18577                            pw.println("Error: unknown resolver table type: " + name);
18578                            return;
18579                        }
18580                        opti++;
18581                    }
18582                }
18583            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18584                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18585            } else if ("permission".equals(cmd)) {
18586                if (opti >= args.length) {
18587                    pw.println("Error: permission requires permission name");
18588                    return;
18589                }
18590                permissionNames = new ArraySet<>();
18591                while (opti < args.length) {
18592                    permissionNames.add(args[opti]);
18593                    opti++;
18594                }
18595                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18596                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18597            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18598                dumpState.setDump(DumpState.DUMP_PREFERRED);
18599            } else if ("preferred-xml".equals(cmd)) {
18600                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18601                if (opti < args.length && "--full".equals(args[opti])) {
18602                    fullPreferred = true;
18603                    opti++;
18604                }
18605            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18606                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18607            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18608                dumpState.setDump(DumpState.DUMP_PACKAGES);
18609            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18610                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18611            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18612                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18613            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18614                dumpState.setDump(DumpState.DUMP_MESSAGES);
18615            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18616                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18617            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18618                    || "intent-filter-verifiers".equals(cmd)) {
18619                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18620            } else if ("version".equals(cmd)) {
18621                dumpState.setDump(DumpState.DUMP_VERSION);
18622            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18623                dumpState.setDump(DumpState.DUMP_KEYSETS);
18624            } else if ("installs".equals(cmd)) {
18625                dumpState.setDump(DumpState.DUMP_INSTALLS);
18626            } else if ("frozen".equals(cmd)) {
18627                dumpState.setDump(DumpState.DUMP_FROZEN);
18628            } else if ("dexopt".equals(cmd)) {
18629                dumpState.setDump(DumpState.DUMP_DEXOPT);
18630            } else if ("compiler-stats".equals(cmd)) {
18631                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18632            } else if ("write".equals(cmd)) {
18633                synchronized (mPackages) {
18634                    mSettings.writeLPr();
18635                    pw.println("Settings written.");
18636                    return;
18637                }
18638            }
18639        }
18640
18641        if (checkin) {
18642            pw.println("vers,1");
18643        }
18644
18645        // reader
18646        synchronized (mPackages) {
18647            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18648                if (!checkin) {
18649                    if (dumpState.onTitlePrinted())
18650                        pw.println();
18651                    pw.println("Database versions:");
18652                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18653                }
18654            }
18655
18656            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18657                if (!checkin) {
18658                    if (dumpState.onTitlePrinted())
18659                        pw.println();
18660                    pw.println("Verifiers:");
18661                    pw.print("  Required: ");
18662                    pw.print(mRequiredVerifierPackage);
18663                    pw.print(" (uid=");
18664                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18665                            UserHandle.USER_SYSTEM));
18666                    pw.println(")");
18667                } else if (mRequiredVerifierPackage != null) {
18668                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18669                    pw.print(",");
18670                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18671                            UserHandle.USER_SYSTEM));
18672                }
18673            }
18674
18675            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18676                    packageName == null) {
18677                if (mIntentFilterVerifierComponent != null) {
18678                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18679                    if (!checkin) {
18680                        if (dumpState.onTitlePrinted())
18681                            pw.println();
18682                        pw.println("Intent Filter Verifier:");
18683                        pw.print("  Using: ");
18684                        pw.print(verifierPackageName);
18685                        pw.print(" (uid=");
18686                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18687                                UserHandle.USER_SYSTEM));
18688                        pw.println(")");
18689                    } else if (verifierPackageName != null) {
18690                        pw.print("ifv,"); pw.print(verifierPackageName);
18691                        pw.print(",");
18692                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18693                                UserHandle.USER_SYSTEM));
18694                    }
18695                } else {
18696                    pw.println();
18697                    pw.println("No Intent Filter Verifier available!");
18698                }
18699            }
18700
18701            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18702                boolean printedHeader = false;
18703                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18704                while (it.hasNext()) {
18705                    String name = it.next();
18706                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18707                    if (!checkin) {
18708                        if (!printedHeader) {
18709                            if (dumpState.onTitlePrinted())
18710                                pw.println();
18711                            pw.println("Libraries:");
18712                            printedHeader = true;
18713                        }
18714                        pw.print("  ");
18715                    } else {
18716                        pw.print("lib,");
18717                    }
18718                    pw.print(name);
18719                    if (!checkin) {
18720                        pw.print(" -> ");
18721                    }
18722                    if (ent.path != null) {
18723                        if (!checkin) {
18724                            pw.print("(jar) ");
18725                            pw.print(ent.path);
18726                        } else {
18727                            pw.print(",jar,");
18728                            pw.print(ent.path);
18729                        }
18730                    } else {
18731                        if (!checkin) {
18732                            pw.print("(apk) ");
18733                            pw.print(ent.apk);
18734                        } else {
18735                            pw.print(",apk,");
18736                            pw.print(ent.apk);
18737                        }
18738                    }
18739                    pw.println();
18740                }
18741            }
18742
18743            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18744                if (dumpState.onTitlePrinted())
18745                    pw.println();
18746                if (!checkin) {
18747                    pw.println("Features:");
18748                }
18749
18750                for (FeatureInfo feat : mAvailableFeatures.values()) {
18751                    if (checkin) {
18752                        pw.print("feat,");
18753                        pw.print(feat.name);
18754                        pw.print(",");
18755                        pw.println(feat.version);
18756                    } else {
18757                        pw.print("  ");
18758                        pw.print(feat.name);
18759                        if (feat.version > 0) {
18760                            pw.print(" version=");
18761                            pw.print(feat.version);
18762                        }
18763                        pw.println();
18764                    }
18765                }
18766            }
18767
18768            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18769                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18770                        : "Activity Resolver Table:", "  ", packageName,
18771                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18772                    dumpState.setTitlePrinted(true);
18773                }
18774            }
18775            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18776                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18777                        : "Receiver Resolver Table:", "  ", packageName,
18778                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18779                    dumpState.setTitlePrinted(true);
18780                }
18781            }
18782            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18783                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18784                        : "Service Resolver Table:", "  ", packageName,
18785                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18786                    dumpState.setTitlePrinted(true);
18787                }
18788            }
18789            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18790                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18791                        : "Provider Resolver Table:", "  ", packageName,
18792                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18793                    dumpState.setTitlePrinted(true);
18794                }
18795            }
18796
18797            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18798                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18799                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18800                    int user = mSettings.mPreferredActivities.keyAt(i);
18801                    if (pir.dump(pw,
18802                            dumpState.getTitlePrinted()
18803                                ? "\nPreferred Activities User " + user + ":"
18804                                : "Preferred Activities User " + user + ":", "  ",
18805                            packageName, true, false)) {
18806                        dumpState.setTitlePrinted(true);
18807                    }
18808                }
18809            }
18810
18811            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18812                pw.flush();
18813                FileOutputStream fout = new FileOutputStream(fd);
18814                BufferedOutputStream str = new BufferedOutputStream(fout);
18815                XmlSerializer serializer = new FastXmlSerializer();
18816                try {
18817                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18818                    serializer.startDocument(null, true);
18819                    serializer.setFeature(
18820                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18821                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18822                    serializer.endDocument();
18823                    serializer.flush();
18824                } catch (IllegalArgumentException e) {
18825                    pw.println("Failed writing: " + e);
18826                } catch (IllegalStateException e) {
18827                    pw.println("Failed writing: " + e);
18828                } catch (IOException e) {
18829                    pw.println("Failed writing: " + e);
18830                }
18831            }
18832
18833            if (!checkin
18834                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18835                    && packageName == null) {
18836                pw.println();
18837                int count = mSettings.mPackages.size();
18838                if (count == 0) {
18839                    pw.println("No applications!");
18840                    pw.println();
18841                } else {
18842                    final String prefix = "  ";
18843                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18844                    if (allPackageSettings.size() == 0) {
18845                        pw.println("No domain preferred apps!");
18846                        pw.println();
18847                    } else {
18848                        pw.println("App verification status:");
18849                        pw.println();
18850                        count = 0;
18851                        for (PackageSetting ps : allPackageSettings) {
18852                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18853                            if (ivi == null || ivi.getPackageName() == null) continue;
18854                            pw.println(prefix + "Package: " + ivi.getPackageName());
18855                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18856                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18857                            pw.println();
18858                            count++;
18859                        }
18860                        if (count == 0) {
18861                            pw.println(prefix + "No app verification established.");
18862                            pw.println();
18863                        }
18864                        for (int userId : sUserManager.getUserIds()) {
18865                            pw.println("App linkages for user " + userId + ":");
18866                            pw.println();
18867                            count = 0;
18868                            for (PackageSetting ps : allPackageSettings) {
18869                                final long status = ps.getDomainVerificationStatusForUser(userId);
18870                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18871                                    continue;
18872                                }
18873                                pw.println(prefix + "Package: " + ps.name);
18874                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18875                                String statusStr = IntentFilterVerificationInfo.
18876                                        getStatusStringFromValue(status);
18877                                pw.println(prefix + "Status:  " + statusStr);
18878                                pw.println();
18879                                count++;
18880                            }
18881                            if (count == 0) {
18882                                pw.println(prefix + "No configured app linkages.");
18883                                pw.println();
18884                            }
18885                        }
18886                    }
18887                }
18888            }
18889
18890            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18891                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18892                if (packageName == null && permissionNames == null) {
18893                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18894                        if (iperm == 0) {
18895                            if (dumpState.onTitlePrinted())
18896                                pw.println();
18897                            pw.println("AppOp Permissions:");
18898                        }
18899                        pw.print("  AppOp Permission ");
18900                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18901                        pw.println(":");
18902                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18903                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18904                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18905                        }
18906                    }
18907                }
18908            }
18909
18910            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18911                boolean printedSomething = false;
18912                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18913                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18914                        continue;
18915                    }
18916                    if (!printedSomething) {
18917                        if (dumpState.onTitlePrinted())
18918                            pw.println();
18919                        pw.println("Registered ContentProviders:");
18920                        printedSomething = true;
18921                    }
18922                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18923                    pw.print("    "); pw.println(p.toString());
18924                }
18925                printedSomething = false;
18926                for (Map.Entry<String, PackageParser.Provider> entry :
18927                        mProvidersByAuthority.entrySet()) {
18928                    PackageParser.Provider p = entry.getValue();
18929                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18930                        continue;
18931                    }
18932                    if (!printedSomething) {
18933                        if (dumpState.onTitlePrinted())
18934                            pw.println();
18935                        pw.println("ContentProvider Authorities:");
18936                        printedSomething = true;
18937                    }
18938                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18939                    pw.print("    "); pw.println(p.toString());
18940                    if (p.info != null && p.info.applicationInfo != null) {
18941                        final String appInfo = p.info.applicationInfo.toString();
18942                        pw.print("      applicationInfo="); pw.println(appInfo);
18943                    }
18944                }
18945            }
18946
18947            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18948                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18949            }
18950
18951            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18952                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18953            }
18954
18955            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18956                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18957            }
18958
18959            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18960                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18961            }
18962
18963            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18964                // XXX should handle packageName != null by dumping only install data that
18965                // the given package is involved with.
18966                if (dumpState.onTitlePrinted()) pw.println();
18967                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18968            }
18969
18970            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18971                // XXX should handle packageName != null by dumping only install data that
18972                // the given package is involved with.
18973                if (dumpState.onTitlePrinted()) pw.println();
18974
18975                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18976                ipw.println();
18977                ipw.println("Frozen packages:");
18978                ipw.increaseIndent();
18979                if (mFrozenPackages.size() == 0) {
18980                    ipw.println("(none)");
18981                } else {
18982                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18983                        ipw.println(mFrozenPackages.valueAt(i));
18984                    }
18985                }
18986                ipw.decreaseIndent();
18987            }
18988
18989            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18990                if (dumpState.onTitlePrinted()) pw.println();
18991                dumpDexoptStateLPr(pw, packageName);
18992            }
18993
18994            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
18995                if (dumpState.onTitlePrinted()) pw.println();
18996                dumpCompilerStatsLPr(pw, packageName);
18997            }
18998
18999            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
19000                if (dumpState.onTitlePrinted()) pw.println();
19001                mSettings.dumpReadMessagesLPr(pw, dumpState);
19002
19003                pw.println();
19004                pw.println("Package warning messages:");
19005                BufferedReader in = null;
19006                String line = null;
19007                try {
19008                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19009                    while ((line = in.readLine()) != null) {
19010                        if (line.contains("ignored: updated version")) continue;
19011                        pw.println(line);
19012                    }
19013                } catch (IOException ignored) {
19014                } finally {
19015                    IoUtils.closeQuietly(in);
19016                }
19017            }
19018
19019            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
19020                BufferedReader in = null;
19021                String line = null;
19022                try {
19023                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19024                    while ((line = in.readLine()) != null) {
19025                        if (line.contains("ignored: updated version")) continue;
19026                        pw.print("msg,");
19027                        pw.println(line);
19028                    }
19029                } catch (IOException ignored) {
19030                } finally {
19031                    IoUtils.closeQuietly(in);
19032                }
19033            }
19034        }
19035    }
19036
19037    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
19038        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19039        ipw.println();
19040        ipw.println("Dexopt state:");
19041        ipw.increaseIndent();
19042        Collection<PackageParser.Package> packages = null;
19043        if (packageName != null) {
19044            PackageParser.Package targetPackage = mPackages.get(packageName);
19045            if (targetPackage != null) {
19046                packages = Collections.singletonList(targetPackage);
19047            } else {
19048                ipw.println("Unable to find package: " + packageName);
19049                return;
19050            }
19051        } else {
19052            packages = mPackages.values();
19053        }
19054
19055        for (PackageParser.Package pkg : packages) {
19056            ipw.println("[" + pkg.packageName + "]");
19057            ipw.increaseIndent();
19058            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19059            ipw.decreaseIndent();
19060        }
19061    }
19062
19063    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19064        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19065        ipw.println();
19066        ipw.println("Compiler stats:");
19067        ipw.increaseIndent();
19068        Collection<PackageParser.Package> packages = null;
19069        if (packageName != null) {
19070            PackageParser.Package targetPackage = mPackages.get(packageName);
19071            if (targetPackage != null) {
19072                packages = Collections.singletonList(targetPackage);
19073            } else {
19074                ipw.println("Unable to find package: " + packageName);
19075                return;
19076            }
19077        } else {
19078            packages = mPackages.values();
19079        }
19080
19081        for (PackageParser.Package pkg : packages) {
19082            ipw.println("[" + pkg.packageName + "]");
19083            ipw.increaseIndent();
19084
19085            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19086            if (stats == null) {
19087                ipw.println("(No recorded stats)");
19088            } else {
19089                stats.dump(ipw);
19090            }
19091            ipw.decreaseIndent();
19092        }
19093    }
19094
19095    private String dumpDomainString(String packageName) {
19096        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19097                .getList();
19098        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19099
19100        ArraySet<String> result = new ArraySet<>();
19101        if (iviList.size() > 0) {
19102            for (IntentFilterVerificationInfo ivi : iviList) {
19103                for (String host : ivi.getDomains()) {
19104                    result.add(host);
19105                }
19106            }
19107        }
19108        if (filters != null && filters.size() > 0) {
19109            for (IntentFilter filter : filters) {
19110                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19111                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19112                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19113                    result.addAll(filter.getHostsList());
19114                }
19115            }
19116        }
19117
19118        StringBuilder sb = new StringBuilder(result.size() * 16);
19119        for (String domain : result) {
19120            if (sb.length() > 0) sb.append(" ");
19121            sb.append(domain);
19122        }
19123        return sb.toString();
19124    }
19125
19126    // ------- apps on sdcard specific code -------
19127    static final boolean DEBUG_SD_INSTALL = false;
19128
19129    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19130
19131    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19132
19133    private boolean mMediaMounted = false;
19134
19135    static String getEncryptKey() {
19136        try {
19137            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19138                    SD_ENCRYPTION_KEYSTORE_NAME);
19139            if (sdEncKey == null) {
19140                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19141                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19142                if (sdEncKey == null) {
19143                    Slog.e(TAG, "Failed to create encryption keys");
19144                    return null;
19145                }
19146            }
19147            return sdEncKey;
19148        } catch (NoSuchAlgorithmException nsae) {
19149            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19150            return null;
19151        } catch (IOException ioe) {
19152            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19153            return null;
19154        }
19155    }
19156
19157    /*
19158     * Update media status on PackageManager.
19159     */
19160    @Override
19161    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19162        int callingUid = Binder.getCallingUid();
19163        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19164            throw new SecurityException("Media status can only be updated by the system");
19165        }
19166        // reader; this apparently protects mMediaMounted, but should probably
19167        // be a different lock in that case.
19168        synchronized (mPackages) {
19169            Log.i(TAG, "Updating external media status from "
19170                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19171                    + (mediaStatus ? "mounted" : "unmounted"));
19172            if (DEBUG_SD_INSTALL)
19173                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19174                        + ", mMediaMounted=" + mMediaMounted);
19175            if (mediaStatus == mMediaMounted) {
19176                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19177                        : 0, -1);
19178                mHandler.sendMessage(msg);
19179                return;
19180            }
19181            mMediaMounted = mediaStatus;
19182        }
19183        // Queue up an async operation since the package installation may take a
19184        // little while.
19185        mHandler.post(new Runnable() {
19186            public void run() {
19187                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19188            }
19189        });
19190    }
19191
19192    /**
19193     * Called by MountService when the initial ASECs to scan are available.
19194     * Should block until all the ASEC containers are finished being scanned.
19195     */
19196    public void scanAvailableAsecs() {
19197        updateExternalMediaStatusInner(true, false, false);
19198    }
19199
19200    /*
19201     * Collect information of applications on external media, map them against
19202     * existing containers and update information based on current mount status.
19203     * Please note that we always have to report status if reportStatus has been
19204     * set to true especially when unloading packages.
19205     */
19206    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19207            boolean externalStorage) {
19208        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19209        int[] uidArr = EmptyArray.INT;
19210
19211        final String[] list = PackageHelper.getSecureContainerList();
19212        if (ArrayUtils.isEmpty(list)) {
19213            Log.i(TAG, "No secure containers found");
19214        } else {
19215            // Process list of secure containers and categorize them
19216            // as active or stale based on their package internal state.
19217
19218            // reader
19219            synchronized (mPackages) {
19220                for (String cid : list) {
19221                    // Leave stages untouched for now; installer service owns them
19222                    if (PackageInstallerService.isStageName(cid)) continue;
19223
19224                    if (DEBUG_SD_INSTALL)
19225                        Log.i(TAG, "Processing container " + cid);
19226                    String pkgName = getAsecPackageName(cid);
19227                    if (pkgName == null) {
19228                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19229                        continue;
19230                    }
19231                    if (DEBUG_SD_INSTALL)
19232                        Log.i(TAG, "Looking for pkg : " + pkgName);
19233
19234                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19235                    if (ps == null) {
19236                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19237                        continue;
19238                    }
19239
19240                    /*
19241                     * Skip packages that are not external if we're unmounting
19242                     * external storage.
19243                     */
19244                    if (externalStorage && !isMounted && !isExternal(ps)) {
19245                        continue;
19246                    }
19247
19248                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19249                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19250                    // The package status is changed only if the code path
19251                    // matches between settings and the container id.
19252                    if (ps.codePathString != null
19253                            && ps.codePathString.startsWith(args.getCodePath())) {
19254                        if (DEBUG_SD_INSTALL) {
19255                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19256                                    + " at code path: " + ps.codePathString);
19257                        }
19258
19259                        // We do have a valid package installed on sdcard
19260                        processCids.put(args, ps.codePathString);
19261                        final int uid = ps.appId;
19262                        if (uid != -1) {
19263                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19264                        }
19265                    } else {
19266                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19267                                + ps.codePathString);
19268                    }
19269                }
19270            }
19271
19272            Arrays.sort(uidArr);
19273        }
19274
19275        // Process packages with valid entries.
19276        if (isMounted) {
19277            if (DEBUG_SD_INSTALL)
19278                Log.i(TAG, "Loading packages");
19279            loadMediaPackages(processCids, uidArr, externalStorage);
19280            startCleaningPackages();
19281            mInstallerService.onSecureContainersAvailable();
19282        } else {
19283            if (DEBUG_SD_INSTALL)
19284                Log.i(TAG, "Unloading packages");
19285            unloadMediaPackages(processCids, uidArr, reportStatus);
19286        }
19287    }
19288
19289    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19290            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19291        final int size = infos.size();
19292        final String[] packageNames = new String[size];
19293        final int[] packageUids = new int[size];
19294        for (int i = 0; i < size; i++) {
19295            final ApplicationInfo info = infos.get(i);
19296            packageNames[i] = info.packageName;
19297            packageUids[i] = info.uid;
19298        }
19299        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19300                finishedReceiver);
19301    }
19302
19303    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19304            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19305        sendResourcesChangedBroadcast(mediaStatus, replacing,
19306                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19307    }
19308
19309    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19310            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19311        int size = pkgList.length;
19312        if (size > 0) {
19313            // Send broadcasts here
19314            Bundle extras = new Bundle();
19315            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19316            if (uidArr != null) {
19317                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19318            }
19319            if (replacing) {
19320                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19321            }
19322            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19323                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19324            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19325        }
19326    }
19327
19328   /*
19329     * Look at potentially valid container ids from processCids If package
19330     * information doesn't match the one on record or package scanning fails,
19331     * the cid is added to list of removeCids. We currently don't delete stale
19332     * containers.
19333     */
19334    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19335            boolean externalStorage) {
19336        ArrayList<String> pkgList = new ArrayList<String>();
19337        Set<AsecInstallArgs> keys = processCids.keySet();
19338
19339        for (AsecInstallArgs args : keys) {
19340            String codePath = processCids.get(args);
19341            if (DEBUG_SD_INSTALL)
19342                Log.i(TAG, "Loading container : " + args.cid);
19343            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19344            try {
19345                // Make sure there are no container errors first.
19346                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19347                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19348                            + " when installing from sdcard");
19349                    continue;
19350                }
19351                // Check code path here.
19352                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19353                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19354                            + " does not match one in settings " + codePath);
19355                    continue;
19356                }
19357                // Parse package
19358                int parseFlags = mDefParseFlags;
19359                if (args.isExternalAsec()) {
19360                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19361                }
19362                if (args.isFwdLocked()) {
19363                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19364                }
19365
19366                synchronized (mInstallLock) {
19367                    PackageParser.Package pkg = null;
19368                    try {
19369                        // Sadly we don't know the package name yet to freeze it
19370                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19371                                SCAN_IGNORE_FROZEN, 0, null);
19372                    } catch (PackageManagerException e) {
19373                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19374                    }
19375                    // Scan the package
19376                    if (pkg != null) {
19377                        /*
19378                         * TODO why is the lock being held? doPostInstall is
19379                         * called in other places without the lock. This needs
19380                         * to be straightened out.
19381                         */
19382                        // writer
19383                        synchronized (mPackages) {
19384                            retCode = PackageManager.INSTALL_SUCCEEDED;
19385                            pkgList.add(pkg.packageName);
19386                            // Post process args
19387                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19388                                    pkg.applicationInfo.uid);
19389                        }
19390                    } else {
19391                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19392                    }
19393                }
19394
19395            } finally {
19396                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19397                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19398                }
19399            }
19400        }
19401        // writer
19402        synchronized (mPackages) {
19403            // If the platform SDK has changed since the last time we booted,
19404            // we need to re-grant app permission to catch any new ones that
19405            // appear. This is really a hack, and means that apps can in some
19406            // cases get permissions that the user didn't initially explicitly
19407            // allow... it would be nice to have some better way to handle
19408            // this situation.
19409            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19410                    : mSettings.getInternalVersion();
19411            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19412                    : StorageManager.UUID_PRIVATE_INTERNAL;
19413
19414            int updateFlags = UPDATE_PERMISSIONS_ALL;
19415            if (ver.sdkVersion != mSdkVersion) {
19416                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19417                        + mSdkVersion + "; regranting permissions for external");
19418                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19419            }
19420            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19421
19422            // Yay, everything is now upgraded
19423            ver.forceCurrent();
19424
19425            // can downgrade to reader
19426            // Persist settings
19427            mSettings.writeLPr();
19428        }
19429        // Send a broadcast to let everyone know we are done processing
19430        if (pkgList.size() > 0) {
19431            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19432        }
19433    }
19434
19435   /*
19436     * Utility method to unload a list of specified containers
19437     */
19438    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19439        // Just unmount all valid containers.
19440        for (AsecInstallArgs arg : cidArgs) {
19441            synchronized (mInstallLock) {
19442                arg.doPostDeleteLI(false);
19443           }
19444       }
19445   }
19446
19447    /*
19448     * Unload packages mounted on external media. This involves deleting package
19449     * data from internal structures, sending broadcasts about disabled packages,
19450     * gc'ing to free up references, unmounting all secure containers
19451     * corresponding to packages on external media, and posting a
19452     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19453     * that we always have to post this message if status has been requested no
19454     * matter what.
19455     */
19456    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19457            final boolean reportStatus) {
19458        if (DEBUG_SD_INSTALL)
19459            Log.i(TAG, "unloading media packages");
19460        ArrayList<String> pkgList = new ArrayList<String>();
19461        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19462        final Set<AsecInstallArgs> keys = processCids.keySet();
19463        for (AsecInstallArgs args : keys) {
19464            String pkgName = args.getPackageName();
19465            if (DEBUG_SD_INSTALL)
19466                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19467            // Delete package internally
19468            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19469            synchronized (mInstallLock) {
19470                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19471                final boolean res;
19472                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19473                        "unloadMediaPackages")) {
19474                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19475                            null);
19476                }
19477                if (res) {
19478                    pkgList.add(pkgName);
19479                } else {
19480                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19481                    failedList.add(args);
19482                }
19483            }
19484        }
19485
19486        // reader
19487        synchronized (mPackages) {
19488            // We didn't update the settings after removing each package;
19489            // write them now for all packages.
19490            mSettings.writeLPr();
19491        }
19492
19493        // We have to absolutely send UPDATED_MEDIA_STATUS only
19494        // after confirming that all the receivers processed the ordered
19495        // broadcast when packages get disabled, force a gc to clean things up.
19496        // and unload all the containers.
19497        if (pkgList.size() > 0) {
19498            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19499                    new IIntentReceiver.Stub() {
19500                public void performReceive(Intent intent, int resultCode, String data,
19501                        Bundle extras, boolean ordered, boolean sticky,
19502                        int sendingUser) throws RemoteException {
19503                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19504                            reportStatus ? 1 : 0, 1, keys);
19505                    mHandler.sendMessage(msg);
19506                }
19507            });
19508        } else {
19509            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19510                    keys);
19511            mHandler.sendMessage(msg);
19512        }
19513    }
19514
19515    private void loadPrivatePackages(final VolumeInfo vol) {
19516        mHandler.post(new Runnable() {
19517            @Override
19518            public void run() {
19519                loadPrivatePackagesInner(vol);
19520            }
19521        });
19522    }
19523
19524    private void loadPrivatePackagesInner(VolumeInfo vol) {
19525        final String volumeUuid = vol.fsUuid;
19526        if (TextUtils.isEmpty(volumeUuid)) {
19527            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19528            return;
19529        }
19530
19531        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19532        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19533        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19534
19535        final VersionInfo ver;
19536        final List<PackageSetting> packages;
19537        synchronized (mPackages) {
19538            ver = mSettings.findOrCreateVersion(volumeUuid);
19539            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19540        }
19541
19542        for (PackageSetting ps : packages) {
19543            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19544            synchronized (mInstallLock) {
19545                final PackageParser.Package pkg;
19546                try {
19547                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19548                    loaded.add(pkg.applicationInfo);
19549
19550                } catch (PackageManagerException e) {
19551                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19552                }
19553
19554                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19555                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19556                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19557                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19558                }
19559            }
19560        }
19561
19562        // Reconcile app data for all started/unlocked users
19563        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19564        final UserManager um = mContext.getSystemService(UserManager.class);
19565        UserManagerInternal umInternal = getUserManagerInternal();
19566        for (UserInfo user : um.getUsers()) {
19567            final int flags;
19568            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19569                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19570            } else if (umInternal.isUserRunning(user.id)) {
19571                flags = StorageManager.FLAG_STORAGE_DE;
19572            } else {
19573                continue;
19574            }
19575
19576            try {
19577                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19578                synchronized (mInstallLock) {
19579                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19580                }
19581            } catch (IllegalStateException e) {
19582                // Device was probably ejected, and we'll process that event momentarily
19583                Slog.w(TAG, "Failed to prepare storage: " + e);
19584            }
19585        }
19586
19587        synchronized (mPackages) {
19588            int updateFlags = UPDATE_PERMISSIONS_ALL;
19589            if (ver.sdkVersion != mSdkVersion) {
19590                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19591                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19592                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19593            }
19594            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19595
19596            // Yay, everything is now upgraded
19597            ver.forceCurrent();
19598
19599            mSettings.writeLPr();
19600        }
19601
19602        for (PackageFreezer freezer : freezers) {
19603            freezer.close();
19604        }
19605
19606        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19607        sendResourcesChangedBroadcast(true, false, loaded, null);
19608    }
19609
19610    private void unloadPrivatePackages(final VolumeInfo vol) {
19611        mHandler.post(new Runnable() {
19612            @Override
19613            public void run() {
19614                unloadPrivatePackagesInner(vol);
19615            }
19616        });
19617    }
19618
19619    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19620        final String volumeUuid = vol.fsUuid;
19621        if (TextUtils.isEmpty(volumeUuid)) {
19622            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19623            return;
19624        }
19625
19626        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19627        synchronized (mInstallLock) {
19628        synchronized (mPackages) {
19629            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19630            for (PackageSetting ps : packages) {
19631                if (ps.pkg == null) continue;
19632
19633                final ApplicationInfo info = ps.pkg.applicationInfo;
19634                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19635                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19636
19637                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19638                        "unloadPrivatePackagesInner")) {
19639                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19640                            false, null)) {
19641                        unloaded.add(info);
19642                    } else {
19643                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19644                    }
19645                }
19646
19647                // Try very hard to release any references to this package
19648                // so we don't risk the system server being killed due to
19649                // open FDs
19650                AttributeCache.instance().removePackage(ps.name);
19651            }
19652
19653            mSettings.writeLPr();
19654        }
19655        }
19656
19657        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19658        sendResourcesChangedBroadcast(false, false, unloaded, null);
19659
19660        // Try very hard to release any references to this path so we don't risk
19661        // the system server being killed due to open FDs
19662        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19663
19664        for (int i = 0; i < 3; i++) {
19665            System.gc();
19666            System.runFinalization();
19667        }
19668    }
19669
19670    /**
19671     * Prepare storage areas for given user on all mounted devices.
19672     */
19673    void prepareUserData(int userId, int userSerial, int flags) {
19674        synchronized (mInstallLock) {
19675            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19676            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19677                final String volumeUuid = vol.getFsUuid();
19678                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19679            }
19680        }
19681    }
19682
19683    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19684            boolean allowRecover) {
19685        // Prepare storage and verify that serial numbers are consistent; if
19686        // there's a mismatch we need to destroy to avoid leaking data
19687        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19688        try {
19689            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19690
19691            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19692                UserManagerService.enforceSerialNumber(
19693                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19694                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19695                    UserManagerService.enforceSerialNumber(
19696                            Environment.getDataSystemDeDirectory(userId), userSerial);
19697                }
19698            }
19699            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19700                UserManagerService.enforceSerialNumber(
19701                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19702                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19703                    UserManagerService.enforceSerialNumber(
19704                            Environment.getDataSystemCeDirectory(userId), userSerial);
19705                }
19706            }
19707
19708            synchronized (mInstallLock) {
19709                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19710            }
19711        } catch (Exception e) {
19712            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19713                    + " because we failed to prepare: " + e);
19714            destroyUserDataLI(volumeUuid, userId,
19715                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19716
19717            if (allowRecover) {
19718                // Try one last time; if we fail again we're really in trouble
19719                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19720            }
19721        }
19722    }
19723
19724    /**
19725     * Destroy storage areas for given user on all mounted devices.
19726     */
19727    void destroyUserData(int userId, int flags) {
19728        synchronized (mInstallLock) {
19729            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19730            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19731                final String volumeUuid = vol.getFsUuid();
19732                destroyUserDataLI(volumeUuid, userId, flags);
19733            }
19734        }
19735    }
19736
19737    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19738        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19739        try {
19740            // Clean up app data, profile data, and media data
19741            mInstaller.destroyUserData(volumeUuid, userId, flags);
19742
19743            // Clean up system data
19744            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19745                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19746                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19747                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19748                }
19749                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19750                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19751                }
19752            }
19753
19754            // Data with special labels is now gone, so finish the job
19755            storage.destroyUserStorage(volumeUuid, userId, flags);
19756
19757        } catch (Exception e) {
19758            logCriticalInfo(Log.WARN,
19759                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19760        }
19761    }
19762
19763    /**
19764     * Examine all users present on given mounted volume, and destroy data
19765     * belonging to users that are no longer valid, or whose user ID has been
19766     * recycled.
19767     */
19768    private void reconcileUsers(String volumeUuid) {
19769        final List<File> files = new ArrayList<>();
19770        Collections.addAll(files, FileUtils
19771                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19772        Collections.addAll(files, FileUtils
19773                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19774        Collections.addAll(files, FileUtils
19775                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19776        Collections.addAll(files, FileUtils
19777                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19778        for (File file : files) {
19779            if (!file.isDirectory()) continue;
19780
19781            final int userId;
19782            final UserInfo info;
19783            try {
19784                userId = Integer.parseInt(file.getName());
19785                info = sUserManager.getUserInfo(userId);
19786            } catch (NumberFormatException e) {
19787                Slog.w(TAG, "Invalid user directory " + file);
19788                continue;
19789            }
19790
19791            boolean destroyUser = false;
19792            if (info == null) {
19793                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19794                        + " because no matching user was found");
19795                destroyUser = true;
19796            } else if (!mOnlyCore) {
19797                try {
19798                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19799                } catch (IOException e) {
19800                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19801                            + " because we failed to enforce serial number: " + e);
19802                    destroyUser = true;
19803                }
19804            }
19805
19806            if (destroyUser) {
19807                synchronized (mInstallLock) {
19808                    destroyUserDataLI(volumeUuid, userId,
19809                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19810                }
19811            }
19812        }
19813    }
19814
19815    private void assertPackageKnown(String volumeUuid, String packageName)
19816            throws PackageManagerException {
19817        synchronized (mPackages) {
19818            final PackageSetting ps = mSettings.mPackages.get(packageName);
19819            if (ps == null) {
19820                throw new PackageManagerException("Package " + packageName + " is unknown");
19821            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19822                throw new PackageManagerException(
19823                        "Package " + packageName + " found on unknown volume " + volumeUuid
19824                                + "; expected volume " + ps.volumeUuid);
19825            }
19826        }
19827    }
19828
19829    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19830            throws PackageManagerException {
19831        synchronized (mPackages) {
19832            final PackageSetting ps = mSettings.mPackages.get(packageName);
19833            if (ps == null) {
19834                throw new PackageManagerException("Package " + packageName + " is unknown");
19835            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19836                throw new PackageManagerException(
19837                        "Package " + packageName + " found on unknown volume " + volumeUuid
19838                                + "; expected volume " + ps.volumeUuid);
19839            } else if (!ps.getInstalled(userId)) {
19840                throw new PackageManagerException(
19841                        "Package " + packageName + " not installed for user " + userId);
19842            }
19843        }
19844    }
19845
19846    /**
19847     * Examine all apps present on given mounted volume, and destroy apps that
19848     * aren't expected, either due to uninstallation or reinstallation on
19849     * another volume.
19850     */
19851    private void reconcileApps(String volumeUuid) {
19852        final File[] files = FileUtils
19853                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19854        for (File file : files) {
19855            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19856                    && !PackageInstallerService.isStageName(file.getName());
19857            if (!isPackage) {
19858                // Ignore entries which are not packages
19859                continue;
19860            }
19861
19862            try {
19863                final PackageLite pkg = PackageParser.parsePackageLite(file,
19864                        PackageParser.PARSE_MUST_BE_APK);
19865                assertPackageKnown(volumeUuid, pkg.packageName);
19866
19867            } catch (PackageParserException | PackageManagerException e) {
19868                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19869                synchronized (mInstallLock) {
19870                    removeCodePathLI(file);
19871                }
19872            }
19873        }
19874    }
19875
19876    /**
19877     * Reconcile all app data for the given user.
19878     * <p>
19879     * Verifies that directories exist and that ownership and labeling is
19880     * correct for all installed apps on all mounted volumes.
19881     */
19882    void reconcileAppsData(int userId, int flags) {
19883        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19884        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19885            final String volumeUuid = vol.getFsUuid();
19886            synchronized (mInstallLock) {
19887                reconcileAppsDataLI(volumeUuid, userId, flags);
19888            }
19889        }
19890    }
19891
19892    /**
19893     * Reconcile all app data on given mounted volume.
19894     * <p>
19895     * Destroys app data that isn't expected, either due to uninstallation or
19896     * reinstallation on another volume.
19897     * <p>
19898     * Verifies that directories exist and that ownership and labeling is
19899     * correct for all installed apps.
19900     */
19901    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19902        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19903                + Integer.toHexString(flags));
19904
19905        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19906        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19907
19908        // First look for stale data that doesn't belong, and check if things
19909        // have changed since we did our last restorecon
19910        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19911            if (StorageManager.isFileEncryptedNativeOrEmulated()
19912                    && !StorageManager.isUserKeyUnlocked(userId)) {
19913                throw new RuntimeException(
19914                        "Yikes, someone asked us to reconcile CE storage while " + userId
19915                                + " was still locked; this would have caused massive data loss!");
19916            }
19917
19918            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19919            for (File file : files) {
19920                final String packageName = file.getName();
19921                try {
19922                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19923                } catch (PackageManagerException e) {
19924                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19925                    try {
19926                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19927                                StorageManager.FLAG_STORAGE_CE, 0);
19928                    } catch (InstallerException e2) {
19929                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19930                    }
19931                }
19932            }
19933        }
19934        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19935            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19936            for (File file : files) {
19937                final String packageName = file.getName();
19938                try {
19939                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19940                } catch (PackageManagerException e) {
19941                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19942                    try {
19943                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19944                                StorageManager.FLAG_STORAGE_DE, 0);
19945                    } catch (InstallerException e2) {
19946                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19947                    }
19948                }
19949            }
19950        }
19951
19952        // Ensure that data directories are ready to roll for all packages
19953        // installed for this volume and user
19954        final List<PackageSetting> packages;
19955        synchronized (mPackages) {
19956            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19957        }
19958        int preparedCount = 0;
19959        for (PackageSetting ps : packages) {
19960            final String packageName = ps.name;
19961            if (ps.pkg == null) {
19962                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19963                // TODO: might be due to legacy ASEC apps; we should circle back
19964                // and reconcile again once they're scanned
19965                continue;
19966            }
19967
19968            if (ps.getInstalled(userId)) {
19969                prepareAppDataLIF(ps.pkg, userId, flags);
19970
19971                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19972                    // We may have just shuffled around app data directories, so
19973                    // prepare them one more time
19974                    prepareAppDataLIF(ps.pkg, userId, flags);
19975                }
19976
19977                preparedCount++;
19978            }
19979        }
19980
19981        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
19982    }
19983
19984    /**
19985     * Prepare app data for the given app just after it was installed or
19986     * upgraded. This method carefully only touches users that it's installed
19987     * for, and it forces a restorecon to handle any seinfo changes.
19988     * <p>
19989     * Verifies that directories exist and that ownership and labeling is
19990     * correct for all installed apps. If there is an ownership mismatch, it
19991     * will try recovering system apps by wiping data; third-party app data is
19992     * left intact.
19993     * <p>
19994     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19995     */
19996    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19997        final PackageSetting ps;
19998        synchronized (mPackages) {
19999            ps = mSettings.mPackages.get(pkg.packageName);
20000            mSettings.writeKernelMappingLPr(ps);
20001        }
20002
20003        final UserManager um = mContext.getSystemService(UserManager.class);
20004        UserManagerInternal umInternal = getUserManagerInternal();
20005        for (UserInfo user : um.getUsers()) {
20006            final int flags;
20007            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20008                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20009            } else if (umInternal.isUserRunning(user.id)) {
20010                flags = StorageManager.FLAG_STORAGE_DE;
20011            } else {
20012                continue;
20013            }
20014
20015            if (ps.getInstalled(user.id)) {
20016                // TODO: when user data is locked, mark that we're still dirty
20017                prepareAppDataLIF(pkg, user.id, flags);
20018            }
20019        }
20020    }
20021
20022    /**
20023     * Prepare app data for the given app.
20024     * <p>
20025     * Verifies that directories exist and that ownership and labeling is
20026     * correct for all installed apps. If there is an ownership mismatch, this
20027     * will try recovering system apps by wiping data; third-party app data is
20028     * left intact.
20029     */
20030    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
20031        if (pkg == null) {
20032            Slog.wtf(TAG, "Package was null!", new Throwable());
20033            return;
20034        }
20035        prepareAppDataLeafLIF(pkg, userId, flags);
20036        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20037        for (int i = 0; i < childCount; i++) {
20038            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
20039        }
20040    }
20041
20042    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20043        if (DEBUG_APP_DATA) {
20044            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
20045                    + Integer.toHexString(flags));
20046        }
20047
20048        final String volumeUuid = pkg.volumeUuid;
20049        final String packageName = pkg.packageName;
20050        final ApplicationInfo app = pkg.applicationInfo;
20051        final int appId = UserHandle.getAppId(app.uid);
20052
20053        Preconditions.checkNotNull(app.seinfo);
20054
20055        long ceDataInode = -1;
20056        try {
20057            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20058                    appId, app.seinfo, app.targetSdkVersion);
20059        } catch (InstallerException e) {
20060            if (app.isSystemApp()) {
20061                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20062                        + ", but trying to recover: " + e);
20063                destroyAppDataLeafLIF(pkg, userId, flags);
20064                try {
20065                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20066                            appId, app.seinfo, app.targetSdkVersion);
20067                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20068                } catch (InstallerException e2) {
20069                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
20070                }
20071            } else {
20072                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20073            }
20074        }
20075
20076        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
20077            // TODO: mark this structure as dirty so we persist it!
20078            synchronized (mPackages) {
20079                final PackageSetting ps = mSettings.mPackages.get(packageName);
20080                if (ps != null) {
20081                    ps.setCeDataInode(ceDataInode, userId);
20082                }
20083            }
20084        }
20085
20086        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20087    }
20088
20089    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20090        if (pkg == null) {
20091            Slog.wtf(TAG, "Package was null!", new Throwable());
20092            return;
20093        }
20094        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20095        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20096        for (int i = 0; i < childCount; i++) {
20097            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20098        }
20099    }
20100
20101    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20102        final String volumeUuid = pkg.volumeUuid;
20103        final String packageName = pkg.packageName;
20104        final ApplicationInfo app = pkg.applicationInfo;
20105
20106        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20107            // Create a native library symlink only if we have native libraries
20108            // and if the native libraries are 32 bit libraries. We do not provide
20109            // this symlink for 64 bit libraries.
20110            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20111                final String nativeLibPath = app.nativeLibraryDir;
20112                try {
20113                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20114                            nativeLibPath, userId);
20115                } catch (InstallerException e) {
20116                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20117                }
20118            }
20119        }
20120    }
20121
20122    /**
20123     * For system apps on non-FBE devices, this method migrates any existing
20124     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20125     * requested by the app.
20126     */
20127    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20128        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20129                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20130            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20131                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20132            try {
20133                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20134                        storageTarget);
20135            } catch (InstallerException e) {
20136                logCriticalInfo(Log.WARN,
20137                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20138            }
20139            return true;
20140        } else {
20141            return false;
20142        }
20143    }
20144
20145    public PackageFreezer freezePackage(String packageName, String killReason) {
20146        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20147    }
20148
20149    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20150        return new PackageFreezer(packageName, userId, killReason);
20151    }
20152
20153    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20154            String killReason) {
20155        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20156    }
20157
20158    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20159            String killReason) {
20160        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20161            return new PackageFreezer();
20162        } else {
20163            return freezePackage(packageName, userId, killReason);
20164        }
20165    }
20166
20167    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20168            String killReason) {
20169        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20170    }
20171
20172    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20173            String killReason) {
20174        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20175            return new PackageFreezer();
20176        } else {
20177            return freezePackage(packageName, userId, killReason);
20178        }
20179    }
20180
20181    /**
20182     * Class that freezes and kills the given package upon creation, and
20183     * unfreezes it upon closing. This is typically used when doing surgery on
20184     * app code/data to prevent the app from running while you're working.
20185     */
20186    private class PackageFreezer implements AutoCloseable {
20187        private final String mPackageName;
20188        private final PackageFreezer[] mChildren;
20189
20190        private final boolean mWeFroze;
20191
20192        private final AtomicBoolean mClosed = new AtomicBoolean();
20193        private final CloseGuard mCloseGuard = CloseGuard.get();
20194
20195        /**
20196         * Create and return a stub freezer that doesn't actually do anything,
20197         * typically used when someone requested
20198         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20199         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20200         */
20201        public PackageFreezer() {
20202            mPackageName = null;
20203            mChildren = null;
20204            mWeFroze = false;
20205            mCloseGuard.open("close");
20206        }
20207
20208        public PackageFreezer(String packageName, int userId, String killReason) {
20209            synchronized (mPackages) {
20210                mPackageName = packageName;
20211                mWeFroze = mFrozenPackages.add(mPackageName);
20212
20213                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20214                if (ps != null) {
20215                    killApplication(ps.name, ps.appId, userId, killReason);
20216                }
20217
20218                final PackageParser.Package p = mPackages.get(packageName);
20219                if (p != null && p.childPackages != null) {
20220                    final int N = p.childPackages.size();
20221                    mChildren = new PackageFreezer[N];
20222                    for (int i = 0; i < N; i++) {
20223                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20224                                userId, killReason);
20225                    }
20226                } else {
20227                    mChildren = null;
20228                }
20229            }
20230            mCloseGuard.open("close");
20231        }
20232
20233        @Override
20234        protected void finalize() throws Throwable {
20235            try {
20236                mCloseGuard.warnIfOpen();
20237                close();
20238            } finally {
20239                super.finalize();
20240            }
20241        }
20242
20243        @Override
20244        public void close() {
20245            mCloseGuard.close();
20246            if (mClosed.compareAndSet(false, true)) {
20247                synchronized (mPackages) {
20248                    if (mWeFroze) {
20249                        mFrozenPackages.remove(mPackageName);
20250                    }
20251
20252                    if (mChildren != null) {
20253                        for (PackageFreezer freezer : mChildren) {
20254                            freezer.close();
20255                        }
20256                    }
20257                }
20258            }
20259        }
20260    }
20261
20262    /**
20263     * Verify that given package is currently frozen.
20264     */
20265    private void checkPackageFrozen(String packageName) {
20266        synchronized (mPackages) {
20267            if (!mFrozenPackages.contains(packageName)) {
20268                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20269            }
20270        }
20271    }
20272
20273    @Override
20274    public int movePackage(final String packageName, final String volumeUuid) {
20275        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20276
20277        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20278        final int moveId = mNextMoveId.getAndIncrement();
20279        mHandler.post(new Runnable() {
20280            @Override
20281            public void run() {
20282                try {
20283                    movePackageInternal(packageName, volumeUuid, moveId, user);
20284                } catch (PackageManagerException e) {
20285                    Slog.w(TAG, "Failed to move " + packageName, e);
20286                    mMoveCallbacks.notifyStatusChanged(moveId,
20287                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20288                }
20289            }
20290        });
20291        return moveId;
20292    }
20293
20294    private void movePackageInternal(final String packageName, final String volumeUuid,
20295            final int moveId, UserHandle user) throws PackageManagerException {
20296        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20297        final PackageManager pm = mContext.getPackageManager();
20298
20299        final boolean currentAsec;
20300        final String currentVolumeUuid;
20301        final File codeFile;
20302        final String installerPackageName;
20303        final String packageAbiOverride;
20304        final int appId;
20305        final String seinfo;
20306        final String label;
20307        final int targetSdkVersion;
20308        final PackageFreezer freezer;
20309        final int[] installedUserIds;
20310
20311        // reader
20312        synchronized (mPackages) {
20313            final PackageParser.Package pkg = mPackages.get(packageName);
20314            final PackageSetting ps = mSettings.mPackages.get(packageName);
20315            if (pkg == null || ps == null) {
20316                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20317            }
20318
20319            if (pkg.applicationInfo.isSystemApp()) {
20320                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20321                        "Cannot move system application");
20322            }
20323
20324            if (pkg.applicationInfo.isExternalAsec()) {
20325                currentAsec = true;
20326                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20327            } else if (pkg.applicationInfo.isForwardLocked()) {
20328                currentAsec = true;
20329                currentVolumeUuid = "forward_locked";
20330            } else {
20331                currentAsec = false;
20332                currentVolumeUuid = ps.volumeUuid;
20333
20334                final File probe = new File(pkg.codePath);
20335                final File probeOat = new File(probe, "oat");
20336                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20337                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20338                            "Move only supported for modern cluster style installs");
20339                }
20340            }
20341
20342            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20343                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20344                        "Package already moved to " + volumeUuid);
20345            }
20346            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20347                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20348                        "Device admin cannot be moved");
20349            }
20350
20351            if (mFrozenPackages.contains(packageName)) {
20352                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20353                        "Failed to move already frozen package");
20354            }
20355
20356            codeFile = new File(pkg.codePath);
20357            installerPackageName = ps.installerPackageName;
20358            packageAbiOverride = ps.cpuAbiOverrideString;
20359            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20360            seinfo = pkg.applicationInfo.seinfo;
20361            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20362            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20363            freezer = freezePackage(packageName, "movePackageInternal");
20364            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20365        }
20366
20367        final Bundle extras = new Bundle();
20368        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20369        extras.putString(Intent.EXTRA_TITLE, label);
20370        mMoveCallbacks.notifyCreated(moveId, extras);
20371
20372        int installFlags;
20373        final boolean moveCompleteApp;
20374        final File measurePath;
20375
20376        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20377            installFlags = INSTALL_INTERNAL;
20378            moveCompleteApp = !currentAsec;
20379            measurePath = Environment.getDataAppDirectory(volumeUuid);
20380        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20381            installFlags = INSTALL_EXTERNAL;
20382            moveCompleteApp = false;
20383            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20384        } else {
20385            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20386            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20387                    || !volume.isMountedWritable()) {
20388                freezer.close();
20389                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20390                        "Move location not mounted private volume");
20391            }
20392
20393            Preconditions.checkState(!currentAsec);
20394
20395            installFlags = INSTALL_INTERNAL;
20396            moveCompleteApp = true;
20397            measurePath = Environment.getDataAppDirectory(volumeUuid);
20398        }
20399
20400        final PackageStats stats = new PackageStats(null, -1);
20401        synchronized (mInstaller) {
20402            for (int userId : installedUserIds) {
20403                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20404                    freezer.close();
20405                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20406                            "Failed to measure package size");
20407                }
20408            }
20409        }
20410
20411        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20412                + stats.dataSize);
20413
20414        final long startFreeBytes = measurePath.getFreeSpace();
20415        final long sizeBytes;
20416        if (moveCompleteApp) {
20417            sizeBytes = stats.codeSize + stats.dataSize;
20418        } else {
20419            sizeBytes = stats.codeSize;
20420        }
20421
20422        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20423            freezer.close();
20424            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20425                    "Not enough free space to move");
20426        }
20427
20428        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20429
20430        final CountDownLatch installedLatch = new CountDownLatch(1);
20431        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20432            @Override
20433            public void onUserActionRequired(Intent intent) throws RemoteException {
20434                throw new IllegalStateException();
20435            }
20436
20437            @Override
20438            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20439                    Bundle extras) throws RemoteException {
20440                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20441                        + PackageManager.installStatusToString(returnCode, msg));
20442
20443                installedLatch.countDown();
20444                freezer.close();
20445
20446                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20447                switch (status) {
20448                    case PackageInstaller.STATUS_SUCCESS:
20449                        mMoveCallbacks.notifyStatusChanged(moveId,
20450                                PackageManager.MOVE_SUCCEEDED);
20451                        break;
20452                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20453                        mMoveCallbacks.notifyStatusChanged(moveId,
20454                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20455                        break;
20456                    default:
20457                        mMoveCallbacks.notifyStatusChanged(moveId,
20458                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20459                        break;
20460                }
20461            }
20462        };
20463
20464        final MoveInfo move;
20465        if (moveCompleteApp) {
20466            // Kick off a thread to report progress estimates
20467            new Thread() {
20468                @Override
20469                public void run() {
20470                    while (true) {
20471                        try {
20472                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20473                                break;
20474                            }
20475                        } catch (InterruptedException ignored) {
20476                        }
20477
20478                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20479                        final int progress = 10 + (int) MathUtils.constrain(
20480                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20481                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20482                    }
20483                }
20484            }.start();
20485
20486            final String dataAppName = codeFile.getName();
20487            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20488                    dataAppName, appId, seinfo, targetSdkVersion);
20489        } else {
20490            move = null;
20491        }
20492
20493        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20494
20495        final Message msg = mHandler.obtainMessage(INIT_COPY);
20496        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20497        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20498                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20499                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20500        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20501        msg.obj = params;
20502
20503        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20504                System.identityHashCode(msg.obj));
20505        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20506                System.identityHashCode(msg.obj));
20507
20508        mHandler.sendMessage(msg);
20509    }
20510
20511    @Override
20512    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20513        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20514
20515        final int realMoveId = mNextMoveId.getAndIncrement();
20516        final Bundle extras = new Bundle();
20517        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20518        mMoveCallbacks.notifyCreated(realMoveId, extras);
20519
20520        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20521            @Override
20522            public void onCreated(int moveId, Bundle extras) {
20523                // Ignored
20524            }
20525
20526            @Override
20527            public void onStatusChanged(int moveId, int status, long estMillis) {
20528                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20529            }
20530        };
20531
20532        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20533        storage.setPrimaryStorageUuid(volumeUuid, callback);
20534        return realMoveId;
20535    }
20536
20537    @Override
20538    public int getMoveStatus(int moveId) {
20539        mContext.enforceCallingOrSelfPermission(
20540                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20541        return mMoveCallbacks.mLastStatus.get(moveId);
20542    }
20543
20544    @Override
20545    public void registerMoveCallback(IPackageMoveObserver callback) {
20546        mContext.enforceCallingOrSelfPermission(
20547                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20548        mMoveCallbacks.register(callback);
20549    }
20550
20551    @Override
20552    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20553        mContext.enforceCallingOrSelfPermission(
20554                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20555        mMoveCallbacks.unregister(callback);
20556    }
20557
20558    @Override
20559    public boolean setInstallLocation(int loc) {
20560        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20561                null);
20562        if (getInstallLocation() == loc) {
20563            return true;
20564        }
20565        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20566                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20567            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20568                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20569            return true;
20570        }
20571        return false;
20572   }
20573
20574    @Override
20575    public int getInstallLocation() {
20576        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20577                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20578                PackageHelper.APP_INSTALL_AUTO);
20579    }
20580
20581    /** Called by UserManagerService */
20582    void cleanUpUser(UserManagerService userManager, int userHandle) {
20583        synchronized (mPackages) {
20584            mDirtyUsers.remove(userHandle);
20585            mUserNeedsBadging.delete(userHandle);
20586            mSettings.removeUserLPw(userHandle);
20587            mPendingBroadcasts.remove(userHandle);
20588            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20589            removeUnusedPackagesLPw(userManager, userHandle);
20590        }
20591    }
20592
20593    /**
20594     * We're removing userHandle and would like to remove any downloaded packages
20595     * that are no longer in use by any other user.
20596     * @param userHandle the user being removed
20597     */
20598    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20599        final boolean DEBUG_CLEAN_APKS = false;
20600        int [] users = userManager.getUserIds();
20601        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20602        while (psit.hasNext()) {
20603            PackageSetting ps = psit.next();
20604            if (ps.pkg == null) {
20605                continue;
20606            }
20607            final String packageName = ps.pkg.packageName;
20608            // Skip over if system app
20609            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20610                continue;
20611            }
20612            if (DEBUG_CLEAN_APKS) {
20613                Slog.i(TAG, "Checking package " + packageName);
20614            }
20615            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20616            if (keep) {
20617                if (DEBUG_CLEAN_APKS) {
20618                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20619                }
20620            } else {
20621                for (int i = 0; i < users.length; i++) {
20622                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20623                        keep = true;
20624                        if (DEBUG_CLEAN_APKS) {
20625                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20626                                    + users[i]);
20627                        }
20628                        break;
20629                    }
20630                }
20631            }
20632            if (!keep) {
20633                if (DEBUG_CLEAN_APKS) {
20634                    Slog.i(TAG, "  Removing package " + packageName);
20635                }
20636                mHandler.post(new Runnable() {
20637                    public void run() {
20638                        deletePackageX(packageName, userHandle, 0);
20639                    } //end run
20640                });
20641            }
20642        }
20643    }
20644
20645    /** Called by UserManagerService */
20646    void createNewUser(int userId) {
20647        synchronized (mInstallLock) {
20648            mSettings.createNewUserLI(this, mInstaller, userId);
20649        }
20650        synchronized (mPackages) {
20651            scheduleWritePackageRestrictionsLocked(userId);
20652            scheduleWritePackageListLocked(userId);
20653            applyFactoryDefaultBrowserLPw(userId);
20654            primeDomainVerificationsLPw(userId);
20655        }
20656    }
20657
20658    void onNewUserCreated(final int userId) {
20659        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20660        // If permission review for legacy apps is required, we represent
20661        // dagerous permissions for such apps as always granted runtime
20662        // permissions to keep per user flag state whether review is needed.
20663        // Hence, if a new user is added we have to propagate dangerous
20664        // permission grants for these legacy apps.
20665        if (mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) {
20666            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20667                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20668        }
20669    }
20670
20671    @Override
20672    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20673        mContext.enforceCallingOrSelfPermission(
20674                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20675                "Only package verification agents can read the verifier device identity");
20676
20677        synchronized (mPackages) {
20678            return mSettings.getVerifierDeviceIdentityLPw();
20679        }
20680    }
20681
20682    @Override
20683    public void setPermissionEnforced(String permission, boolean enforced) {
20684        // TODO: Now that we no longer change GID for storage, this should to away.
20685        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20686                "setPermissionEnforced");
20687        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20688            synchronized (mPackages) {
20689                if (mSettings.mReadExternalStorageEnforced == null
20690                        || mSettings.mReadExternalStorageEnforced != enforced) {
20691                    mSettings.mReadExternalStorageEnforced = enforced;
20692                    mSettings.writeLPr();
20693                }
20694            }
20695            // kill any non-foreground processes so we restart them and
20696            // grant/revoke the GID.
20697            final IActivityManager am = ActivityManagerNative.getDefault();
20698            if (am != null) {
20699                final long token = Binder.clearCallingIdentity();
20700                try {
20701                    am.killProcessesBelowForeground("setPermissionEnforcement");
20702                } catch (RemoteException e) {
20703                } finally {
20704                    Binder.restoreCallingIdentity(token);
20705                }
20706            }
20707        } else {
20708            throw new IllegalArgumentException("No selective enforcement for " + permission);
20709        }
20710    }
20711
20712    @Override
20713    @Deprecated
20714    public boolean isPermissionEnforced(String permission) {
20715        return true;
20716    }
20717
20718    @Override
20719    public boolean isStorageLow() {
20720        final long token = Binder.clearCallingIdentity();
20721        try {
20722            final DeviceStorageMonitorInternal
20723                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20724            if (dsm != null) {
20725                return dsm.isMemoryLow();
20726            } else {
20727                return false;
20728            }
20729        } finally {
20730            Binder.restoreCallingIdentity(token);
20731        }
20732    }
20733
20734    @Override
20735    public IPackageInstaller getPackageInstaller() {
20736        return mInstallerService;
20737    }
20738
20739    private boolean userNeedsBadging(int userId) {
20740        int index = mUserNeedsBadging.indexOfKey(userId);
20741        if (index < 0) {
20742            final UserInfo userInfo;
20743            final long token = Binder.clearCallingIdentity();
20744            try {
20745                userInfo = sUserManager.getUserInfo(userId);
20746            } finally {
20747                Binder.restoreCallingIdentity(token);
20748            }
20749            final boolean b;
20750            if (userInfo != null && userInfo.isManagedProfile()) {
20751                b = true;
20752            } else {
20753                b = false;
20754            }
20755            mUserNeedsBadging.put(userId, b);
20756            return b;
20757        }
20758        return mUserNeedsBadging.valueAt(index);
20759    }
20760
20761    @Override
20762    public KeySet getKeySetByAlias(String packageName, String alias) {
20763        if (packageName == null || alias == null) {
20764            return null;
20765        }
20766        synchronized(mPackages) {
20767            final PackageParser.Package pkg = mPackages.get(packageName);
20768            if (pkg == null) {
20769                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20770                throw new IllegalArgumentException("Unknown package: " + packageName);
20771            }
20772            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20773            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20774        }
20775    }
20776
20777    @Override
20778    public KeySet getSigningKeySet(String packageName) {
20779        if (packageName == null) {
20780            return null;
20781        }
20782        synchronized(mPackages) {
20783            final PackageParser.Package pkg = mPackages.get(packageName);
20784            if (pkg == null) {
20785                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20786                throw new IllegalArgumentException("Unknown package: " + packageName);
20787            }
20788            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20789                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20790                throw new SecurityException("May not access signing KeySet of other apps.");
20791            }
20792            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20793            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20794        }
20795    }
20796
20797    @Override
20798    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20799        if (packageName == null || ks == null) {
20800            return false;
20801        }
20802        synchronized(mPackages) {
20803            final PackageParser.Package pkg = mPackages.get(packageName);
20804            if (pkg == null) {
20805                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20806                throw new IllegalArgumentException("Unknown package: " + packageName);
20807            }
20808            IBinder ksh = ks.getToken();
20809            if (ksh instanceof KeySetHandle) {
20810                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20811                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20812            }
20813            return false;
20814        }
20815    }
20816
20817    @Override
20818    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20819        if (packageName == null || ks == null) {
20820            return false;
20821        }
20822        synchronized(mPackages) {
20823            final PackageParser.Package pkg = mPackages.get(packageName);
20824            if (pkg == null) {
20825                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20826                throw new IllegalArgumentException("Unknown package: " + packageName);
20827            }
20828            IBinder ksh = ks.getToken();
20829            if (ksh instanceof KeySetHandle) {
20830                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20831                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20832            }
20833            return false;
20834        }
20835    }
20836
20837    private void deletePackageIfUnusedLPr(final String packageName) {
20838        PackageSetting ps = mSettings.mPackages.get(packageName);
20839        if (ps == null) {
20840            return;
20841        }
20842        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20843            // TODO Implement atomic delete if package is unused
20844            // It is currently possible that the package will be deleted even if it is installed
20845            // after this method returns.
20846            mHandler.post(new Runnable() {
20847                public void run() {
20848                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20849                }
20850            });
20851        }
20852    }
20853
20854    /**
20855     * Check and throw if the given before/after packages would be considered a
20856     * downgrade.
20857     */
20858    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20859            throws PackageManagerException {
20860        if (after.versionCode < before.mVersionCode) {
20861            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20862                    "Update version code " + after.versionCode + " is older than current "
20863                    + before.mVersionCode);
20864        } else if (after.versionCode == before.mVersionCode) {
20865            if (after.baseRevisionCode < before.baseRevisionCode) {
20866                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20867                        "Update base revision code " + after.baseRevisionCode
20868                        + " is older than current " + before.baseRevisionCode);
20869            }
20870
20871            if (!ArrayUtils.isEmpty(after.splitNames)) {
20872                for (int i = 0; i < after.splitNames.length; i++) {
20873                    final String splitName = after.splitNames[i];
20874                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20875                    if (j != -1) {
20876                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20877                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20878                                    "Update split " + splitName + " revision code "
20879                                    + after.splitRevisionCodes[i] + " is older than current "
20880                                    + before.splitRevisionCodes[j]);
20881                        }
20882                    }
20883                }
20884            }
20885        }
20886    }
20887
20888    private static class MoveCallbacks extends Handler {
20889        private static final int MSG_CREATED = 1;
20890        private static final int MSG_STATUS_CHANGED = 2;
20891
20892        private final RemoteCallbackList<IPackageMoveObserver>
20893                mCallbacks = new RemoteCallbackList<>();
20894
20895        private final SparseIntArray mLastStatus = new SparseIntArray();
20896
20897        public MoveCallbacks(Looper looper) {
20898            super(looper);
20899        }
20900
20901        public void register(IPackageMoveObserver callback) {
20902            mCallbacks.register(callback);
20903        }
20904
20905        public void unregister(IPackageMoveObserver callback) {
20906            mCallbacks.unregister(callback);
20907        }
20908
20909        @Override
20910        public void handleMessage(Message msg) {
20911            final SomeArgs args = (SomeArgs) msg.obj;
20912            final int n = mCallbacks.beginBroadcast();
20913            for (int i = 0; i < n; i++) {
20914                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20915                try {
20916                    invokeCallback(callback, msg.what, args);
20917                } catch (RemoteException ignored) {
20918                }
20919            }
20920            mCallbacks.finishBroadcast();
20921            args.recycle();
20922        }
20923
20924        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20925                throws RemoteException {
20926            switch (what) {
20927                case MSG_CREATED: {
20928                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20929                    break;
20930                }
20931                case MSG_STATUS_CHANGED: {
20932                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20933                    break;
20934                }
20935            }
20936        }
20937
20938        private void notifyCreated(int moveId, Bundle extras) {
20939            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20940
20941            final SomeArgs args = SomeArgs.obtain();
20942            args.argi1 = moveId;
20943            args.arg2 = extras;
20944            obtainMessage(MSG_CREATED, args).sendToTarget();
20945        }
20946
20947        private void notifyStatusChanged(int moveId, int status) {
20948            notifyStatusChanged(moveId, status, -1);
20949        }
20950
20951        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20952            Slog.v(TAG, "Move " + moveId + " status " + status);
20953
20954            final SomeArgs args = SomeArgs.obtain();
20955            args.argi1 = moveId;
20956            args.argi2 = status;
20957            args.arg3 = estMillis;
20958            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20959
20960            synchronized (mLastStatus) {
20961                mLastStatus.put(moveId, status);
20962            }
20963        }
20964    }
20965
20966    private final static class OnPermissionChangeListeners extends Handler {
20967        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20968
20969        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20970                new RemoteCallbackList<>();
20971
20972        public OnPermissionChangeListeners(Looper looper) {
20973            super(looper);
20974        }
20975
20976        @Override
20977        public void handleMessage(Message msg) {
20978            switch (msg.what) {
20979                case MSG_ON_PERMISSIONS_CHANGED: {
20980                    final int uid = msg.arg1;
20981                    handleOnPermissionsChanged(uid);
20982                } break;
20983            }
20984        }
20985
20986        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20987            mPermissionListeners.register(listener);
20988
20989        }
20990
20991        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20992            mPermissionListeners.unregister(listener);
20993        }
20994
20995        public void onPermissionsChanged(int uid) {
20996            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20997                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20998            }
20999        }
21000
21001        private void handleOnPermissionsChanged(int uid) {
21002            final int count = mPermissionListeners.beginBroadcast();
21003            try {
21004                for (int i = 0; i < count; i++) {
21005                    IOnPermissionsChangeListener callback = mPermissionListeners
21006                            .getBroadcastItem(i);
21007                    try {
21008                        callback.onPermissionsChanged(uid);
21009                    } catch (RemoteException e) {
21010                        Log.e(TAG, "Permission listener is dead", e);
21011                    }
21012                }
21013            } finally {
21014                mPermissionListeners.finishBroadcast();
21015            }
21016        }
21017    }
21018
21019    private class PackageManagerInternalImpl extends PackageManagerInternal {
21020        @Override
21021        public void setLocationPackagesProvider(PackagesProvider provider) {
21022            synchronized (mPackages) {
21023                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
21024            }
21025        }
21026
21027        @Override
21028        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
21029            synchronized (mPackages) {
21030                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
21031            }
21032        }
21033
21034        @Override
21035        public void setSmsAppPackagesProvider(PackagesProvider provider) {
21036            synchronized (mPackages) {
21037                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
21038            }
21039        }
21040
21041        @Override
21042        public void setDialerAppPackagesProvider(PackagesProvider provider) {
21043            synchronized (mPackages) {
21044                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21045            }
21046        }
21047
21048        @Override
21049        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21050            synchronized (mPackages) {
21051                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21052            }
21053        }
21054
21055        @Override
21056        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21057            synchronized (mPackages) {
21058                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21059            }
21060        }
21061
21062        @Override
21063        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21064            synchronized (mPackages) {
21065                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21066                        packageName, userId);
21067            }
21068        }
21069
21070        @Override
21071        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21072            synchronized (mPackages) {
21073                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21074                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21075                        packageName, userId);
21076            }
21077        }
21078
21079        @Override
21080        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21081            synchronized (mPackages) {
21082                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21083                        packageName, userId);
21084            }
21085        }
21086
21087        @Override
21088        public void setKeepUninstalledPackages(final List<String> packageList) {
21089            Preconditions.checkNotNull(packageList);
21090            List<String> removedFromList = null;
21091            synchronized (mPackages) {
21092                if (mKeepUninstalledPackages != null) {
21093                    final int packagesCount = mKeepUninstalledPackages.size();
21094                    for (int i = 0; i < packagesCount; i++) {
21095                        String oldPackage = mKeepUninstalledPackages.get(i);
21096                        if (packageList != null && packageList.contains(oldPackage)) {
21097                            continue;
21098                        }
21099                        if (removedFromList == null) {
21100                            removedFromList = new ArrayList<>();
21101                        }
21102                        removedFromList.add(oldPackage);
21103                    }
21104                }
21105                mKeepUninstalledPackages = new ArrayList<>(packageList);
21106                if (removedFromList != null) {
21107                    final int removedCount = removedFromList.size();
21108                    for (int i = 0; i < removedCount; i++) {
21109                        deletePackageIfUnusedLPr(removedFromList.get(i));
21110                    }
21111                }
21112            }
21113        }
21114
21115        @Override
21116        public boolean isPermissionsReviewRequired(String packageName, int userId) {
21117            synchronized (mPackages) {
21118                // If we do not support permission review, done.
21119                if (!mPermissionReviewRequired && !Build.PERMISSIONS_REVIEW_REQUIRED) {
21120                    return false;
21121                }
21122
21123                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21124                if (packageSetting == null) {
21125                    return false;
21126                }
21127
21128                // Permission review applies only to apps not supporting the new permission model.
21129                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21130                    return false;
21131                }
21132
21133                // Legacy apps have the permission and get user consent on launch.
21134                PermissionsState permissionsState = packageSetting.getPermissionsState();
21135                return permissionsState.isPermissionReviewRequired(userId);
21136            }
21137        }
21138
21139        @Override
21140        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21141            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21142        }
21143
21144        @Override
21145        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21146                int userId) {
21147            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21148        }
21149
21150        @Override
21151        public void setDeviceAndProfileOwnerPackages(
21152                int deviceOwnerUserId, String deviceOwnerPackage,
21153                SparseArray<String> profileOwnerPackages) {
21154            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21155                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21156        }
21157
21158        @Override
21159        public boolean isPackageDataProtected(int userId, String packageName) {
21160            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21161        }
21162
21163        @Override
21164        public boolean wasPackageEverLaunched(String packageName, int userId) {
21165            synchronized (mPackages) {
21166                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21167            }
21168        }
21169    }
21170
21171    @Override
21172    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21173        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21174        synchronized (mPackages) {
21175            final long identity = Binder.clearCallingIdentity();
21176            try {
21177                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21178                        packageNames, userId);
21179            } finally {
21180                Binder.restoreCallingIdentity(identity);
21181            }
21182        }
21183    }
21184
21185    @Override
21186    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
21187        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
21188        synchronized (mPackages) {
21189            final long identity = Binder.clearCallingIdentity();
21190            try {
21191                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
21192                        packageNames, userId);
21193            } finally {
21194                Binder.restoreCallingIdentity(identity);
21195            }
21196        }
21197    }
21198
21199    private static void enforceSystemOrPhoneCaller(String tag) {
21200        int callingUid = Binder.getCallingUid();
21201        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21202            throw new SecurityException(
21203                    "Cannot call " + tag + " from UID " + callingUid);
21204        }
21205    }
21206
21207    boolean isHistoricalPackageUsageAvailable() {
21208        return mPackageUsage.isHistoricalPackageUsageAvailable();
21209    }
21210
21211    /**
21212     * Return a <b>copy</b> of the collection of packages known to the package manager.
21213     * @return A copy of the values of mPackages.
21214     */
21215    Collection<PackageParser.Package> getPackages() {
21216        synchronized (mPackages) {
21217            return new ArrayList<>(mPackages.values());
21218        }
21219    }
21220
21221    /**
21222     * Logs process start information (including base APK hash) to the security log.
21223     * @hide
21224     */
21225    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21226            String apkFile, int pid) {
21227        if (!SecurityLog.isLoggingEnabled()) {
21228            return;
21229        }
21230        Bundle data = new Bundle();
21231        data.putLong("startTimestamp", System.currentTimeMillis());
21232        data.putString("processName", processName);
21233        data.putInt("uid", uid);
21234        data.putString("seinfo", seinfo);
21235        data.putString("apkFile", apkFile);
21236        data.putInt("pid", pid);
21237        Message msg = mProcessLoggingHandler.obtainMessage(
21238                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21239        msg.setData(data);
21240        mProcessLoggingHandler.sendMessage(msg);
21241    }
21242
21243    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21244        return mCompilerStats.getPackageStats(pkgName);
21245    }
21246
21247    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21248        return getOrCreateCompilerPackageStats(pkg.packageName);
21249    }
21250
21251    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21252        return mCompilerStats.getOrCreatePackageStats(pkgName);
21253    }
21254
21255    public void deleteCompilerPackageStats(String pkgName) {
21256        mCompilerStats.deletePackageStats(pkgName);
21257    }
21258}
21259